text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Update test to reflect renamed 'js' and 'css' dirs
|
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('bespoke generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('bespoke:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'package.json',
'bower.json',
'Gruntfile.js',
'.gitignore',
'.jshintrc',
'.bowerrc',
'src/index.jade',
'src/scripts/main.js',
'src/styles/main.styl'
];
helpers.mockPrompt(this.app, {
'title': 'Foo Bar',
'bullets': 'Y',
'hash': 'Y'
});
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
|
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('bespoke generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('bespoke:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'package.json',
'bower.json',
'Gruntfile.js',
'.gitignore',
'.jshintrc',
'.bowerrc',
'src/index.jade',
'src/js/js.js',
'src/css/css.styl'
];
helpers.mockPrompt(this.app, {
'title': 'Foo Bar',
'bullets': 'Y',
'hash': 'Y'
});
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
|
Use more standard package name django-partner-feeds
|
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-partner-feeds',
version=__import__('partner_feeds').__version__,
author_email='ATMOprogrammers@theatlantic.com',
packages=find_packages(),
url='https://github.com/theatlantic/django-partner-feeds',
description='Consume partner RSS or ATOM feeds',
long_description=open('README.rst').read(),
include_package_data=True,
install_requires=[
"Django >= 1.2",
"celery >= 2.1.4",
"django-celery >= 2.1.4",
"feedparser >= 5",
"timelib",
],
)
|
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='Partner Feeds',
version=__import__('partner_feeds').__version__,
author_email='ATMOprogrammers@theatlantic.com',
packages=find_packages(),
url='https://github.com/theatlantic/django-partner-feeds',
description='Consume partner RSS or ATOM feeds',
long_description=open('README.rst').read(),
include_package_data=True,
install_requires=[
"Django >= 1.2",
"celery >= 2.1.4",
"django-celery >= 2.1.4",
"feedparser >= 5",
"timelib",
],
)
|
Allow POST on settings too
|
package disallow
import (
"net/http"
"github.com/rancher/apiserver/pkg/types"
"github.com/rancher/steve/pkg/attributes"
schema2 "github.com/rancher/steve/pkg/schema"
steve "github.com/rancher/steve/pkg/server"
)
var (
allowPost = map[string]bool{
"settings": true,
}
allowPut = map[string]bool{
"features": true,
"settings": true,
}
)
func Register(server *steve.Server) {
server.SchemaFactory.AddTemplate(schema2.Template{
Customize: func(schema *types.APISchema) {
gr := attributes.GR(schema)
if gr.Group == "management.cattle.io" || gr.Group == "project.cattle.io" {
attributes.AddDisallowMethods(schema,
http.MethodPatch,
http.MethodDelete)
if !allowPut[gr.Resource] {
attributes.AddDisallowMethods(schema, http.MethodPut)
}
if !allowPut[gr.Resource] {
attributes.AddDisallowMethods(schema, http.MethodPost)
}
}
},
})
}
|
package disallow
import (
"net/http"
"github.com/rancher/apiserver/pkg/types"
"github.com/rancher/steve/pkg/attributes"
schema2 "github.com/rancher/steve/pkg/schema"
steve "github.com/rancher/steve/pkg/server"
)
var (
allowPut = map[string]bool{
"features": true,
"settings": true,
}
)
func Register(server *steve.Server) {
server.SchemaFactory.AddTemplate(schema2.Template{
Customize: func(schema *types.APISchema) {
gr := attributes.GR(schema)
if gr.Group == "management.cattle.io" || gr.Group == "project.cattle.io" {
attributes.AddDisallowMethods(schema,
http.MethodPost,
http.MethodPatch,
http.MethodDelete)
if !allowPut[gr.Resource] {
attributes.AddDisallowMethods(schema, http.MethodPut)
}
}
},
})
}
|
Fix bug that prevents `yo incubator` from working
|
"use strict";
var yeoman = require("yeoman-generator");
var incSay = require("incubator-say");
var util = require("util");
var path = require("path");
var IncubatorGenerator = module.exports = function IncubatorGenerator () {
yeoman.generators.Base.apply(this, arguments);
this.argument("appname", { type : String, required : false });
this.appname = this.appname || path.basename(process.cwd());
this.appname = this._.camelize(this._.slugify(this._.humanize(this.appname)));
this.option("skip-welcome-message", {
desc : "Do not print out the welcome message.",
type : Boolean,
defaults : false
});
this.option("skip-core", {
desc : "Skip core installation.",
type : Boolean,
defaults : false
});
};
util.inherits(IncubatorGenerator, yeoman.generators.Base);
IncubatorGenerator.prototype.greeting = function () {
if (!this.options["skip-welcome-message"]) {
this.log(incSay("Welcome to the Incubator Generator!"));
this.log("By default I will create a Gruntfile and all dotfiles required to work");
this.log("with the Bandwidth Incubator build pipeline.");
this.log();
}
};
IncubatorGenerator.prototype.components = function () {
if (!this.options["skip-core"]) {
this.invoke("incubator:core", this.args);
}
};
|
"use strict";
var yeoman = require("yeoman-generator");
var incSay = require("incubator-say");
var util = require("util");
var path = require("path");
var IncubatorGenerator = module.exports = function IncubatorGenerator (args) {
yeoman.generators.Base.apply(this, arguments);
this.argument("appname", { type : String, required : false });
this.appname = this.appname || path.basename(process.cwd());
this.appname = this._.camelize(this._.slugify(this._.humanize(this.appname)));
this.option("skip-welcome-message", {
desc : "Do not print out the welcome message.",
type : Boolean,
defaults : true
});
this.option("skip-core", {
desc : "Skip core installation.",
type : Boolean,
defaults : true
});
if (!this.options["skip-welcome-message"]) {
this.log(incSay("Welcome to the Incubator Generator!"));
this.log("By default I will create a Gruntfile and all dotfiles required to work");
this.log("with the Bandwidth Incubator build pipeline.");
this.log();
}
if (!this.options["skip-core"]) {
this.invoke("incubator:core", args);
}
};
util.inherits(IncubatorGenerator, yeoman.generators.Base);
|
Sort the list of meeting series by last change descending
|
import { MeetingSeries } from '/imports/meetingseries'
import { Minutes } from '/imports/minutes'
Template.meetingSeriesList.onRendered(function () {
});
Template.meetingSeriesList.onCreated(function () {
});
Template.meetingSeriesList.helpers({
meetingSeriesRow: function () {
return MeetingSeries.find({}, {sort: {lastChange: -1}});
}
});
Template.meetingSeriesList.events({
"click .hidehelp": function () {
$(".help").hide(); // use jQuery to find and hide class
},
"click #deleteMeetingSeries": function() {
console.log("Remove Meeting Series"+this._id);
if (confirm("Do you really want to delete this meeting series?")) {
MeetingSeries.remove(this._id);
}
}
});
|
import { MeetingSeries } from '/imports/meetingseries'
import { Minutes } from '/imports/minutes'
Template.meetingSeriesList.onRendered(function () {
});
Template.meetingSeriesList.onCreated(function () {
});
Template.meetingSeriesList.helpers({
meetingSeriesRow: function () {
return MeetingSeries.find({}, {sort: {createdAt: -1}});
}
});
Template.meetingSeriesList.events({
"click .hidehelp": function () {
$(".help").hide(); // use jQuery to find and hide class
},
"click #deleteMeetingSeries": function() {
console.log("Remove Meeting Series"+this._id);
if (confirm("Do you really want to delete this meeting series?")) {
MeetingSeries.remove(this._id);
}
}
});
|
Fix add live promise problem
|
import { GraphQLBoolean, GraphQLString } from 'graphql';
import { createClient } from 'redis';
import { redisUrl } from '../../config';
const startLive = {
type: GraphQLBoolean,
args: {
id: { type: GraphQLString },
},
async resolve(fieldName, { id }, context, { rootValue: request }) {
const addLivePromise = new Promise((resolve, reject) => {
if (!request.user) {
resolve(false);
}
const redis = createClient(redisUrl);
redis.rpush('live', id, (err, reply) => {
redis.quit();
if (!err) {
resolve(true);
} else {
reject(err);
}
});
});
return await addLivePromise;
}
};
export default startLive;
|
import { GraphQLBoolean, GraphQLString } from 'graphql';
import { createClient } from 'redis';
import { redisUrl } from '../../config';
const startLive = {
type: GraphQLBoolean,
args: {
id: { type: GraphQLString },
},
resolve(fieldName, { id }, context, { rootValue: request }) {
return new Promise((resolve, reject) => {
if (!request.user) {
resolve(false);
}
const redis = createClient(redisUrl);
redis.rpush('live', id, (err, reply) => {
if (!err) {
resolve(true);
} else {
reject(err);
}
redis.quit();
});
});
}
};
export default startLive;
|
Fix not opening paths with spaces.
|
#!/usr/bin/env python3
import os
import sys
import neovim
files = [os.path.abspath(arg) for arg in sys.argv[1:]]
if not files:
sys.exit(1)
addr = os.environ.get('NVIM_LISTEN_ADDRESS', None)
if not addr:
os.execvp('nvim', files)
nvim = neovim.attach('socket', path=addr)
tbuf = nvim.current.buffer
for fname in files:
fname = nvim.eval('fnameescape("{}")'.format(fname)).decode('utf-8')
nvim.command('drop {}'.format(fname))
nvim.command('autocmd BufUnload <buffer> silent! call rpcnotify({}, "m")'
.format(nvim.channel_id))
while files:
try:
nvim.session.next_message()
except:
pass
files.pop()
nvim.current.buffer = tbuf
nvim.input('i')
|
#!/usr/bin/env python3
import os
import sys
import neovim
files = {os.path.abspath(arg) for arg in sys.argv[1:]}
if not files:
sys.exit(1)
addr = os.environ.get('NVIM_LISTEN_ADDRESS', None)
if not addr:
os.execvp('nvim', files)
nvim = neovim.attach('socket', path=addr)
tbuf = nvim.current.buffer
for fname in files:
nvim.command('drop {}'.format(fname))
nvim.command('autocmd BufUnload <buffer> silent! call rpcnotify({}, "m")'
.format(nvim.channel_id))
while files:
try:
nvim.session.next_message()
except:
pass
files.pop()
nvim.current.buffer = tbuf
nvim.input('i')
|
fabric: Use sudo() function for db migration call
|
from fabric.api import env, local, cd, run, settings, sudo
env.use_ssh_config = True
env.hosts = ['root@skylines']
def deploy(branch='master', force=False):
push(branch, force)
restart()
def push(branch='master', force=False):
cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch)
if force:
cmd += ' --force'
local(cmd)
def restart():
with cd('/opt/skylines/src'):
run('git reset --hard')
# compile i18n .mo files
run('./manage.py babel compile')
# generate JS/CSS assets
run('./manage.py assets build')
# do database migrations
with settings(sudo_user='skylines'):
sudo('./manage.py migrate upgrade')
# restart services
restart_service('skylines-fastcgi')
restart_service('mapserver-fastcgi')
restart_service('skylines-daemon')
restart_service('celery-daemon')
def restart_service(service):
run('sv restart ' + service)
|
from fabric.api import env, local, cd, run
env.use_ssh_config = True
env.hosts = ['root@skylines']
def deploy(branch='master', force=False):
push(branch, force)
restart()
def push(branch='master', force=False):
cmd = 'git push %s:/opt/skylines/src/ %s:master' % (env.host_string, branch)
if force:
cmd += ' --force'
local(cmd)
def restart():
with cd('/opt/skylines/src'):
run('git reset --hard')
# compile i18n .mo files
run('./manage.py babel compile')
# generate JS/CSS assets
run('./manage.py assets build')
# do database migrations
run('sudo -u skylines ./manage.py migrate upgrade')
# restart services
restart_service('skylines-fastcgi')
restart_service('mapserver-fastcgi')
restart_service('skylines-daemon')
restart_service('celery-daemon')
def restart_service(service):
run('sv restart ' + service)
|
Add check for null parameter
|
/*
* Copyright (c) 2016 EMC Corporation. All Rights Reserved.
*/
package com.emc.ia.sdk.support.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.function.Supplier;
import org.apache.commons.io.IOUtils;
/**
* Provide repeatable access to the same {@linkplain InputStream} by caching it in memory.
*/
public class RepeatableInputStream implements Supplier<InputStream> {
private final ByteArrayInputOutputStream provider = new ByteArrayInputOutputStream();
/**
* Provide repeatable access to the given input stream.
* @param source The input stream to make available for repeated access. Must not be <code>null</code>
* @throws IOException When an I/O error occurs
*/
public RepeatableInputStream(InputStream source) throws IOException {
IOUtils.copy(Objects.requireNonNull(source), provider);
}
@Override
public InputStream get() {
return provider.getInputStream();
}
}
|
/*
* Copyright (c) 2016 EMC Corporation. All Rights Reserved.
*/
package com.emc.ia.sdk.support.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Supplier;
import org.apache.commons.io.IOUtils;
/**
* Provide repeatable access to the same {@linkplain InputStream} by caching it in memory.
*/
public class RepeatableInputStream implements Supplier<InputStream> {
private final ByteArrayInputOutputStream provider = new ByteArrayInputOutputStream();
/**
* Provide repeatable access to the given input stream.
* @param source The input stream to make available for repeated access
* @throws IOException When an I/O error occurs
*/
public RepeatableInputStream(InputStream source) throws IOException {
IOUtils.copy(source, provider);
}
@Override
public InputStream get() {
return provider.getInputStream();
}
}
|
Extend visualisation period until end of 2015
|
var moment = require('moment');
// NOTE: month indices are zero-based
module.exports.DATA_START_YEAR = 2012;
module.exports.DATA_START_MONTH = 0;
module.exports.DATA_START_MOMENT = moment([
module.exports.DATA_START_YEAR,
module.exports.DATA_START_MONTH]).startOf('month');
module.exports.DATA_END_YEAR = 2015;
module.exports.DATA_END_MONTH = 11;
module.exports.DATA_END_MOMENT = moment([
module.exports.DATA_END_YEAR,
module.exports.DATA_END_MONTH]).endOf('month');
module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 1, 5]);
module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN'];
module.exports.fullRange = [module.exports.DATA_START_MOMENT.unix(), module.exports.DATA_END_MOMENT.unix()];
module.exports.labelShowBreakPoint = 992;
|
var moment = require('moment');
// NOTE: month indices are zero-based
module.exports.DATA_START_YEAR = 2012;
module.exports.DATA_START_MONTH = 0;
module.exports.DATA_START_MOMENT = moment([
module.exports.DATA_START_YEAR,
module.exports.DATA_START_MONTH]).startOf('month');
module.exports.DATA_END_YEAR = 2015;
module.exports.DATA_END_MONTH = 10;
module.exports.DATA_END_MOMENT = moment([
module.exports.DATA_END_YEAR,
module.exports.DATA_END_MONTH]).endOf('month');
module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 1, 5]);
module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN'];
module.exports.fullRange = [module.exports.DATA_START_MOMENT.unix(), module.exports.DATA_END_MOMENT.unix()];
module.exports.labelShowBreakPoint = 992;
|
Resolve files from the /es folder instead of /src
|
import { resolve } from 'path';
import { removeStartSlash } from './common';
export const rootDirectory = resolve(__dirname, '../../..');
/**
* Resolves a file in the root directory of the project using the framework.
*
* @param fileName - The name of the file to resolve.
* @returns The path of the file.
*/
export function resolveProject(fileName: string): string {
return resolve(process.cwd(), removeStartSlash(fileName));
}
/**
* Resolves a file in the root directory of the framework.
*
* @param fileName - The name of the file to resolve.
* @returns The path of the file.
*/
export function resolveRoot(fileName: string = ''): string {
return resolve(rootDirectory, removeStartSlash(fileName));
}
/**
* Resolves a file in the root directory of source of the framework (.build or framework).
*
* @param fileName - The name of the file to resolve.
* @returns The path of the file.
*/
export function resolveFrameworkSource(fileName: string): string {
return resolve(rootDirectory, 'es/framework', removeStartSlash(fileName));
}
|
import { resolve } from 'path';
import { removeStartSlash } from './common';
export const rootDirectory = resolve(__dirname, '../../..');
/**
* Resolves a file in the root directory of the project using the framework.
*
* @param fileName - The name of the file to resolve.
* @returns The path of the file.
*/
export function resolveProject(fileName: string): string {
return resolve(process.cwd(), removeStartSlash(fileName));
}
/**
* Resolves a file in the root directory of the framework.
*
* @param fileName - The name of the file to resolve.
* @returns The path of the file.
*/
export function resolveRoot(fileName: string = ''): string {
return resolve(rootDirectory, removeStartSlash(fileName));
}
/**
* Resolves a file in the root directory of source of the framework (.build or framework).
*
* @param fileName - The name of the file to resolve.
* @returns The path of the file.
*/
export function resolveFrameworkSource(fileName: string): string {
return resolve(rootDirectory, 'src/framework', removeStartSlash(fileName));
}
|
Apply changes in FOSS because of prioprietary merges
|
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.utils.exception;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionUtil {
public static String toString(Throwable th) {
return toString(th, true);
}
public static String toString(Throwable th, boolean printStack) {
final StringWriter writer = new StringWriter();
writer.append("Exception: " + th.getClass().getName() + "\n");
writer.append("Message: ");
writer.append(th.getMessage()).append("\n");
if(printStack) {
writer.append("Stack: ");
th.printStackTrace(new PrintWriter(writer));
}
return writer.toString();
}
}
|
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.utils.exception;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionUtil {
public static String toString(Throwable th) {
final StringWriter writer = new StringWriter();
writer.append("Exception: " + th.getClass().getName() + "\n");
writer.append("Message: ");
writer.append(th.getMessage());
writer.append("\n Stack: ");
th.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
}
|
Add `parse_value` test for AppleScript dates
Added a test case to `parse_value` to parse dates returned in
AppleScript responses.
|
"""
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
|
"""
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from itunes.itunes import parse_value
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
|
fix: Remove index argument while creating order products sample
|
# importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create a sample of prior orders
orders_df = pd.read_csv("Data/orders.csv")
s = round(3214874 * 0.1)
i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s))
orders_df.loc[i,:].to_csv("Data/orders_prior_sample.csv", index = False)
# create a sample of train orders
s = round(131209 * 0.1)
j = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="train"].index), s))
orders_df.loc[j,:].to_csv("Data/orders_train_sample.csv", index = False)
# create a sample of prior order products
order_products_prior_df = pd.read_csv('Data/order_products__prior.csv', index_col = 'order_id')
order_products_prior_df.loc[orders_df.loc[i,:]['order_id'],:].to_csv("Data/order_products_prior_sample.csv")
# create a sample of train order products
order_products_train_df = pd.read_csv('Data/order_products__train.csv', index_col = 'order_id')
order_products_train_df.loc[orders_df.loc[j,:]['order_id'],:].to_csv("Data/order_products_train_sample.csv")
|
# importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create a sample of prior orders
orders_df = pd.read_csv("Data/orders.csv")
s = round(3214874 * 0.1)
i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s))
orders_df.loc[i,:].to_csv("Data/orders_prior_sample.csv", index = False)
# create a sample of train orders
s = round(131209 * 0.1)
j = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="train"].index), s))
orders_df.loc[j,:].to_csv("Data/orders_train_sample.csv", index = False)
# create a sample of prior order products
order_products_prior_df = pd.read_csv('Data/order_products__prior.csv', index_col = 'order_id')
order_products_prior_df.loc[orders_df.loc[i,:]['order_id'],:].to_csv("Data/order_products_prior_sample.csv", index = False)
# create a sample of train order products
order_products_train_df = pd.read_csv('Data/order_products__train.csv', index_col = 'order_id')
order_products_train_df.loc[orders_df.loc[j,:]['order_id'],:].to_csv("Data/order_products_train_sample.csv", index = False)
|
Cut out blank lines at the start of PyPi README
|
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as readme:
README = readme.read().split('h1>\n\n', 2)[1]
setup(
name='django-postgres-extra',
version='1.21a4',
packages=find_packages(),
include_package_data=True,
license='MIT License',
description='Bringing all of PostgreSQL\'s awesomeness to Django.',
long_description=README,
url='https://github.com/SectorLabs/django-postgres-extra',
author='Sector Labs',
author_email='open-source@sectorlabs.ro',
keywords=['django', 'postgres', 'extra', 'hstore', 'ltree'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
]
)
|
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as readme:
README = readme.read().split('h1>', 2)[1]
setup(
name='django-postgres-extra',
version='1.21a3',
packages=find_packages(),
include_package_data=True,
license='MIT License',
description='Bringing all of PostgreSQL\'s awesomeness to Django.',
long_description=README,
url='https://github.com/SectorLabs/django-postgres-extra',
author='Sector Labs',
author_email='open-source@sectorlabs.ro',
keywords=['django', 'postgres', 'extra', 'hstore', 'ltree'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
]
)
|
Fix from phone number for US/Canadian messages.
|
/* 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/. */
"use strict";
var request = require("request");
var querystring = require("querystring");
function Nexmo(options) {
this._conf = options;
if (this._conf.endpoint === '') {
throw new Error("You should configure Nexmo credentials first.");
}
}
Nexmo.prototype = {
sendSms: function sendSms(from, to, message, callback) {
var url = this._conf.endpoint + "?" + querystring.stringify({
api_key: this._conf.apiKey,
api_secret: this._conf.apiSecret,
from: from.replace("+", ""),
to: to.replace("+", ""),
text: message
});
request.get(url, function(err) {
callback(err);
});
}
};
module.exports = Nexmo;
|
/* 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/. */
"use strict";
var request = require("request");
var querystring = require("querystring");
function Nexmo(options) {
this._conf = options;
if (this._conf.endpoint === '') {
throw new Error("You should configure Nexmo credentials first.");
}
}
Nexmo.prototype = {
sendSms: function sendSms(from, to, message, callback) {
var url = this._conf.endpoint + "?" + querystring.stringify({
api_key: this._conf.apiKey,
api_secret: this._conf.apiSecret,
from: from,
to: to.replace("+", ""),
text: message
});
request.get(url, function(err) {
callback(err);
});
}
};
module.exports = Nexmo;
|
Fix "Too Many Connections" error during testing
See laravel/framework#20340
|
<?php
namespace Laravel\Lumen\Testing;
trait DatabaseTransactions
{
/**
* Handle database transactions on the specified connections.
*
* @return void
*/
public function beginDatabaseTransaction()
{
$database = $this->app->make('db');
foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->beginTransaction();
}
$this->beforeApplicationDestroyed(function () use ($database) {
foreach ($this->connectionsToTransact() as $name) {
$connection = $database->connection($name);
$connection->rollBack();
$connection->disconnect();
}
});
}
/**
* The database connections that should have transactions.
*
* @return array
*/
protected function connectionsToTransact()
{
return property_exists($this, 'connectionsToTransact')
? $this->connectionsToTransact : [null];
}
}
|
<?php
namespace Laravel\Lumen\Testing;
trait DatabaseTransactions
{
/**
* Handle database transactions on the specified connections.
*
* @return void
*/
public function beginDatabaseTransaction()
{
$database = $this->app->make('db');
foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->beginTransaction();
}
$this->beforeApplicationDestroyed(function () use ($database) {
foreach ($this->connectionsToTransact() as $name) {
$database->connection($name)->rollBack();
}
});
}
/**
* The database connections that should have transactions.
*
* @return array
*/
protected function connectionsToTransact()
{
return property_exists($this, 'connectionsToTransact')
? $this->connectionsToTransact : [null];
}
}
|
Remove "clappr-zepto" external and "publlicPath" from webpack conf
|
var path = require('path');
var webpack = require('webpack');
var Clean = require('clean-webpack-plugin');
var plugins = [
new Clean(['dist'])
];
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
plugins: plugins,
externals: {
clappr: 'Clappr'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
compact: true,
}
},
{
test: /\.sass$/,
loaders: ['css', 'sass?includePaths[]=' + path.resolve(__dirname, "./node_modules/compass-mixins/lib")],
},
{
test: /\.html/, loader: 'html?minimize=false'
},
],
},
resolve: {
extensions: ['', '.js'],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'clappr-thumbnails-plugin.js',
library: 'ClapprThumbnailsPlugin',
libraryTarget: 'umd',
},
};
|
var path = require('path');
var webpack = require('webpack');
var Clean = require('clean-webpack-plugin');
var plugins = [
new Clean(['dist'])
];
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
plugins: plugins,
externals: {
clappr: 'Clappr',
"clappr-zepto": "clappr-zepto"
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
compact: true,
}
},
{
test: /\.sass$/,
loaders: ['css', 'sass?includePaths[]=' + path.resolve(__dirname, "./node_modules/compass-mixins/lib")],
},
{
test: /\.html/, loader: 'html?minimize=false'
},
],
},
resolve: {
extensions: ['', '.js'],
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '<%=baseUrl%>/',
filename: 'clappr-thumbnails-plugin.js',
library: 'ClapprThumbnailsPlugin',
libraryTarget: 'umd',
},
};
|
Add the PXE VendorPassthru interface to PXEDracDriver
Without the PXE VendorPassthru interface to expose the "pass_deploy_info"
method in the vendor_passthru endpoint of the API the DRAC it can't
continue the deployment after the ramdisk is booted.
Closes-Bug: #1379705
Change-Id: I21042cbb95a486742abfcb430471d01cd73b3a4a
(cherry picked from commit 78ec7d5336eb65ff845da7ea9f93d34b402f5a0f)
|
#
# 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.
"""
DRAC Driver for remote system management using Dell Remote Access Card.
"""
from oslo.utils import importutils
from ironic.common import exception
from ironic.common.i18n import _
from ironic.drivers import base
from ironic.drivers.modules.drac import management
from ironic.drivers.modules.drac import power
from ironic.drivers.modules import pxe
class PXEDracDriver(base.BaseDriver):
"""Drac driver using PXE for deploy."""
def __init__(self):
if not importutils.try_import('pywsman'):
raise exception.DriverLoadError(
driver=self.__class__.__name__,
reason=_('Unable to import pywsman library'))
self.power = power.DracPower()
self.deploy = pxe.PXEDeploy()
self.management = management.DracManagement()
self.vendor = pxe.VendorPassthru()
|
#
# 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.
"""
DRAC Driver for remote system management using Dell Remote Access Card.
"""
from oslo.utils import importutils
from ironic.common import exception
from ironic.common.i18n import _
from ironic.drivers import base
from ironic.drivers.modules.drac import management
from ironic.drivers.modules.drac import power
from ironic.drivers.modules import pxe
class PXEDracDriver(base.BaseDriver):
"""Drac driver using PXE for deploy."""
def __init__(self):
if not importutils.try_import('pywsman'):
raise exception.DriverLoadError(
driver=self.__class__.__name__,
reason=_('Unable to import pywsman library'))
self.power = power.DracPower()
self.deploy = pxe.PXEDeploy()
self.management = management.DracManagement()
|
Revert previous commit as fuse-python doesn't seem to play nicely with easy_install (at least on Ubuntu).
git-svn-id: fdb8975c015a424b33c0997a6b0d758f3a24819f@14 bfab2ddc-a81c-11dd-9a07-0f3041a8e97c
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Jason Davies
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'CouchDB-FUSE',
version = '0.1',
description = 'CouchDB FUSE module',
long_description = \
"""This is a Python FUSE module for CouchDB. It allows CouchDB document
attachments to be mounted on a virtual filesystem and edited directly.""",
author = 'Jason Davies',
author_email = 'jason@jasondavies.com',
license = 'BSD',
url = 'http://code.google.com/p/couchdb-fuse/',
zip_safe = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Database :: Front-Ends',
],
packages = ['couchdbfuse'],
entry_points = {
'console_scripts': [
'couchmount = couchdbfuse:main',
],
},
install_requires = ['CouchDB>=0.5'],
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Jason Davies
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'CouchDB-FUSE',
version = '0.1',
description = 'CouchDB FUSE module',
long_description = \
"""This is a Python FUSE module for CouchDB. It allows CouchDB document
attachments to be mounted on a virtual filesystem and edited directly.""",
author = 'Jason Davies',
author_email = 'jason@jasondavies.com',
license = 'BSD',
url = 'http://code.google.com/p/couchdb-fuse/',
zip_safe = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Database :: Front-Ends',
],
packages = ['couchdbfuse'],
entry_points = {
'console_scripts': [
'couchmount = couchdbfuse:main',
],
},
install_requires = ['CouchDB>=0.5', 'fuse-python>=0.2'],
)
|
Allow chargeToken to be null un paymentForm
|
<?php
namespace PureBilling\Bundle\SDKBundle\Store\V1\Charge;
use PureBilling\Bundle\SDKBundle\Store\Base\Element;
use Symfony\Component\Validator\Constraints as Assert;
use PureBilling\Bundle\SDKBundle\Constraints as PBAssert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
class PaymentForm extends Element
{
/**
* @Store\Property(description="Charge token (to send to pb.js). Null if merchant callback is defined.")
* @PBAssert\Type(type="id", idPrefixes={"chargetoken"})
*/
protected $chargeToken;
/**
* @Store\Property(description="Offsite payment form URL. Defined only if merchantCallback is set")
* @Assert\Type("string")
*/
protected $redirectUrl;
}
|
<?php
namespace PureBilling\Bundle\SDKBundle\Store\V1\Charge;
use PureBilling\Bundle\SDKBundle\Store\Base\Element;
use Symfony\Component\Validator\Constraints as Assert;
use PureBilling\Bundle\SDKBundle\Constraints as PBAssert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
class PaymentForm extends Element
{
/**
* @Store\Property(description="Charge token (to send to pb.js)")
* @PBAssert\Type(type="id", idPrefixes={"chargetoken"})
* @Assert\NotBlank()
*/
protected $chargeToken;
/**
* @Store\Property(description="Offsite payment form URL. Defined only if merchantCallback is set")
* @Assert\Type("string")
*/
protected $redirectUrl;
}
|
Fix countdown time identifier mistake
|
module.exports = {
0: {
countdown: 0,
time: "מיידי",
time_en: "Immediately"
},
15: {
countdown: 15,
time: "15 שניות",
time_en: "15 seconds"
},
30: {
countdown: 30,
time: "30 שניות",
time_en: "30 seconds"
},
45: {
countdown: 45,
time: "45 שניות",
time_en: "45 seconds"
},
60: {
countdown: 60,
time: "דקה",
time_en: "A minute"
},
90: {
countdown: 90,
time: "דקה וחצי",
time_en: "A minute and a half"
},
180: {
countdown: 180,
time: "3 דקות",
time_en: "3 minutes"
}
};
|
module.exports = {
0: {
countdown: 0,
time: "מיידי",
time_en: "Immediately"
},
15: {
countdown: 15,
time: "15 שניות",
time_en: "15 seconds"
},
30: {
countdown: 90,
time: "30 שניות",
time_en: "30 seconds"
},
45: {
countdown: 45,
time: "45 שניות",
time_en: "45 seconds"
},
60: {
countdown: 60,
time: "דקה",
time_en: "A minute"
},
90: {
countdown: 90,
time: "דקה וחצי",
time_en: "A minute and a half"
},
180: {
countdown: 180,
time: "3 דקות",
time_en: "3 minutes"
}
};
|
Add note about sort stability
|
package filter
// Copyright ©2011 Dan Kortschak <dan.kortschak@adelaide.edu.au>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
type FilterHit struct {
QFrom int
QTo int
DiagIndex int
}
// This is a direct translation of the qsort compar function used by PALS.
// However it results in a different sort order (with respect to the non-key
// fields) for FilterHits because of differences in the underlying sort
// algorithms and their respective sort stability.
// This appears to have some impact on FilterHit merging.
func (self FilterHit) Less(y interface{}) bool {
return self.QFrom < y.(FilterHit).QFrom
}
|
package filter
// Copyright ©2011 Dan Kortschak <dan.kortschak@adelaide.edu.au>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
type FilterHit struct {
QFrom int
QTo int
DiagIndex int
}
func (self FilterHit) Less(y interface{}) bool {
return self.QFrom < y.(FilterHit).QFrom
}
|
Set register route as public
|
"use strict";
module.exports = function(){
var user = new app.controllers.user();
return [
{
method: 'get',
url: '/users',
action: user.list,
cors: true
},
{
method: 'get',
url: '/users/me',
action: user.me,
cors: true
},
{
method: 'post',
url: '/users',
action: user.create,
cors: true,
public: true
}
];
};
|
"use strict";
module.exports = function(){
var user = new app.controllers.user();
return [
{
method: 'get',
url: '/users',
action: user.list,
cors: true
},
{
method: 'get',
url: '/users/me',
action: user.me,
cors: true
},
{
method: 'post',
url: '/users',
action: user.create,
cors: true
}
];
};
|
Datalogger: Fix trivial off by 1 in the livestream datalogger example
|
from pymoku import Moku, MokuException, NoDataException
from pymoku.instruments import *
import time, logging, traceback
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name('example')
i = Oscilloscope()
m.attach_instrument(i)
try:
i.set_defaults()
i.set_samplerate(10)
i.set_xmode(OSC_ROLL)
i.commit()
time.sleep(1)
i.datalogger_stop()
i.datalogger_start(start=0, duration=10, filetype='net')
while True:
ch, idx, d = i.datalogger_get_samples(timeout=5)
print "Received samples %d to %d from channel %d" % (idx, idx + len(d) - 1, ch)
except NoDataException as e:
# This will be raised if we try and get samples but the session has finished.
print e
except Exception as e:
print traceback.format_exc()
finally:
i.datalogger_stop()
m.close()
|
from pymoku import Moku, MokuException, NoDataException
from pymoku.instruments import *
import time, logging, traceback
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name('example')
i = Oscilloscope()
m.attach_instrument(i)
try:
i.set_defaults()
i.set_samplerate(10)
i.set_xmode(OSC_ROLL)
i.commit()
time.sleep(1)
i.datalogger_stop()
i.datalogger_start(start=0, duration=10, filetype='net')
while True:
ch, idx, d = i.datalogger_get_samples(timeout=5)
print "Received samples %d to %d from channel %d" % (idx, idx + len(d), ch)
except NoDataException as e:
# This will be raised if we try and get samples but the session has finished.
print e
except Exception as e:
print traceback.format_exc()
finally:
i.datalogger_stop()
m.close()
|
Fix JavaDoc "Cannot resolved symbol" issues.
|
package nerd.tuxmobil.fahrplan.congress.base;
import android.support.v4.app.ListFragment;
import nerd.tuxmobil.fahrplan.congress.models.Lecture;
/**
* A fragment representing a list of Items.
* <p/>
* Large screen devices (such as tablets) are supported by replacing the ListView
* with a GridView.
* <p/>
* Activities containing this fragment MUST implement the {@link OnLectureListClick}
* interface.
*/
public abstract class AbstractListFragment extends ListFragment {
public interface OnLectureListClick {
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
* @param lecture The lecture which was clicked.
* @param requiresScheduleReload Boolean flag to indicate whether the schedule
* must be reload from the data source or not.
*/
void onLectureListClick(Lecture lecture, boolean requiresScheduleReload);
}
}
|
package nerd.tuxmobil.fahrplan.congress.base;
import android.support.v4.app.ListFragment;
import nerd.tuxmobil.fahrplan.congress.models.Lecture;
/**
* A fragment representing a list of Items.
* <p/>
* Large screen devices (such as tablets) are supported by replacing the ListView
* with a GridView.
* <p/>
* Activities containing this fragment MUST implement the {@link OnLectureListClick}
* interface.
*/
public abstract class AbstractListFragment extends ListFragment {
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
* @param lecture The lecture which was clicked.
* @param requiresScheduleReload Boolean flag to indicate whether the schedule
* must be reload from the data source or not.
*/
public interface OnLectureListClick {
void onLectureListClick(Lecture lecture, boolean requiresScheduleReload);
}
}
|
Remove 300 ms additional delay
|
var NotificationController = SingleModelController.createComponent("NotificationController");
NotificationController.defineAlias("model", "notification");
NotificationController.defineMethod("initView", function initView() {
if (!this.view) return;
this.view.classList.add("hidden");
setElementProperty(this.view, "notification-id", this.notification.componentId);
});
NotificationController.defineMethod("updateView", function updateView() {
if (!this.view) return;
this.view.querySelectorAll("[data-ica-notification]").forEach(function (element) {
element.textContent = this.notification[getElementProperty(element, "notification")];
}.bind(this));
this.view.classList.remove("hidden");
});
NotificationController.defineMethod("uninitView", function uninitView() {
if (!this.view) return;
removeElementProperty(this.view, "notification-id");
});
NotificationController.defineMethod("destroy", function destroy(destroyView = false) {
// Destroy view
if (destroyView && this.view) {
var view = this.view,
model = this.notification,
jointModels = Object.values(this.notification.jointModels);
new Waterfall(function () {
view.classList.add("hidden");
}, 300 + 1)
.then(function () {
jointModels.forEach(function (jointModel) {
jointModel.removeNotification(model);
jointModel.didUpdate();
});
view.parentNode.removeChild(view);
}.bind(this));
}
return [];
});
|
var NotificationController = SingleModelController.createComponent("NotificationController");
NotificationController.defineAlias("model", "notification");
NotificationController.defineMethod("initView", function initView() {
if (!this.view) return;
this.view.classList.add("hidden");
setElementProperty(this.view, "notification-id", this.notification.componentId);
});
NotificationController.defineMethod("updateView", function updateView() {
if (!this.view) return;
this.view.querySelectorAll("[data-ica-notification]").forEach(function (element) {
element.textContent = this.notification[getElementProperty(element, "notification")];
}.bind(this));
this.view.classList.remove("hidden");
});
NotificationController.defineMethod("uninitView", function uninitView() {
if (!this.view) return;
removeElementProperty(this.view, "notification-id");
});
NotificationController.defineMethod("destroy", function destroy(destroyView = false) {
// Destroy view
if (destroyView && this.view) {
var view = this.view,
model = this.notification,
jointModels = Object.values(this.notification.jointModels);
new Waterfall(null, 300 + 1) // Leave time for transition to finish
.then(function () {
view.classList.add("hidden");
}, 300 + 1)
.then(function () {
view.parentNode.removeChild(view);
jointModels.forEach(function (jointModel) {
jointModel.removeNotification(model);
jointModel.didUpdate();
});
}.bind(this));
}
return [];
});
|
Add tab key to list of keycodes
|
// Keyboard keycodes
export const keyCodes = {
TAB: 9,
ENTER: 13,
ESCAPE: 27,
SPACE: 32,
LEFT_ARROW: 37,
UP_ARROW: 38,
RIGHT_ARROW: 39,
DOWN_ARROW: 40
};
// Classnames likely to be shared across modules
export const defaultClassNames = {
IS_ACTIVE: 'is-active',
IS_HIDDEN: 'is-hidden',
IS_READY: 'is-ready',
NO_BACKDROP: 'no-backdrop',
DIALOG_BACKDROP: 'dialog-backdrop'
};
export const NATIVELY_FOCUSABLE_ELEMENTS = [
'a[href]',
'area[href]',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'button:not([disabled])',
'iframe',
'object',
'embed',
'[contenteditable]',
'[tabindex]:not([tabindex^="-"])'
];
|
// Keyboard keycodes
export const keyCodes = {
ESCAPE: 27,
ENTER: 13,
SPACE: 32,
LEFT_ARROW: 37,
UP_ARROW: 38,
RIGHT_ARROW: 39,
DOWN_ARROW: 40
};
// Classnames likely to be shared across modules
export const defaultClassNames = {
IS_ACTIVE: 'is-active',
IS_HIDDEN: 'is-hidden',
IS_READY: 'is-ready',
NO_BACKDROP: 'no-backdrop',
DIALOG_BACKDROP: 'dialog-backdrop'
};
export const NATIVELY_FOCUSABLE_ELEMENTS = [
'a[href]',
'area[href]',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'button:not([disabled])',
'iframe',
'object',
'embed',
'[contenteditable]',
'[tabindex]:not([tabindex^="-"])'
];
|
Cover case we have an error exception
|
<?php
namespace PhpSpec\Wrapper\Subject\Expectation;
use Exception;
use PhpSpec\Exception\Example\ErrorException;
use PhpSpec\Util\Instantiator;
use PhpSpec\Wrapper\Subject\WrappedObject;
use PhpSpec\Wrapper\Unwrapper;
class ConstructorDecorator extends Decorator implements ExpectationInterface
{
private $unwrapper;
public function __construct(ExpectationInterface $expectation, Unwrapper $unwrapper)
{
$this->setExpectation($expectation);
$this->unwrapper = $unwrapper;
}
public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null)
{
try {
$wrapped = $subject->getWrappedObject();
} catch (ErrorException $e) {
throw $e;
} catch (Exception $e) {
if ($wrappedObject->getClassName()) {
$instantiator = new Instantiator();
$wrapped = $instantiator->instantiate($wrappedObject->getClassName());
}
}
return $this->getExpectation()->match($alias, $wrapped, $arguments);
}
}
|
<?php
namespace PhpSpec\Wrapper\Subject\Expectation;
use Exception;
use PhpSpec\Util\Instantiator;
use PhpSpec\Wrapper\Subject\WrappedObject;
use PhpSpec\Wrapper\Unwrapper;
class ConstructorDecorator extends Decorator implements ExpectationInterface
{
private $unwrapper;
public function __construct(ExpectationInterface $expectation, Unwrapper $unwrapper)
{
$this->setExpectation($expectation);
$this->unwrapper = $unwrapper;
}
public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null)
{
try {
$wrapped = $subject->getWrappedObject();
} catch (Exception $e) {
if ($wrappedObject->getClassName()) {
$instantiator = new Instantiator();
$wrapped = $instantiator->instantiate($wrappedObject->getClassName());
}
}
return $this->getExpectation()->match($alias, $wrapped, $arguments);
}
}
|
Fix bug where the included template was unattached from it's data
|
var angularMeteorTemplate = angular.module('angular-blaze-template', []);
// blaze-template adds Blaze templates to Angular as directives
angularMeteorTemplate.directive('blazeTemplate', [
'$compile',
function ($compile) {
return {
restrict: 'AE',
scope: false,
link: function (scope, element, attributes) {
// Check if templating and Blaze package exist, they won't exist in a
// Meteor Client Side (https://github.com/idanwe/meteor-client-side) application
if (Template && Package['blaze']){
var name = attributes.blazeTemplate || attributes.name;
if (name && Template[name]) {
var template = Template[name];
var viewHandler = Blaze.renderWithData(template, scope, element[0]);
$compile(element.contents())(scope);
element.find().unwrap();
scope.$on('$destroy', function() {
Blaze.remove(viewHandler);
});
} else {
console.error("meteorTemplate: There is no template with the name '" + name + "'");
}
}
}
};
}
]);
var angularMeteorModule = angular.module('angular-meteor');
angularMeteorModule.requires.push('angular-blaze-template');
|
var angularMeteorTemplate = angular.module('angular-blaze-template', []);
// blaze-template adds Blaze templates to Angular as directives
angularMeteorTemplate.directive('blazeTemplate', [
'$compile',
function ($compile) {
return {
restrict: 'AE',
scope: false,
link: function (scope, element, attributes) {
// Check if templating and Blaze package exist, they won't exist in a
// Meteor Client Side (https://github.com/idanwe/meteor-client-side) application
if (Template && Package['blaze']){
var name = attributes.blazeTemplate || attributes.name;
if (name && Template[name]) {
var template = Template[name];
var viewHandler = Blaze.renderWithData(template, scope, element[0]);
$compile(element.contents())(scope);
var childs = element.children();
element.replaceWith(childs);
scope.$on('$destroy', function() {
Blaze.remove(viewHandler);
});
} else {
console.error("meteorTemplate: There is no template with the name '" + name + "'");
}
}
}
};
}
]);
var angularMeteorModule = angular.module('angular-meteor');
angularMeteorModule.requires.push('angular-blaze-template');
|
Check For Empty String On Page Title Update
This commit fixes #8
|
<?php
class ReeCreate_PageTitle_Model_Observer
{
/**
* Change product or category page titles
*
* @pram Varien_Event_Observer $observer
* @return ReeCreate_PageTitle_Model_Observer
*/
public function controller_action_layout_generate_blocks_after(Varien_Event_Observer $observer)
{
$head = $observer->getLayout()->getBlock('head');
if(Mage::registry('current_product'))
{
$title = Mage::registry('current_product')->getName();
}
if(Mage::registry('current_category') && empty($title))
{
$title = Mage::registry('current_category')->getName();
}
if(!empty($title))
{
$head->setTitle($title);
}
}
}
|
<?php
class ReeCreate_PageTitle_Model_Observer
{
/**
* Change product or category page titles
*
* @pram Varien_Event_Observer $observer
* @return ReeCreate_PageTitle_Model_Observer
*/
public function controller_action_layout_generate_blocks_after(Varien_Event_Observer $observer)
{
$head = $observer->getLayout()->getBlock('head');
if(Mage::registry('current_product'))
{
$title = Mage::registry('current_product')->getName();
}
if(Mage::registry('current_category') && empty($title))
{
$title = Mage::registry('current_category')->getName();
}
$head->setTitle($title);
}
}
|
Add additional CRUD functions to Quiz class
|
from database import QuizDB
db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT)
class Quiz(Base):
def __init__(self, id):
self.id = id
QUESTION_HASH = "{0}:question".format(self.id)
ANSWER_HASH = "{0}:answer".format(self.id)
def new_card(self, question, answer):
assert db.hlen(QUESTION_HASH) == db.hlen(ANSWER_HASH)
q_id = max([int(i) for i in db.hkeys(QUESTION_HASH)]) + 1
db.hset(QUESTION_HASH, q_id, question)
db.hset(ANSWER_HASH, q_id, answer)
def delete_card(self, q_id):
db.hdel(QUESTION_HASH, q_id)
db.hdel(ANSWER_HASH, q_id)
def update_question(self, q_id, updated_question):
db.hset(QUESTION_HASH, q_id, updated_question)
def update_answer(self, q_id, updated_answer):
db.hset(ANSWER_HASH, q_id, updated_answer)
|
from database import QuizDB
db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT)
class Quiz(Base):
def __init__(self, id):
self.id = id
QUESTION_HASH = "{0}:question".format(self.id)
ANSWER_HASH = "{0}:answer".format(self.id)
def new_card(self, question, answer):
assert db.hlen(QUESTION_HASH) == db.hlen(ANSWER_HASH)
q_id = max([int(i) for i in db.hkeys(QUESTION_HASH)]) + 1
db.hset(QUESTION_HASH, q_id, question)
db.hset(ANSWER_HASH, q_id, answer)
def delete_card(self, q_id):
db.hdel(QUESTION_HASH, q_id)
db.hdel(ANSWER_HASH, q_id)
|
Upgrade tangled.web 0.1a10 => 1.0a12
|
from setuptools import setup
setup(
name='tangled.mako',
version='1.0a4.dev0',
description='Tangled Mako integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.mako/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
include_package_data=True,
packages=[
'tangled',
'tangled.mako',
'tangled.mako.tests',
],
install_requires=[
'tangled.web>=1.0a12',
'Mako>=1.0',
],
extras_require={
'dev': [
'tangled[dev]>=1.0a11',
'tangled.web[dev]>=1.0a12',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
from setuptools import setup
setup(
name='tangled.mako',
version='1.0a4.dev0',
description='Tangled Mako integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.mako/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
include_package_data=True,
packages=[
'tangled',
'tangled.mako',
'tangled.mako.tests',
],
install_requires=[
'tangled.web>=0.1a10',
'Mako>=1.0',
],
extras_require={
'dev': [
'tangled.web[dev]>=0.1a10',
'tangled[dev]>=1.0a11',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
Update expected icon name in tests
|
const assert = require('assert');
const Account = require('../Contents/Scripts/account.js').Account;
const PullRequest = require('../Contents/Scripts/pull-request.js').PullRequest;
const Repository = require('../Contents/Scripts/repository.js').Repository;
describe('PullRequest', function() {
let number = '42';
let title = 'Fix off by one bug';
let owner = new Account('obama');
let repo = new Repository(owner, 'whitehouse.gov', 'My blog.');
let pullRequest = new PullRequest(number, repo, title);
describe('#url', function() {
it('returns the URL of the pull request', function() {
assert.equal('https://github.com/obama/whitehouse.gov/pull/42', pullRequest.url);
});
});
describe('#shortURL', function() {
it('returns the short URL of the pull request', function() {
assert.equal('obama/whitehouse.gov#42', pullRequest.shortURL);
});
});
describe('#toMenuItem()', function() {
it('returns a JSON formatted menu item for LaunchBar', function() {
assert.deepEqual({
title: 'Fix off by one bug',
subtitle: 'obama/whitehouse.gov#42',
alwaysShowsSubtitle: true,
icon: 'pullRequestTemplate.png',
url: 'https://github.com/obama/whitehouse.gov/pull/42',
}, pullRequest.toMenuItem());
});
});
});
|
const assert = require('assert');
const Account = require('../Contents/Scripts/account.js').Account;
const PullRequest = require('../Contents/Scripts/pull-request.js').PullRequest;
const Repository = require('../Contents/Scripts/repository.js').Repository;
describe('PullRequest', function() {
let number = '42';
let title = 'Fix off by one bug';
let owner = new Account('obama');
let repo = new Repository(owner, 'whitehouse.gov', 'My blog.');
let pullRequest = new PullRequest(number, repo, title);
describe('#url', function() {
it('returns the URL of the pull request', function() {
assert.equal('https://github.com/obama/whitehouse.gov/pull/42', pullRequest.url);
});
});
describe('#shortURL', function() {
it('returns the short URL of the pull request', function() {
assert.equal('obama/whitehouse.gov#42', pullRequest.shortURL);
});
});
describe('#toMenuItem()', function() {
it('returns a JSON formatted menu item for LaunchBar', function() {
assert.deepEqual({
title: 'Fix off by one bug',
subtitle: 'obama/whitehouse.gov#42',
alwaysShowsSubtitle: true,
icon: 'pull-request.png',
url: 'https://github.com/obama/whitehouse.gov/pull/42',
}, pullRequest.toMenuItem());
});
});
});
|
Change minimum value of minimum content width
|
'use babel';
import Controller from './controller.js';
export default {
config: {
grammars: {
order : 1,
type : 'array',
default: ['source.gfm', 'text.md'],
items : {
type: 'string'
}
},
minimumContentWidth: {
order : 2,
type : 'integer',
default: 3,
minimum: 1
},
useEastAsianWidth: {
order : 3,
type : 'boolean',
default : false,
description: 'Compute character width'
+ ' based on the Unicode East Asian Width specification'
},
smartCursor: {
order : 4,
type : 'boolean',
default: false,
title : 'Experimental: Smart Cursor'
}
},
controler: null,
activate() {
this.controller = new Controller();
},
deactivate() {
this.controller.destroy();
},
serialize() {
}
};
|
'use babel';
import Controller from './controller.js';
export default {
config: {
grammars: {
order : 1,
type : 'array',
default: ['source.gfm', 'text.md'],
items : {
type: 'string'
}
},
minimumContentWidth: {
order : 2,
type : 'integer',
default: 3,
minimum: 3
},
useEastAsianWidth: {
order : 3,
type : 'boolean',
default : false,
description: 'Compute character width'
+ ' based on the Unicode East Asian Width specification'
},
smartCursor: {
order : 4,
type : 'boolean',
default: false,
title : 'Experimental: Smart Cursor'
}
},
controler: null,
activate() {
this.controller = new Controller();
},
deactivate() {
this.controller.destroy();
},
serialize() {
}
};
|
Fix object creation 5.3 compatible
|
<?php
/**
* Class MagicTest
*/
class MagicTest extends PHPUnit_Framework_TestCase
{
/**
*
*/
public function testAssertIsInvokable()
{
$this->assertInstanceOf('\Invokable', new ExampleClass());
}
/**
*
*/
public function testAssertStringifiable()
{
$this->assertInstanceOf('\Stringifiable', new ExampleClass());
}
/**
*
*/
public function testAssertArrayable()
{
$this->assertInstanceOf('\Arrayable', new ExampleClass());
}
/**
*
*/
public function testAssertArrayableReturn()
{
$o = new ExampleClass();
$this->assertContainsOnly('string', $o->toArray());
}
}
|
<?php
/**
* Class MagicTest
*/
class MagicTest extends PHPUnit_Framework_TestCase
{
/**
*
*/
public function testAssertIsInvokable()
{
$this->assertInstanceOf('\Invokable', new ExampleClass());
}
/**
*
*/
public function testAssertStringifiable()
{
$this->assertInstanceOf('\Stringifiable', new ExampleClass());
}
/**
*
*/
public function testAssertArrayable()
{
$this->assertInstanceOf('\Arrayable', new ExampleClass());
}
/**
*
*/
public function testAssertArrayableReturn()
{
$this->assertContainsOnly('string', (new ExampleClass())->toArray());
}
}
|
Fix logic for retrieving test suite id
|
define([
'underscore',
'backbone',
'models/core/BaseModel',
], function(_, Backbone, BaseModel) {
var TestSuiteModel = BaseModel.extend({
defaults: {
id: null,
project_id: 1,
name: 'No test suite name',
description: 'No description',
url: '#/404'
},
initialize: function(options) {
_.bindAll(this, 'url', 'parse');
},
url: function() {
var url = '/api/projects/' + this.get('project_id') + '/testsuites';
if (this.get('id') != null) {
url += '/' + this.get('id');
} else if (this.id) {
url += '/' + this.id;
}
return url;
},
parse: function(obj) {
if (typeof(obj.test_suite) != 'undefined')
return obj.test_suite;
return obj;
}
});
return TestSuiteModel;
});
|
define([
'underscore',
'backbone',
'models/core/BaseModel',
], function(_, Backbone, BaseModel) {
var TestSuiteModel = BaseModel.extend({
defaults: {
id: null,
project_id: 1,
name: 'No test suite name',
description: 'No description',
url: '#/404'
},
initialize: function(options) {
_.bindAll(this, 'url', 'parse');
},
url: function() {
var url = '/api/projects/' + this.get('project_id') + '/testsuites';
if (this.get('id') != null) {
url += '/' + this.get('id');
}
if (this.id)
url += '/' + this.id;
return url;
},
parse: function(obj) {
if (typeof(obj.test_suite) != 'undefined')
return obj.test_suite;
return obj;
}
});
return TestSuiteModel;
});
|
Switch from staging to production.
|
(function($) {
var baseUrl = 'https://api.cloudmine.me/v1/app/';
$.cm = {
getJSON: function(appid, apikey, keys, callback) {
var url = baseUrl + appid + '/text';
$.ajax(url, {
headers: { 'X-CloudMine-ApiKey': apikey },
success: callback
});
},
replaceJSON: function(appid, apikey, data, callback) {
var url = baseUrl + appid + '/text';
$.ajax(url, {
headers: { 'X-CloudMine-ApiKey': apikey },
processData: false,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: callback
});
},
insertValueForKey: function(appid, apikey, key, value, callback) {
var data = {};
data[key] = value;
this.replaceJSON(appid, apikey, data, callback);
}
};
})(jQuery);
|
(function($) {
var baseUrl = 'https://api-staging.cloudmine.me/v1/app/';
$.cm = {
getJSON: function(appid, apikey, keys, callback) {
var url = baseUrl + appid + '/text';
$.ajax(url, {
headers: { 'X-CloudMine-ApiKey': apikey },
success: callback
});
},
replaceJSON: function(appid, apikey, data, callback) {
var url = baseUrl + appid + '/text';
$.ajax(url, {
headers: { 'X-CloudMine-ApiKey': apikey },
processData: false,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: callback
});
},
insertValueForKey: function(appid, apikey, key, value, callback) {
var data = {};
data[key] = value;
this.replaceJSON(appid, apikey, data, callback);
}
};
})(jQuery);
|
Fix javascript bug that was causing parts to be overridden
Don't use last-child to figure out what the last fieldset, instead do a general selection and use jQuery.last() to pull out the final element. The previous method was actually matching the first element
|
var formtastic_ids = {};
$(function () {
$('.add-associated').click(function () {
elem = $(this);
var target_id = elem.data('target');
var target = $('#' + target_id);
var template_id = elem.data('tmpl_id');
template_contents = $('#' + template_id).html();
if (typeof(formtastic_ids[template_id]) == 'undefined') {
var current_id = target.find('fieldset input').last().attr('id').match(/_attributes_(\d+)_/)[1];
formtastic_ids[template_id] = current_id;
}
formtastic_ids[template_id]++;
var html = $.mustache(template_contents, {
index: formtastic_ids[template_id]
});
target.append(html);
$(this).trigger('associated-added');
return false;
});
$('.remove-associated').click(function () {
var css_selector = $(this).data('selector');
$(this).parents(css_selector).hide(); $(this).prev(':input').val('1');
})
});
|
var formtastic_ids = {};
$(function () {
$('.add-associated').click(function () {
elem = $(this);
var target_id = elem.data('target');
var target = $('#' + target_id);
var template_id = elem.data('tmpl_id');
template_contents = $('#' + template_id).html();
if (typeof(formtastic_ids[template_id]) == 'undefined') {
var current_id = target.find('fieldset:last-child input').attr('id').match(/_attributes_(\d+)_/)[1];
formtastic_ids[template_id] = current_id;
}
formtastic_ids[template_id]++;
var html = $.mustache(template_contents, {
index: formtastic_ids[template_id]
});
target.append(html);
$(this).trigger('associated-added');
return false;
});
$('.remove-associated').click(function () {
var css_selector = $(this).data('selector');
$(this).parents(css_selector).hide(); $(this).prev(':input').val('1');
})
});
|
:wrench: Add loading check for Login container
|
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import { get } from 'axios';
import FlintLogo from 'components/FlintLogo';
import './LoginContainer.scss';
import { siteName } from '../../../config';
export default class LoginContainer extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
}
state = { siteLogo: null, isFetching: true }
componentWillMount() { document.body.classList.add('body--grey'); }
componentDidMount() {
get('/admin/api/site').then(({ data }) => {
this.setState({ siteLogo: data.siteLogo, isFetching: false });
});
}
componentWillUnmount() { document.body.classList.remove('body--grey'); }
render() {
const { siteLogo, isFetching } = this.state;
const { children } = this.props;
if (isFetching) return null;
return (
<div className="login">
{siteLogo ? <img style={{ maxWidth: '420px', maxHeight: '200px', margin: '1em auto' }} src={`/public/assets/${siteLogo.filename}`} alt={siteName} /> : <FlintLogo width={140} height={80} />}
{children}
<Link to="/admin/fp" className="login__forgot">Forgot your password?</Link>
{siteLogo && <FlintLogo poweredBy width={100} height={25} />}
</div>
);
}
}
|
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import { get } from 'axios';
import FlintLogo from 'components/FlintLogo';
import './LoginContainer.scss';
import { siteName } from '../../../config';
export default class LoginContainer extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
}
state = { siteLogo: null }
componentWillMount() { document.body.classList.add('body--grey'); }
componentDidMount() {
get('/admin/api/site').then(({ data }) => {
this.setState({ siteLogo: data.siteLogo });
});
}
componentWillUnmount() { document.body.classList.remove('body--grey'); }
render() {
const { siteLogo } = this.state;
const { children } = this.props;
return (
<div className="login">
{siteLogo ? <img style={{ maxWidth: '420px', maxHeight: '200px', margin: '1em auto' }} src={`/public/assets/${siteLogo.filename}`} alt={siteName} /> : <FlintLogo width={140} height={80} />}
{children}
<Link to="/admin/fp" className="login__forgot">Forgot your password?</Link>
{siteLogo && <FlintLogo poweredBy width={100} height={25} />}
</div>
);
}
}
|
Add parent loading of beforeFilter
|
<?php
/**
* CakeManager (http://cakemanager.org)
* Copyright (c) http://cakemanager.org
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) http://cakemanager.org
* @link http://cakemanager.org CakeManager Project
* @since 1.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Users\Controller;
use App\Controller\AppController as BaseController;
use Cake\Event\Event;
class AppController extends BaseController
{
public function beforeFilter(Event $event)
{
if ($this->authUser) {
$this->layout = 'Users.default';
} else {
$this->layout = 'Users.login';
}
parent::beforeFilter($event);
}
}
|
<?php
/**
* CakeManager (http://cakemanager.org)
* Copyright (c) http://cakemanager.org
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) http://cakemanager.org
* @link http://cakemanager.org CakeManager Project
* @since 1.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Users\Controller;
use App\Controller\AppController as BaseController;
use Cake\Event\Event;
class AppController extends BaseController
{
public function beforeFilter(Event $event)
{
if ($this->authUser) {
$this->layout = 'Users.default';
} else {
$this->layout = 'Users.login';
}
}
}
|
Add minimize task to default
|
//Import dependencies
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var header = require('gulp-header');
//Import the package
var pkg = require('./package.json');
//Generate the header
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
'', ''].join('\n');
//Concat all files in build folder
gulp.task('concat', function(){
//Set the source files
gulp.src(['./src/cv.js', './src/**/*'])
//Concat all files
.pipe(concat('cv.js'))
//Add the header
.pipe(header(banner, { pkg : pkg } ))
//Save
.pipe(gulp.dest('./dist/'));
});
//Minimize the output file
gulp.task('minimize', function(){
//Set the source file
gulp.src('./dist/cv.js')
//Minimize
.pipe(uglify())
//Save the file
.pipe(rename('cv.min.js'))
//Add the header
.pipe(header(banner, { pkg : pkg } ))
//Save in css/ folder
.pipe(gulp.dest('./dist/'));
});
//Execute the tasks
gulp.task('default', ['concat', 'minimize']);
|
//Import dependencies
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var header = require('gulp-header');
//Import the package
var pkg = require('./package.json');
//Generate the header
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
'', ''].join('\n');
//Concat all files in build folder
gulp.task('concat', function(){
//Set the source files
gulp.src(['./src/cv.js', './src/**/*'])
//Concat all files
.pipe(concat('cv.js'))
//Add the header
.pipe(header(banner, { pkg : pkg } ))
//Save
.pipe(gulp.dest('./dist/'));
});
//Minimize the output file
gulp.task('minimize', function(){
//Set the source file
gulp.src('./dist/cv.js')
//Minimize
.pipe(uglify())
//Save the file
.pipe(rename('cv.min.js'))
//Add the header
.pipe(header(banner, { pkg : pkg } ))
//Save in css/ folder
.pipe(gulp.dest('./dist/'));
});
//Execute the tasks
gulp.task('default', ['concat']);
|
Make the failing test pass
|
defaultConf = {
height: 100,
width: 300,
fingerprintLength: 4
};
describe("The constructor is supposed a proper Captcha object", function() {
it('Constructor Captcha exists', function(){
expect(Captcha).toBeDefined();
});
var captcha = new Captcha();
it("Captcha object is not null", function(){
expect(captcha).not.toBeNull();
});
it('captcha object should be an instance of Captcha class', function(){
expect(captcha instanceof Captcha).toBeTruthy();
});
it('the height of the svg should be set to the configured height', function(){
expect(Number(captcha.height)).toEqual(defaultConf.height);
});
it('the width of the svg should be set to the configured width', function(){
expect(Number(captcha.width)).toEqual(defaultConf.width);
});
it('the length of the fingerprint should be set to the configured fingerprintLength', function(){
expect(Number(captcha.fingerprintLength)).toEqual(defaultConf.fingerprintLength);
});
});
|
defaultConf = {
height: 100,
width: 300,
fingerprintLength: 20
};
describe("The constructor is supposed a proper Captcha object", function() {
it('Constructor Captcha exists', function(){
expect(Captcha).toBeDefined();
});
var captcha = new Captcha();
it("Captcha object is not null", function(){
expect(captcha).not.toBeNull();
});
it('captcha object should be an instance of Captcha class', function(){
expect(captcha instanceof Captcha).toBeTruthy();
});
it('the height of the svg should be set to the configured height', function(){
expect(Number(captcha.height)).toEqual(defaultConf.height);
});
it('the width of the svg should be set to the configured width', function(){
expect(Number(captcha.width)).toEqual(defaultConf.width);
});
it('the length of the fingerprint should be set to the configured fingerprintLength', function(){
expect(Number(captcha.fingerprintLength)).toEqual(defaultConf.fingerprintLength);
});
});
|
Update for compatibility with pyes==0.19.1
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search_raw({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
Use lazy URL generator as to prevent construction race
|
<?php
namespace Bolt\Provider;
use Bolt\Routing\Canonical;
use Silex\Application;
use Silex\ServiceProviderInterface;
/**
* Canonical service provider.
*
* @author Carson Full <carsonfull@gmail.com>
*/
class CanonicalServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['canonical'] = $app->share(
function ($app) {
return new Canonical(
$app['url_generator.lazy'],
$app['config']->get('general/force_ssl'),
$app['config']->get('general/canonical')
);
}
);
}
public function boot(Application $app)
{
if (isset($app['canonical'])) {
$app['dispatcher']->addSubscriber($app['canonical']);
}
}
}
|
<?php
namespace Bolt\Provider;
use Bolt\Routing\Canonical;
use Silex\Application;
use Silex\ServiceProviderInterface;
/**
* Canonical service provider.
*
* @author Carson Full <carsonfull@gmail.com>
*/
class CanonicalServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['canonical'] = $app->share(
function ($app) {
return new Canonical(
$app['url_generator'],
$app['config']->get('general/force_ssl'),
$app['config']->get('general/canonical')
);
}
);
}
public function boot(Application $app)
{
if (isset($app['canonical'])) {
$app['dispatcher']->addSubscriber($app['canonical']);
}
}
}
|
[r=jtv] Switch Azure provider over to loggo logging.
|
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package azure
import (
"launchpad.net/juju-core/environs"
"launchpad.net/juju-core/environs/config"
"launchpad.net/juju-core/instance"
"launchpad.net/loggo"
)
// Logger for the Azure provider.
var logger = loggo.GetLogger("juju.environs.azure")
type azureEnvironProvider struct{}
// azureEnvironProvider implements EnvironProvider.
var _ environs.EnvironProvider = (*azureEnvironProvider)(nil)
// Open is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {
logger.Debugf("opening environment %q.", cfg.Name())
return NewEnviron(cfg)
}
// PublicAddress is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) PublicAddress() (string, error) {
panic("unimplemented")
}
// PrivateAddress is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) PrivateAddress() (string, error) {
panic("unimplemented")
}
// InstanceId is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) InstanceId() (instance.Id, error) {
panic("unimplemented")
}
|
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package azure
import (
"launchpad.net/juju-core/environs"
"launchpad.net/juju-core/environs/config"
"launchpad.net/juju-core/instance"
"launchpad.net/juju-core/log"
)
type azureEnvironProvider struct{}
// azureEnvironProvider implements EnvironProvider.
var _ environs.EnvironProvider = (*azureEnvironProvider)(nil)
// Open is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {
log.Debugf("environs/azure: opening environment %q.", cfg.Name())
return NewEnviron(cfg)
}
// PublicAddress is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) PublicAddress() (string, error) {
panic("unimplemented")
}
// PrivateAddress is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) PrivateAddress() (string, error) {
panic("unimplemented")
}
// InstanceId is specified in the EnvironProvider interface.
func (prov azureEnvironProvider) InstanceId() (instance.Id, error) {
panic("unimplemented")
}
|
Fix order of components of shift
FITS and bumpy have opposite conventions as to which axis is the first axis
|
from image import ImageWithWCS
import numpy as np
from os import path
def shift_images(files, source_dir, output_file='_shifted'):
"""Align images based on astrometry."""
ref = files[0] # TODO: make reference image an input
ref_im = ImageWithWCS(path.join(source_dir, ref))
ref_pix = np.int32(np.array(ref_im.data.shape) / 2)
ref_ra_dec = ref_im.wcs_pix2sky(ref_pix)
base, ext = path.splitext(files[0])
ref_im.save(path.join(source_dir, base + output_file + ext))
for fil in files[1:]:
img = ImageWithWCS(path.join(source_dir, fil))
ra_dec_pix = img.wcs_sky2pix(ref_ra_dec)
shift = ref_pix - np.int32(ra_dec_pix)
# FITS order of axes opposite of numpy, so swap:
shift = shift[::-1]
img.shift(shift, in_place=True)
base, ext = path.splitext(fil)
img.save(path.join(source_dir, base + output_file + ext))
|
from image import ImageWithWCS
import numpy as np
from os import path
def shift_images(files, source_dir, output_file='_shifted'):
"""Align images based on astrometry."""
ref = files[0] # TODO: make reference image an input
ref_im = ImageWithWCS(path.join(source_dir, ref))
ref_pix = np.int32(np.array(ref_im.data.shape) / 2)
ref_ra_dec = ref_im.wcs_pix2sky(ref_pix)
base, ext = path.splitext(files[0])
ref_im.save(path.join(source_dir, base + output_file + ext))
for fil in files[1:]:
img = ImageWithWCS(path.join(source_dir, fil))
ra_dec_pix = img.wcs_sky2pix(ref_ra_dec)
shift = ref_pix - np.int32(ra_dec_pix)
print shift
img.shift(shift, in_place=True)
base, ext = path.splitext(fil)
img.save(path.join(source_dir, base + output_file + ext))
|
Remove "Parse error, " from error messages
|
# -*- coding: utf-8 -*-
# php.py - sublimelint package for checking php files
import re
from base_linter import BaseLinter
CONFIG = {
'language': 'php',
'executable': 'php',
'lint_args': ('-l', '-d display_errors=On')
}
class Linter(BaseLinter):
def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages):
for line in errors.splitlines():
match = re.match(r'^Parse error:\s*(?:\w+ error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line)
if match:
error, line = match.group('error'), match.group('line')
self.add_message(int(line), lines, error, errorMessages)
|
# -*- coding: utf-8 -*-
# php.py - sublimelint package for checking php files
import re
from base_linter import BaseLinter
CONFIG = {
'language': 'php',
'executable': 'php',
'lint_args': ('-l', '-d display_errors=On')
}
class Linter(BaseLinter):
def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages):
for line in errors.splitlines():
match = re.match(r'^Parse error:\s*(?:syntax error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line)
if match:
error, line = match.group('error'), match.group('line')
self.add_message(int(line), lines, error, errorMessages)
|
Remove unused method and add some javadoc.
|
package com.github.pedrovgs.nox.path;
/**
* Spiral Path implementation used to place NoxItem objects in a equiangular spiral starting from
* the center of the view. NoxItem instances in this path will have the same size. This path is
* based on the Archimedean Spiral.
*
* @author Pedro Vicente Gomez Sanchez.
*/
class SpiralPath extends Path {
SpiralPath(PathConfig pathConfig) {
super(pathConfig);
}
@Override public void calculate() {
int numberOfItems = getPathConfig().getNumberOfElements();
float centerY =
(getPathConfig().getViewHeight() / 2) - (getPathConfig().getFirstItemSize() / 2);
float centerX = (getPathConfig().getViewWidth() / 2) + (getPathConfig().getFirstItemSize() / 2);
float angle = getPathConfig().getFirstItemSize();
for (int i = 0; i < numberOfItems; i++) {
double x = centerX + (angle * i * Math.cos(i));
setNoxItemLeftPosition(i, (float) x);
double y = centerY + (angle * i * Math.sin(i));
setNoxItemTopPosition(i, (float) y);
}
}
}
|
package com.github.pedrovgs.nox.path;
/**
* Spiral Path implementation used to place NoxItem objects in a equiangular spiral starting from
* the center of the view. NoxItem instances in this path will have the same size.
*
* @author Pedro Vicente Gomez Sanchez.
*/
class SpiralPath extends Path {
SpiralPath(PathConfig pathConfig) {
super(pathConfig);
}
@Override public void calculate() {
int numberOfItems = getPathConfig().getNumberOfElements();
float centerY =
(getPathConfig().getViewHeight() / 2) - (getPathConfig().getFirstItemSize() / 2);
float centerX = (getPathConfig().getViewWidth() / 2) + (getPathConfig().getFirstItemSize() / 2);
float angle = getPathConfig().getFirstItemSize();
for (int i = 0; i < numberOfItems; i++) {
double x = centerX + (angle * i * Math.cos(i));
setNoxItemLeftPosition(i, (float) x);
double y = centerY + (angle * i * Math.sin(i));
setNoxItemTopPosition(i, (float) y);
}
}
protected float getFirstItemLeftPosition() {
return getPathConfig().getFirstItemMargin();
}
}
|
Update 'install_requires' to right versions
|
from setuptools import setup, find_packages
setup(
name='django-facebook',
version='0.1',
description='Replace Django Authentication with Facebook',
long_description=open('README.md').read(),
author='Aidan Lister',
author_email='aidan@php.net',
url='http://github.com/pythonforfacebook/django-facebook',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'django>=1.5',
'facebook-sdk==0.4.0',
],
dependency_links=[
'https://github.com/pythonforfacebook/facebook-sdk/tarball/master#egg=facebook-sdk-dev',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
from setuptools import setup, find_packages
setup(
name='django-facebook',
version='0.1',
description='Replace Django Authentication with Facebook',
long_description=open('README.md').read(),
author='Aidan Lister',
author_email='aidan@php.net',
url='http://github.com/pythonforfacebook/django-facebook',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'django>=1.2.7',
'facebook-sdk>=0.2.0,==dev',
],
dependency_links=[
'https://github.com/pythonforfacebook/facebook-sdk/tarball/master#egg=facebook-sdk-dev',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Fix system module integration tests
|
/*
* Copyright (C) 2018 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.system.impl;
import org.jbb.lib.cache.CacheConfig;
import org.jbb.lib.commons.CommonsConfig;
import org.jbb.lib.db.DbConfig;
import org.jbb.lib.eventbus.EventBusConfig;
import org.jbb.lib.health.HealthCheckConfig;
import org.jbb.lib.logging.LoggingConfig;
import org.jbb.lib.mvc.MvcConfig;
import org.jbb.lib.properties.PropertiesConfig;
import org.jbb.lib.test.MockCommonsConfig;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {CommonsConfig.class, SystemConfig.class, MvcConfig.class, LoggingConfig.class,
EventBusConfig.class, PropertiesConfig.class, DbConfig.class, CacheConfig.class,
HealthCheckConfig.class, MockCommonsConfig.class})
public abstract class BaseIT {
}
|
/*
* Copyright (C) 2018 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.system.impl;
import org.jbb.lib.cache.CacheConfig;
import org.jbb.lib.commons.CommonsConfig;
import org.jbb.lib.db.DbConfig;
import org.jbb.lib.eventbus.EventBusConfig;
import org.jbb.lib.logging.LoggingConfig;
import org.jbb.lib.mvc.MvcConfig;
import org.jbb.lib.properties.PropertiesConfig;
import org.jbb.lib.test.MockCommonsConfig;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {CommonsConfig.class, SystemConfig.class, MvcConfig.class, LoggingConfig.class,
EventBusConfig.class, PropertiesConfig.class, DbConfig.class, CacheConfig.class, MockCommonsConfig.class})
public abstract class BaseIT {
}
|
Break chaining into different lines and change string to single quotes
* Keep styling in file consistent..
|
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var imagemin = require('gulp-imagemin');
var open = require('gulp-open');
gulp.task('scripts', function () {
return browserify('./js/main.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./build/js'));
});
gulp.task('css', function () {
return gulp.src('./css/**/*.css')
.pipe(gulp.dest('./build/css'));
});
gulp.task('html', function () {
return gulp.src('./*.html')
.pipe(gulp.dest('./build'));
});
gulp.task('images', function () {
return gulp.src('./public/images/**/*')
.pipe(imagemin())
.pipe(gulp.dest('./build/public/images'))
});
gulp.task('watch', function () {
gulp.watch('./js/**/*.js', ['scripts']);
gulp.watch('./css/**/*.css', ['css']);
gulp.watch('./*.html', ['html']);
});
gulp.task('open', function () {
var options = {
app: 'google chrome'
};
return gulp.src('./build/index.html')
.pipe(open('./build/index.html', options));
});
gulp.task('default', ['scripts', 'css', 'html', 'images', 'watch', 'open']);
|
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var imagemin = require('gulp-imagemin');
var open = require('gulp-open');
gulp.task('scripts', function () {
return browserify('./js/main.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./build/js'));
});
gulp.task('css', function () {
return gulp.src('./css/**/*.css')
.pipe(gulp.dest('./build/css'));
});
gulp.task('html', function () {
return gulp.src('./*.html')
.pipe(gulp.dest('./build'));
});
gulp.task('images', function () {
return gulp.src('./public/images/**/*')
.pipe(imagemin())
.pipe(gulp.dest('./build/public/images'))
});
gulp.task('watch', function () {
gulp.watch('./js/**/*.js', ['scripts']);
gulp.watch('./css/**/*.css', ['css']);
gulp.watch('./*.html', ['html']);
});
gulp.task('open', function () {
var options = {
app: 'google chrome'
};
return gulp.src("./build/index.html").pipe(open('./build/index.html', options));
});
gulp.task('default', ['scripts', 'css', 'html', 'images', 'watch', 'open']);
|
Update up to changes in es5-ext
|
'use strict';
var Assert = require('test/assert').Assert
, bindMethods = require('es5-ext/lib/Object/plain/bind-methods').call
, merge = require('es5-ext/lib/Object/plain/merge').call
, never, neverBind;
never = function (message) {
this.fail({
message: message,
operator: "never"
});
};
neverBind = function (message) {
return never.bind(this, message);
};
module.exports = function (logger) {
var assert = new Assert({
pass: logger.pass.bind(logger),
fail: logger.fail.bind(logger),
error: logger.error.bind(logger)
});
assert = bindMethods(assert.strictEqual.bind(assert),
assert, Assert.prototype);
assert.not = assert.notStrictEqual;
assert.deep = assert.deepEqual;
assert.notDeep = assert.notDeepEqual;
assert.never = never.bind(assert);
assert.never.bind = neverBind.bind(assert);
return assert;
};
|
'use strict';
var Assert = require('test/assert').Assert
, bindMethods = require('es5-ext/lib/Object/bind-methods').call
, merge = require('es5-ext/lib/Object/plain/merge').call
, never, neverBind;
never = function (message) {
this.fail({
message: message,
operator: "never"
});
};
neverBind = function (message) {
return never.bind(this, message);
};
module.exports = function (logger) {
var assert = new Assert({
pass: logger.pass.bind(logger),
fail: logger.fail.bind(logger),
error: logger.error.bind(logger)
});
assert = bindMethods(assert.strictEqual.bind(assert),
assert, Assert.prototype);
assert.not = assert.notStrictEqual;
assert.deep = assert.deepEqual;
assert.notDeep = assert.notDeepEqual;
assert.never = never.bind(assert);
assert.never.bind = neverBind.bind(assert);
return assert;
};
|
Stop showing atomic block in "All" example
|
import React from 'react';
import ReactDOM from 'react-dom';
import DraftailEditor, { BLOCK_TYPE, INLINE_STYLE } from '../lib';
import allContentState from './utils/allContentState';
const mount = document.querySelector('[data-mount-all]');
const onSave = contentState => {
sessionStorage.setItem('all:contentState', JSON.stringify(contentState));
};
const allBlockTypes = Object.keys(BLOCK_TYPE)
.filter(t => t !== 'ATOMIC')
.map(type => ({
label: `${type.charAt(0).toUpperCase()}${type
.slice(1)
.toLowerCase()
.replace(/_/g, ' ')}`,
type: BLOCK_TYPE[type],
}));
const allInlineStyles = Object.keys(INLINE_STYLE).map(type => ({
label: `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()}`,
type: INLINE_STYLE[type],
}));
const editor = (
<DraftailEditor
rawContentState={allContentState}
onSave={onSave}
stripPastedStyles={false}
enableHorizontalRule={true}
enableLineBreak={true}
showUndoRedoControls={true}
blockTypes={allBlockTypes}
inlineStyles={allInlineStyles}
/>
);
ReactDOM.render(editor, mount);
|
import React from 'react';
import ReactDOM from 'react-dom';
import DraftailEditor, { BLOCK_TYPE, INLINE_STYLE } from '../lib';
import allContentState from './utils/allContentState';
const mount = document.querySelector('[data-mount-all]');
const onSave = contentState => {
sessionStorage.setItem('all:contentState', JSON.stringify(contentState));
};
const allBlockTypes = Object.keys(BLOCK_TYPE).map(type => ({
label: `${type.charAt(0).toUpperCase()}${type
.slice(1)
.toLowerCase()
.replace(/_/g, ' ')}`,
type: BLOCK_TYPE[type],
}));
const allInlineStyles = Object.keys(INLINE_STYLE).map(type => ({
label: `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()}`,
type: INLINE_STYLE[type],
}));
const editor = (
<DraftailEditor
rawContentState={allContentState}
onSave={onSave}
stripPastedStyles={false}
enableHorizontalRule={true}
enableLineBreak={true}
showUndoRedoControls={true}
blockTypes={allBlockTypes}
inlineStyles={allInlineStyles}
/>
);
ReactDOM.render(editor, mount);
|
Fix weird character issues by hard-coding to UTF-8
|
package haushaltsbuch.controllers;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter("/*")
public class ContentTypeFilter implements Filter
{
public void destroy()
{
// this space intentionally left blank
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
response.setLocale(Locale.GERMANY);
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException
{
// this space intentionally left blank
}
}
|
package haushaltsbuch.controllers;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter("/*")
public class ContentTypeFilter implements Filter
{
public void destroy()
{
// this space intentionally left blank
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
response.setContentType("text/html; charset=utf-8");
response.setLocale(Locale.GERMANY);
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException
{
// this space intentionally left blank
}
}
|
Allow for passing in a simple string as the name of a logger
|
var std = require('std')
// TODO Send email on error
module.exports = std.Class(function() {
var defaults = {
name: 'Logger'
}
this._init = function(opts) {
if (typeof opts == 'string') { opts = { name:opts } }
opts = std.extend(opts, defaults)
this._name = opts.name
this._emailQueue = []
}
this.log = function() {
this._consoleLog(std.slice(arguments))
}
this.error = function(err, message) {
var messageParts = [this._name, new Date().getTime(), message, err.message, err.stack]
this._consoleLog(messageParts)
this._queueEmail(messageParts)
}
this._queueEmail = function(messageParts) {
this._emailQueue.push(messageParts)
this._scheduleEmailDispatch()
}
var joinParts = function(arr) { return arr.join(' | ') }
this._consoleLog = function(messageParts) {
console.log(joinParts(messageParts))
}
this._scheduleEmailDispatch = std.delay(function() {
var message = std.map(this._emailQueue, joinParts).join('\n')
// TODO send message to error reporting email address
}, 10000) // Send at most one email per 10 seconds
})
|
var std = require('std')
// TODO Send email on error
module.exports = std.Class(function() {
var defaults = {
name: 'Logger'
}
this._init = function(opts) {
opts = std.extend(opts, defaults)
this._name = opts.name
this._emailQueue = []
}
this.log = function() {
this._consoleLog(std.slice(arguments))
}
this.error = function(err, message) {
var messageParts = [this._name, new Date().getTime(), message, err.message, err.stack]
this._consoleLog(messageParts)
this._queueEmail(messageParts)
}
this._queueEmail = function(messageParts) {
this._emailQueue.push(messageParts)
this._scheduleEmailDispatch()
}
var joinParts = function(arr) { return arr.join(' | ') }
this._consoleLog = function(messageParts) {
console.log(joinParts(messageParts))
}
this._scheduleEmailDispatch = std.delay(function() {
var message = std.map(this._emailQueue, joinParts).join('\n')
// TODO send message to error reporting email address
}, 10000) // Send at most one email per 10 seconds
})
|
Switch to the new github release download links
|
#!/usr/bin/env python
from setuptools import setup
def read(filename):
return open(filename).read()
setup(name="lzo-indexer",
version="0.0.1",
description="Library for indexing LZO compressed files",
long_description=read("README.md"),
author="Tom Arnfeld",
author_email="tom@duedil.com",
maintainer="Tom Arnfeld",
maintainer_email="tom@duedil.com",
url="https://github.com/duedil-ltd/python-lzo-indexer",
download_url="https://github.com/duedil-ltd/python-lzo-indexer/archive/0.0.1.tar.gz",
license=read("LICENSE"),
packages=["lzo_indexer"],
scripts=["bin/lzo-indexer"],
test_suite="tests.test_indexer",
)
|
#!/usr/bin/env python
from setuptools import setup
def read(filename):
return open(filename).read()
setup(name="lzo-indexer",
version="0.0.1",
description="Library for indexing LZO compressed files",
long_description=read("README.md"),
author="Tom Arnfeld",
author_email="tom@duedil.com",
maintainer="Tom Arnfeld",
maintainer_email="tom@duedil.com",
url="https://github.com/duedil-ltd/python-lzo-indexer",
download_url="https://github.com/duedil-ltd/python-lzo-indexer/archive/release-0.0.1.zip",
license=read("LICENSE"),
packages=["lzo_indexer"],
scripts=["bin/lzo-indexer"],
test_suite="tests.test_indexer",
)
|
Use isset instead of empty
|
<?php defined('SYSPATH') or die('No direct script access.');
class MustacheView
{
protected $values;
public $name;
public function __construct($name)
{
$this->name = $name;
}
public function __get($key)
{
if (!isset($this->values[$key])) return false;
return $this->values[$key];
}
public function __set($key, $value)
{
if (is_object($value) && method_exists($value, '__toString'))
{
$value = $value->__toString();
}
$this->values[$key] = $value;
}
public function __toString()
{
return $this->render();
}
public function __isset($key)
{
return (isset($this->values[$key]));
}
public function render()
{
$m = new Mustache;
return $m->render($this->markup(), $this);
}
protected function markup()
{
return file_get_contents(APPPATH . 'views/' . $this->name . '.ms');
}
public static function factory($name)
{
return new self($name);
}
}
|
<?php defined('SYSPATH') or die('No direct script access.');
class MustacheView
{
protected $values;
public $name;
public function __construct($name)
{
$this->name = $name;
}
public function __get($key)
{
if (empty($this->values[$key])) return false;
return $this->values[$key];
}
public function __set($key, $value)
{
if (is_object($value) && method_exists($value, '__toString'))
{
$value = $value->__toString();
}
$this->values[$key] = $value;
}
public function __toString()
{
return $this->render();
}
public function __isset($key)
{
return (isset($this->values[$key]));
}
public function render()
{
$m = new Mustache;
return $m->render($this->markup(), $this);
}
protected function markup()
{
return file_get_contents(APPPATH . 'views/' . $this->name . '.ms');
}
public static function factory($name)
{
return new self($name);
}
}
|
Add a way of listing commands
|
from argparse import ArgumentParser
import yaml
from .runner import Runner
def parse_variables(args):
variables = {}
if args is not None:
for variable in args:
tokens = variable.split('=')
name = tokens[0]
value = '='.join(tokens[1:])
variables[name] = value
return variables
def main():
parser = ArgumentParser()
parser.add_argument('-f', '--file', default='mo.yaml')
parser.add_argument('-v', '--var', dest='variables', nargs='*')
parser.add_argument('tasks', metavar='task', nargs='*')
args = parser.parse_args()
with open(args.file) as file:
configuration = yaml.load(file.read())
variables = parse_variables(args.variables)
runner = Runner(configuration, variables)
if args.tasks is None:
for task in args.tasks:
runner.run_task(task)
else:
print()
for task in runner.tasks.values():
print('', task.name, '-', task.description)
|
from argparse import ArgumentParser
import yaml
from .runner import Runner
def parse_variables(args):
variables = {}
if args is not None:
for variable in args:
tokens = variable.split('=')
name = tokens[0]
value = '='.join(tokens[1:])
variables[name] = value
return variables
def main():
parser = ArgumentParser()
parser.add_argument('-f', '--file', default='mo.yaml')
parser.add_argument('-v', '--var', dest='variables', nargs='*')
parser.add_argument('tasks', metavar='task', nargs='+')
args = parser.parse_args()
with open(args.file) as file:
configuration = yaml.load(file.read())
variables = parse_variables(args.variables)
runner = Runner(configuration, variables)
for task in args.tasks:
runner.run_task(task)
|
Remove keyword argument and allow generic argument passing.
|
from django.forms.widgets import Select
class LayoutSelector(Select):
"""
Modified `Select` class to select the original value.
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
"""
def render(self, name, value, attrs=None, *args, **kwargs):
"""
Modified render to set the data original value.
:param name: The name of the `Select` field.
:param value: The value of the `Select` field.
:param attrs: Additional attributes of the `Select` field.
:param args: pass along any other arguments.
:param kwargs: pass along any other keyword arguments.
:return: HTML select.
"""
if attrs:
attrs['data-original-value'] = value
return super(LayoutSelector, self).render(name, value, attrs, *args, **kwargs)
|
from django.forms.widgets import Select
class LayoutSelector(Select):
"""
Modified `Select` class to select the original value.
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
"""
def render(self, name, value, attrs=None, choices=()):
"""
Modified render to set the data original value.
:param name: The name of the `Select` field.
:param value: The value of the `Select` field.
:param attrs: Additional attributes of the `Select` field.
:param choices: Available choices for the `Select` field.
:return: HTML select.
"""
if attrs:
attrs['data-original-value'] = value
return super(LayoutSelector, self).render(name, value, attrs, choices)
|
Move projects dropdown to Bootstrap list-group
|
import React from 'react';
const Projects = props => {
return (
<div className="projects list-group">
{Object.keys(props.projects).map(projectId => {
const ticket = props.projects[projectId][0];
return (
<button
key={projectId}
type="button"
className="list-group-item"
onClick={props.searchProject.bind(this, {
company: ticket.company.name,
project: ticket.project.name,
})}
>
<strong>{ticket.company.name}</strong> — {ticket.project.name}
</button>
);
})}
</div>
);
};
export default Projects;
|
import React from 'react';
const Projects = props => {
return (
<ul className="projects">
{Object.keys(props.projects).map(projectId => {
const ticket = props.projects[projectId][0];
return (
<li key={projectId}>
{ticket.company.name} —
<button
type="button"
className="btn-link"
onClick={props.searchProject.bind(this, {
company: ticket.company.name,
project: ticket.project.name,
})}
>
{ticket.project.name}
</button>
</li>
);
})}
</ul>
);
};
export default Projects;
|
Add some Java 8-isms to coverage merger.
|
package com.squareup.spoon;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import org.jacoco.core.tools.ExecFileLoader;
import static com.google.common.collect.Collections2.transform;
import static com.squareup.spoon.SpoonDeviceRunner.COVERAGE_DIR;
import static com.squareup.spoon.SpoonDeviceRunner.COVERAGE_FILE;
final class SpoonCoverageMerger {
private static final String MERGED_COVERAGE_FILE = "merged-coverage.ec";
private ExecFileLoader execFileLoader;
public SpoonCoverageMerger() {
this.execFileLoader = new ExecFileLoader();
}
public void mergeCoverageFiles(Set<String> serials, File outputDirectory) throws IOException {
Collection<String> sanitizeSerials = transform(serials, SpoonUtils::sanitizeSerial);
for (String serial : sanitizeSerials) {
String coverageFilePath = COVERAGE_DIR + "/" + serial + "/" + COVERAGE_FILE;
execFileLoader.load(new File(outputDirectory, coverageFilePath));
}
String mergedCoverageFile = COVERAGE_DIR + "/" + MERGED_COVERAGE_FILE;
execFileLoader.save(new File(outputDirectory, mergedCoverageFile), false);
}
}
|
package com.squareup.spoon;
import com.google.common.base.Function;
import org.jacoco.core.tools.ExecFileLoader;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import static com.google.common.collect.Collections2.transform;
import static com.squareup.spoon.SpoonDeviceRunner.COVERAGE_DIR;
import static com.squareup.spoon.SpoonDeviceRunner.COVERAGE_FILE;
import static com.squareup.spoon.SpoonUtils.sanitizeSerial;
final class SpoonCoverageMerger {
private static final String MERGED_COVERAGE_FILE = "merged-coverage.ec";
private ExecFileLoader execFileLoader;
public SpoonCoverageMerger() {
this.execFileLoader = new ExecFileLoader();
}
public void mergeCoverageFiles(Set<String> serials, File outputDirectory) throws IOException {
Collection<String> sanitizeSerials = transform(serials, toSanitizeSerials());
for (String serial : sanitizeSerials) {
String coverageFilePath = COVERAGE_DIR + "/" + serial + "/" + COVERAGE_FILE;
execFileLoader.load(new File(outputDirectory, coverageFilePath));
}
String mergedCoverageFile = COVERAGE_DIR + "/" + MERGED_COVERAGE_FILE;
execFileLoader.save(new File(outputDirectory, mergedCoverageFile), false);
}
private Function<String, String> toSanitizeSerials() {
return new Function<String, String>() {
@Override
public String apply(String serials) {
return sanitizeSerial(serials);
}
};
}
}
|
Check if the optional family field is null before attempting to insert.
|
/**
*
*/
package ca.eandb.sortable;
import java.util.LinkedList;
import java.util.List;
import ca.eandb.sortable.Product.Field;
/**
* @author brad
*
*/
public final class ProductTrieBuilder implements ProductVisitor {
private final TrieNode root = new TrieNode();
/*(non-Javadoc)
* @see ca.eandb.sortable.ProductVisitor#visit(ca.eandb.sortable.Product)
*/
@Override
public void visit(Product product) {
addProduct(product);
}
public void addProduct(Product product) {
processField(product, Field.MANUFACTURER, product.getManufacturer());
processField(product, Field.MODEL, product.getModel());
if (product.getFamily() != null) {
processField(product, Field.FAMILY, product.getFamily());
}
}
private void processField(Product product, Field field, String value) {
value = StringUtil.normalize(value);
String[] words = value.split(" ");
ProductMatch match = new ProductMatch(product, field);
for (String word : words) {
TrieNode node = root.insert(word);
List<ProductMatch> products = (List<ProductMatch>) node.getData();
if (products == null) {
products = new LinkedList<ProductMatch>();
node.setData(products);
}
products.add(match);
}
}
public TrieNode getRoot() {
return root;
}
}
|
/**
*
*/
package ca.eandb.sortable;
import java.util.LinkedList;
import java.util.List;
import ca.eandb.sortable.Product.Field;
/**
* @author brad
*
*/
public final class ProductTrieBuilder implements ProductVisitor {
private final TrieNode root = new TrieNode();
/*(non-Javadoc)
* @see ca.eandb.sortable.ProductVisitor#visit(ca.eandb.sortable.Product)
*/
@Override
public void visit(Product product) {
addProduct(product);
}
public void addProduct(Product product) {
processField(product, Field.MANUFACTURER, product.getManufacturer());
processField(product, Field.FAMILY, product.getFamily());
processField(product, Field.MODEL, product.getModel());
}
private void processField(Product product, Field field, String value) {
value = StringUtil.normalize(value);
String[] words = value.split(" ");
ProductMatch match = new ProductMatch(product, field);
for (String word : words) {
TrieNode node = root.insert(word);
List<ProductMatch> products = (List<ProductMatch>) node.getData();
if (products == null) {
products = new LinkedList<ProductMatch>();
node.setData(products);
}
products.add(match);
}
}
public TrieNode getRoot() {
return root;
}
}
|
Fix Controller class not found
|
<?php
namespace BuzzwordCompliant\FAQs\Controllers;
use Backend\Classes\Controller;
use Backend\Facades\BackendMenu;
use Illuminate\Http\Request;
class FAQs extends Controller
{
public function __construct()
{
parent::__construct();
BackendMenu::setContext('BuzzwordCompliant.FAQs', 'faqs');
}
public $implement = [
'Backend.Behaviors.ListController',
'Backend.Behaviors.FormController',
'Backend.Behaviors.RelationController',
'Backend.Behaviors.ReorderController',
];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $relationConfig = 'config_relation.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function reorderExtendQuery($query)
{
$query->where('faq_id', $this->params[0]);
}
}
|
<?php
namespace BuzzwordCompliant\FAQs\Controllers;
use Backend\Facades\BackendMenu;
use Illuminate\Http\Request;
class FAQs extends Controller
{
public function __construct()
{
parent::__construct();
BackendMenu::setContext('BuzzwordCompliant.FAQs', 'faqs');
}
public $implement = [
'Backend.Behaviors.ListController',
'Backend.Behaviors.FormController',
'Backend.Behaviors.RelationController',
'Backend.Behaviors.ReorderController',
];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $relationConfig = 'config_relation.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function reorderExtendQuery($query)
{
$query->where('faq_id', $this->params[0]);
}
}
|
[connected_components/javascript] Replace fat arrow by traditional function for clarity
|
export class AdjacencyList {
constructor(graph) {
this.a = constructAdjacencyList(graph);
}
depthFirstSearch(start, earlyCallback) {
depthFirstSearch(this.a, start, earlyCallback);
}
}
function constructAdjacencyList(graph) {
// new Array(vertexCount).fill([]) does not work because it reuses the same array instance for
// every element.
let a = Array.from(new Array(graph.vertexCount), () => []);
for (let [x, y] of graph.edges) {
insertEdge(a, x, y, graph.directed);
}
return a;
}
function insertEdge(a, x, y, directed) {
a[x].push(y);
if (!directed) {
insertEdge(a, y, x, true);
}
}
function depthFirstSearch(a, start, earlyCallback) {
let processed = new Array(a.length);
function dfs(x) {
if (processed[x]) {
return;
}
processed[x] = true;
earlyCallback(x);
a[x].forEach(dfs);
}
dfs(start);
}
|
export class AdjacencyList {
constructor(graph) {
this.a = constructAdjacencyList(graph);
}
depthFirstSearch(start, earlyCallback) {
depthFirstSearch(this.a, start, earlyCallback);
}
}
function constructAdjacencyList(graph) {
// new Array(vertexCount).fill([]) does not work because it reuses the same array instance for
// every element.
let a = Array.from(new Array(graph.vertexCount), () => []);
for (let [x, y] of graph.edges) {
insertEdge(a, x, y, graph.directed);
}
return a;
}
function insertEdge(a, x, y, directed) {
a[x].push(y);
if (!directed) {
insertEdge(a, y, x, true);
}
}
function depthFirstSearch(a, start, earlyCallback) {
let processed = new Array(a.length);
let dfs = x => {
if (processed[x]) {
return;
}
processed[x] = true;
earlyCallback(x);
a[x].forEach(dfs);
};
dfs(start);
}
|
Enable dummy promise return until verifyContactExists actually works
|
var Q = require('q');
/**
* Confirms that the supplied ID is a valid number.
* @param {string} id String to confirm is a valid integer
* @returns {Q.promise} containing value of the ID number as integer
*/
function verifyNumberIsInteger(id) {
let deferred = Q.defer()
if (id == "0"){
deferred.resolve(0)
return deferred.promise
}
let parsed_id = parseInt(id,10)
if (!parsed_id) {
deferred.reject(new Error("Supplied number is not an integer: " + id))
}
else {
deferred.resolve(parsed_id)
}
return deferred.promise
}
module.exports.verifyNumberIsInteger = verifyNumberIsInteger
function verifyContactExists(id){
let deferred = Q.defer()
// TODO: Make this actually work
deferred.resolve(id)
return deferred.promise
}
module.exports.verifyContactExists = verifyContactExists
|
var Q = require('q');
/**
* Confirms that the supplied ID is a valid number.
* @param {string} id String to confirm is a valid integer
* @returns {Q.promise} containing value of the ID number as integer
*/
function verifyNumberIsInteger(id) {
let deferred = Q.defer()
if (id == "0"){
deferred.resolve(0)
return deferred.promise
}
let parsed_id = parseInt(id,10)
if (!parsed_id) {
deferred.reject(new Error("Supplied number is not an integer: " + id))
}
else {
deferred.resolve(parsed_id)
}
return deferred.promise
}
module.exports.verifyNumberIsInteger = verifyNumberIsInteger
function verifyContactExists(id){
let deferred = Q.defer()
// TODO: Make this actually work
}
module.exports.verifyContactExists = verifyContactExists
|
Correct the darklang migration, since many darklang configs can exist.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Converted from the original South migration 0002_enable_on_install.py
#
from django.db import migrations, models
def create_dark_lang_config(apps, schema_editor):
"""
Enable DarkLang by default when it is installed, to prevent accidental
release of testing languages.
"""
dark_lang_model = apps.get_model("dark_lang", "DarkLangConfig")
db_alias = schema_editor.connection.alias
if not dark_lang_model.objects.using(db_alias).exists():
dark_lang_model.objects.using(db_alias).create(enabled=True)
def remove_dark_lang_config(apps, schema_editor):
"""Write your backwards methods here."""
raise RuntimeError("Cannot reverse this migration.")
class Migration(migrations.Migration):
dependencies = [
('dark_lang', '0001_initial'),
]
operations = [
migrations.RunPython(create_dark_lang_config, remove_dark_lang_config),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Converted from the original South migration 0002_enable_on_install.py
#
from django.db import migrations, models
def create_dark_lang_config(apps, schema_editor):
"""
Enable DarkLang by default when it is installed, to prevent accidental
release of testing languages.
"""
dark_lang_model = apps.get_model("dark_lang", "DarkLangConfig")
db_alias = schema_editor.connection.alias
dark_lang_model.objects.using(db_alias).get_or_create(enabled=True)
def remove_dark_lang_config(apps, schema_editor):
"""Write your backwards methods here."""
raise RuntimeError("Cannot reverse this migration.")
class Migration(migrations.Migration):
dependencies = [
('dark_lang', '0001_initial'),
]
operations = [
migrations.RunPython(create_dark_lang_config, remove_dark_lang_config),
]
|
Add version constraint for marshmallow
|
#!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), fname), 'r') as infile:
content = infile.read()
return content
setup(
name='marshmallow-polyfield',
version=5.0,
description='An unofficial extension to Marshmallow to allow for polymorphic fields',
long_description=read('README.rst'),
author='Matt Bachmann',
author_email='bachmann.matt@gmail.com',
url='https://github.com/Bachmann1234/marshmallow-polyfield',
packages=['marshmallow_polyfield', 'tests'],
license=read('LICENSE'),
keywords=('serialization', 'rest', 'json', 'api', 'marshal',
'marshalling', 'deserialization', 'validation', 'schema'),
install_requires=['marshmallow>=3.0.0b10', 'six'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
)
|
#!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), fname), 'r') as infile:
content = infile.read()
return content
setup(
name='marshmallow-polyfield',
version=5.0,
description='An unofficial extension to Marshmallow to allow for polymorphic fields',
long_description=read('README.rst'),
author='Matt Bachmann',
author_email='bachmann.matt@gmail.com',
url='https://github.com/Bachmann1234/marshmallow-polyfield',
packages=['marshmallow_polyfield', 'tests'],
license=read('LICENSE'),
keywords=('serialization', 'rest', 'json', 'api', 'marshal',
'marshalling', 'deserialization', 'validation', 'schema'),
install_requires=['marshmallow', 'six'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
)
|
Load petstore if library contains no documents
|
<?php
namespace Alt3\Swagger\Controller;
use Cake\Core\Configure;
use Cake\Core\Exception;
use Cake\Routing\Router;
/**
* UiController class responsible for serving the swagger-ui template page.
*
* @package Alt3\Swagger\Controller
*/
class UiController extends AppController
{
/**
* Index action used for setting template variables.
*
* @return void
*/
public function index()
{
$this->viewBuilder()->layout(false);
$this->set('config', static::$config['ui']);
// Load petstore document if library contains no entries
if (empty(static::$config['library'])) {
$this->set('url', 'http://petstore.swagger.io/v2/swagger.json');
return;
}
// Otherwise load first document found in the library
$defaultDocument = key(static::$config['library']);
$this->set('url', Router::url([
'plugin' => 'Alt3/Swagger',
'controller' => 'Docs',
'action' => 'index',
$defaultDocument
], true));
}
}
|
<?php
namespace Alt3\Swagger\Controller;
use Cake\Core\Configure;
use Cake\Core\Exception;
use Cake\Routing\Router;
/**
* UiController class responsible for serving the swagger-ui template page.
*
* @package Alt3\Swagger\Controller
*/
class UiController extends AppController
{
/**
* Index action used for setting template variables.
*
* @return void
*/
public function index()
{
$this->viewBuilder()->layout(false);
$this->set('config', static::$config['ui']);
// make the first document autoload inside the UI
$defaultDocument = key(static::$config['library']);
if (!$defaultDocument) {
throw new \InvalidArgumentException("cakephp-swagger configuration file does not contain any documents");
}
$this->set('url', Router::url([
'plugin' => 'Alt3/Swagger',
'controller' => 'Docs',
'action' => 'index',
$defaultDocument
], true));
}
}
|
Watermark for WRLD branding. Also fixes a bug where the micello logo is not displayed due to case sensitivity. Pair: Malc
|
var IndoorWatermarkController = function() {
var _indoorWatermarkElement = null;
var _elementId = "eegeo-indoor-map-watermark";
var _urlRoot = "https://cdn-webgl.eegeo.com/eegeojs/resources/indoor-vendors/";
var _buildUrlForVendor = function(vendorKey) {
var vendorKeyLower = vendorKey.toLowerCase();
if (vendorKeyLower === "eegeo")
{
vendorKeyLower = "wrld";
}
return _urlRoot + vendorKeyLower + "_logo.png";
};
var _precacheKnownVendors = function() {
var knownVendors = ["eegeo", "micello"];
knownVendors.forEach(function(vendor) {
var vendorImageUrl = _buildUrlForVendor(vendor);
var tempImage = new Image();
tempImage.src = vendorImageUrl;
});
};
_precacheKnownVendors();
this.showWatermarkForVendor = function(vendorKey) {
var imageUrl = _buildUrlForVendor(vendorKey);
if (_indoorWatermarkElement === null) {
_indoorWatermarkElement = document.getElementById(_elementId);
}
_indoorWatermarkElement.src = imageUrl;
_indoorWatermarkElement.style.bottom = 0;
};
this.hideWatermark = function() {
_indoorWatermarkElement.style.bottom = "-50px";
};
};
module.exports = IndoorWatermarkController;
|
var IndoorWatermarkController = function() {
var _indoorWatermarkElement = null;
var _elementId = "eegeo-indoor-map-watermark";
var _urlRoot = "https://cdn-webgl.eegeo.com/eegeojs/resources/indoor-vendors/";
var _buildUrlForVendor = function(vendorKey) {
return _urlRoot + vendorKey + "_logo.png";
};
var _precacheKnownVendors = function() {
var knownVendors = ["eegeo", "micello"];
knownVendors.forEach(function(vendor) {
var vendorImageUrl = _buildUrlForVendor(vendor);
var tempImage = new Image();
tempImage.src = vendorImageUrl;
});
};
_precacheKnownVendors();
this.showWatermarkForVendor = function(vendorKey) {
var imageUrl = _buildUrlForVendor(vendorKey);
if (_indoorWatermarkElement === null) {
_indoorWatermarkElement = document.getElementById(_elementId);
}
_indoorWatermarkElement.src = imageUrl;
_indoorWatermarkElement.style.bottom = 0;
};
this.hideWatermark = function() {
_indoorWatermarkElement.style.bottom = "-50px";
};
};
module.exports = IndoorWatermarkController;
|
Fix deleting old request to VK.
|
<?php
namespace Helldar\Vk\Commands;
use Carbon\Carbon;
use Helldar\Vk\Models\VkRequest;
use Illuminate\Console\Command;
class VkRequestsClear extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'vk:queue-clear';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clear old data';
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*/
public function handle()
{
VkRequest::onlyTrashed()->where('deleted_at', '<', Carbon::now()->addHours(-2))->delete();
}
}
|
<?php
namespace Helldar\Vk\Commands;
use Carbon\Carbon;
use Helldar\Vk\Models\VkRequest;
use Illuminate\Console\Command;
class VkRequestsClear extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'vk:queue-clear';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clear old data';
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
VkRequest::onlyTrashed()->where('deleted_at', '<', Carbon::now()->addHours(2))->delete();
}
}
|
Refactor [description] property to not require
|
/**
* Places.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models
*/
module.exports = {
//connection: 'db_server',
//configurations to disale UpdateAt and CreatedAt Waterline Columns
tableName: 'places',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
id: {
type: 'integer',
autoIncrement: true,
unique: true,
primaryKey: true
},
company_id: {
type: 'integer',
required: true
},
name: {
type: 'string',
required: true
},
description: {
type: 'text'
},
created_at: {
type: 'datetime'
},
updated_at: {
type: 'datetime'
},
updated_by_user: {
type: 'integer',
columnName: 'updated_by_user_id',
required: true
}
}
};
|
/**
* Places.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models
*/
module.exports = {
//connection: 'db_server',
//configurations to disale UpdateAt and CreatedAt Waterline Columns
tableName: 'places',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
id: {
type: 'integer',
autoIncrement: true,
unique: true,
primaryKey: true
},
company_id: {
type: 'integer',
required: true
},
name: {
type: 'string',
required: true
},
description: {
type: 'text',
required: true
},
created_at: {
type: 'datetime'
},
updated_at: {
type: 'datetime'
},
updated_by_user: {
type: 'integer',
columnName: 'updated_by_user_id',
required: true
}
}
};
|
Fix the missing host variable
|
'use strict';
const Promise = require('bluebird');
const pg = require('pg');
const database = JSON.parse(
process.env.PLATFORM_RELATIONSHIPS ?
new Buffer(process.env.PLATFORM_RELATIONSHIPS, 'base64').toString('ascii') :
// Development settings
JSON.stringify({
database: [{
username: 'dpsv',
path: 'dpsv',
password: 'password',
host: '127.0.0.1'
}]
})
).database[0];
const connObj = {
user: database.username,
database: database.path,
password: database.password,
host: database.host
};
Promise.promisifyAll(pg, { multiArgs: true });
Promise.promisifyAll(pg.Client.prototype);
module.exports = function() {
let close;
return pg.connectAsync(connObj).spread(function(client, done) {
close = done;
return client;
}).disposer(function() {
if (close) close();
});
};
|
'use strict';
const Promise = require('bluebird');
const pg = require('pg');
const database = JSON.parse(
process.env.PLATFORM_RELATIONSHIPS ?
new Buffer(process.env.PLATFORM_RELATIONSHIPS, 'base64').toString('ascii') :
// Development settings
JSON.stringify({
database: [{
username: 'dpsv',
database: 'dpsv',
password: 'password'
}]
})
).database[0];
const connObj = {
user: database.username,
database: database.database,
password: database.password
};
Promise.promisifyAll(pg, { multiArgs: true });
Promise.promisifyAll(pg.Client.prototype);
module.exports = function() {
let close;
return pg.connectAsync(connObj).spread(function(client, done) {
close = done;
return client;
}).disposer(function() {
if (close) close();
});
};
|
Use $log in error service
|
(function() {
'use strict';
angular.module('chaise.errors', [])
// Factory for each error type
.factory('ErrorService', ['$log', function ErrorService($log) {
function error409(error) {
// retry logic
// passthrough to app for now
}
// Special behavior for handling annotations not found because an
// annotation that wasn't found != a true 404 error. Just means an
// ERMrest resource doesn't have a particular annotation.
function annotationNotFound(error) {
$log.info(error);
}
return {
error409: error409,
annotationNotFound: annotationNotFound
};
}]);
})();
|
(function() {
'use strict';
angular.module('chaise.errors', [])
// Factory for each error type
.factory('ErrorService', [function ErrorService() {
function error409(error) {
// retry logic
// passthrough to app for now
}
// Special behavior for handling annotations not found because an
// annotation that wasn't found != a true 404 error. Just means an
// ERMrest resource doesn't have a particular annotation.
function annotationNotFound(error) {
console.log(error);
}
return {
error409: error409,
annotationNotFound: annotationNotFound
};
}]);
})();
|
test(lorax): Add config reset for linkToIssue tests
|
var lorax = require('../index');
var linkToIssue = lorax.linkToIssue;
exports.linkToIssueTest = {
tearDown: function(callback) {
lorax.config.reset();
callback();
},
basicTest: function(test) {
var output = linkToIssue('123');
test.equal(output, '[#123](https://github.com/adrianlee44/lorax/issues/123)');
test.done();
},
noUrlTest: function(test) {
lorax.config.set('url', '');
var output = linkToIssue('123');
test.equal(output, '#123');
test.done();
},
noIssueTemplateTest: function(test) {
lorax.config.set('issue', '');
var output = linkToIssue('123');
test.equal(output, '#123');
test.done();
},
noIssueTest: function(test) {
var output = linkToIssue();
test.equal(output, '');
test.done();
}
};
|
var lorax = require('../index');
var linkToIssue = lorax.linkToIssue;
exports.linkToIssueTest = {
basicTest: function(test) {
var output = linkToIssue('123');
test.equal(output, '[#123](https://github.com/adrianlee44/lorax/issues/123)');
test.done();
},
noUrlTest: function(test) {
lorax.config.set('url', '');
var output = linkToIssue('123');
test.equal(output, '#123');
test.done();
},
noIssueTemplateTest: function(test) {
lorax.config.set('issue', '');
var output = linkToIssue('123');
test.equal(output, '#123');
test.done();
},
noIssueTest: function(test) {
var output = linkToIssue();
test.equal(output, '');
test.done();
}
};
|
Set hostname only when not already present
|
/*
Copyright 2016 Nationale-Nederlanden
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 nl.nn.adapterframework.configuration;
import java.util.Properties;
import nl.nn.adapterframework.util.AppConstants;
import nl.nn.adapterframework.util.Misc;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
* Make the hostname property available to the Ibis configuration and the Spring
* configuration.
*
* @author Jaco de Groot
*/
public class HostnamePropertyPlaceholderConfigurer
extends PropertyPlaceholderConfigurer {
private static String HOSTNAME_PROPERTY = "hostname";
public HostnamePropertyPlaceholderConfigurer() {
setIgnoreUnresolvablePlaceholders(true);
}
@Override
protected void convertProperties(Properties props) {
AppConstants appConstants = AppConstants.getInstance();
String hostname = appConstants.getResolvedProperty(HOSTNAME_PROPERTY);
if (StringUtils.isEmpty(hostname)) {
hostname = Misc.getHostname();
appConstants.setPropertyPlaceholderConfigurerProperty(HOSTNAME_PROPERTY, hostname);
props.put(HOSTNAME_PROPERTY, hostname);
}
}
}
|
/*
Copyright 2016 Nationale-Nederlanden
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 nl.nn.adapterframework.configuration;
import java.util.Properties;
import nl.nn.adapterframework.util.AppConstants;
import nl.nn.adapterframework.util.Misc;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
* Make the hostname property available to the Ibis configuration and the Spring
* configuration.
*
* @author Jaco de Groot
*/
public class HostnamePropertyPlaceholderConfigurer
extends PropertyPlaceholderConfigurer {
public HostnamePropertyPlaceholderConfigurer() {
setIgnoreUnresolvablePlaceholders(true);
}
@Override
protected void convertProperties(Properties props) {
AppConstants appConstants = AppConstants.getInstance();
String hostname = Misc.getHostname();
appConstants.setPropertyPlaceholderConfigurerProperty("hostname", hostname);
props.put("hostname", hostname);
}
}
|
Change the redis returner to better use data structures
|
'''
Return data to a redis server
This is a VERY simple example for pushing data to a redis server and is not
nessisarily intended as a usable interface.
'''
import redis
import json
__opts__ = {
'redis.host': 'mcp',
'redis.port': 6379,
'redis.db': '0',
}
def returner(ret):
'''
Return data to a redis data store
'''
serv = redis.Redis(
host=__opts__['redis.host'],
port=__opts__['redis.port'],
db=__opts__['redis.db'])
serv.sadd(ret['id'] + 'jobs', ret['jid'])
serv.set(ret['jid'] + ':' + ret['id'], json.dumps(ret['return']))
serv.sadd('jobs', ret['jid'])
serv.sadd(ret['jid'], ret['id'])
|
'''
Return data to a redis server
This is a VERY simple example for pushing data to a redis server and is not
nessisarily intended as a usable interface.
'''
import redis
import json
__opts__ = {
'redis.host': 'mcp',
'redis.port': 6379,
'redis.db': '0',
}
def returner(ret):
'''
Return data to a redis data store
'''
serv = redis.Redis(
host=__opts__['redis.host'],
port=__opts__['redis.port'],
db=__opts__['redis.db'])
serv.set(ret['id'] + ':' + ret['jid'], json.dumps(ret['return']))
|
Fix problem with convention import
|
import {Origin} from 'aurelia-metadata';
import JadeView from './jade';
/**
Retrieves a `.jade`-type view via usual convention used by `ConventionView`.
@class JadeConventionView
@extends JadeView
@param viewModel {Object} ViewModel to determine viewUrl by convention from
@param [isCompiled] {Boolean} If true, will not attempt to use SystemJS plugin loader (i.e. no '!' suffix)
@param [extension] {String} Custom extension used for your views (defaults to `.jade.js` for compiled, `jade` for non-compiled)
**/
export default class JadeConventionView extends JadeView {
constructor(viewModel, isCompiled) {
this.moduleId = Origin.get(viewModel.constructor).moduleId;
return super(
JadeConventionView.convertModuleIdToViewUrl(this.moduleId),
isCompiled
);
}
/**
Converts a given module ID into the conventional view URL
@static
@method convertModuleIdToViewUrl
@param moduleId {String} Module ID to convert
**/
static convertModuleIdToViewUrl(moduleId, isCompiled) {
return moduleId + '.jade';
}
}
|
import {Origin} from 'aurelia-metadata';
import {JadeView} from './jade';
/**
Retrieves a `.jade`-type view via usual convention used by `ConventionView`.
@class JadeConventionView
@extends JadeView
@param viewModel {Object} ViewModel to determine viewUrl by convention from
@param [isCompiled] {Boolean} If true, will not attempt to use SystemJS plugin loader (i.e. no '!' suffix)
@param [extension] {String} Custom extension used for your views (defaults to `.jade.js` for compiled, `jade` for non-compiled)
**/
export default class JadeConventionView extends JadeView {
constructor(viewModel, isCompiled) {
this.moduleId = Origin.get(viewModel.constructor).moduleId;
return super(
JadeConventionView.convertModuleIdToViewUrl(this.moduleId),
isCompiled
);
}
/**
Converts a given module ID into the conventional view URL
@static
@method convertModuleIdToViewUrl
@param moduleId {String} Module ID to convert
**/
static convertModuleIdToViewUrl(moduleId, isCompiled) {
return moduleId + '.jade';
}
}
|
10: Test all scripts on Windows
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10
|
######
# Class for Menus
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
class cnxMenu:
def __init__( self ):
self.menuitems = []
# Function to add menuitems
def AddItem( self, text, function ):
self.menuitems.append( {'text': text, 'func':function} )
# Function for printing
def Show( self, menutitle ):
self.c = 1
print '\n\t' + menutitle
print '\t----------------------------------------', '\n'
for self.l in self.menuitems:
print '\t',
print self.c, self.l['text']
self.c += 1
print
def Do( self, n ):
self.menuitems[n]["func"]()
|
######
# Class for Menus
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
class cnxMenu:
def __init__( self ):
self.menuitems = []
# Function to add menuitems
def AddItem( self, text, function ):
self.menuitems.append( {'text': text, 'func':function} )
# Function for printing
def Show( menutitle, self ):
self.c = 1
print '\n\t' + menutitle
print '\t----------------------------------------', '\n'
for self.l in self.menuitems:
print '\t',
print self.c, self.l['text']
self.c += 1
print
def Do( self, n ):
self.menuitems[n]["func"]()
|
Remove dependence on sgapi (since we can use shotgun_api3 as well)
|
from setuptools import setup, find_packages
setup(
name='sgevents',
version='0.1-dev',
description='A simplifying Shotgun event daemon',
url='http://github.com/westernx/sgevents',
packages=find_packages(exclude=['build*', 'tests*']),
author='Mike Boers',
author_email='sgevents@mikeboers.com',
license='BSD-3',
install_requires=[
# one of `sgapi` or `shotgun_api3` is required
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from setuptools import setup, find_packages
setup(
name='sgevents',
version='0.1-dev',
description='A simplifying Shotgun event daemon',
url='http://github.com/westernx/sgevents',
packages=find_packages(exclude=['build*', 'tests*']),
author='Mike Boers',
author_email='sgevents@mikeboers.com',
license='BSD-3',
install_requires=[
'sgapi',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Set timer to poll for weather data.
|
var http = require("http");
var log4js = require("log4js");
var logger = log4js.getLogger("OpenWeatherMapAdapter");
var Q = require("q");
var _ = require("lodash");
var request = require("request");
var WeatherInterface = require("../utils/OpenWeatherMapInterface");
function OpenWeatherMapAdapter(options) {
logger.info("Creating OpenWeatherMapAdapter");
this.validateOptions(options);
this.options = options;
this.weatherInterface = new WeatherInterface(options.OpenWeatherMap);
};
OpenWeatherMapAdapter.prototype.validateOptions = function(options) {
logger.debug("Configuration options: ", options);
if(!_.has(options, "OpenWeatherMap.api_key")) {
throw new Error("Bad OpenWeatherMapAdapter configuration.");
}
};
OpenWeatherMapAdapter.prototype.start = function() {
var deferred = Q.defer();
setInterval(function() {
this.weatherInterface
.queryPostCode("OX14", "GB")
.then(function(result) {
logger.debug("Query result: ", result);
});
}.bind(this), 5000);
deferred.resolve();
return deferred.promise;
};
module.exports = OpenWeatherMapAdapter;
|
var http = require("http");
var log4js = require("log4js");
var logger = log4js.getLogger("OpenWeatherMapAdapter");
var Q = require("q");
var _ = require("lodash");
var request = require("request");
var WeatherInterface = require("../utils/OpenWeatherMapInterface");
function OpenWeatherMapAdapter(options) {
logger.info("Creating OpenWeatherMapAdapter");
this.validateOptions(options);
this.options = options;
this.weatherInterface = new WeatherInterface(options.OpenWeatherMap);
};
OpenWeatherMapAdapter.prototype.validateOptions = function(options) {
logger.debug("Configuration options: ", options);
if(!_.has(options, "OpenWeatherMap.api_key")) {
throw new Error("Bad OpenWeatherMapAdapter configuration.");
}
};
OpenWeatherMapAdapter.prototype.start = function() {
var deferred = Q.defer();
deferred.resolve();
return deferred.promise;
};
module.exports = OpenWeatherMapAdapter;
|
Add docstring. 4 spaces for consistency.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.utils
------------------
Helper functions used throughout Cookiecutter.
"""
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that a directory exists.
:param path: A directory path.
"""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
@contextlib.contextmanager
def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.utils
------------------
Helper functions used throughout Cookiecutter.
"""
import errno
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that a directory exists.
:param path: A directory path.
"""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
@contextlib.contextmanager
def work_in(dirname=None):
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
|
[FIX] Fix test after renaming the company name
|
<?php
namespace N98\Magento\Command;
use N98\Magento\Command\PHPUnit\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
class ListCommandTest extends TestCase
{
public function testExecute()
{
$command = $this->getApplication()->find('list');
$commandTester = new CommandTester($command);
$commandTester->execute(
[
'command' => 'list',
]
);
$this->assertContains(
sprintf('n98-magerun version %s by netz98 GmbH', $this->getApplication()->getVersion()),
$commandTester->getDisplay()
);
}
}
|
<?php
namespace N98\Magento\Command;
use N98\Magento\Command\PHPUnit\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
class ListCommandTest extends TestCase
{
public function testExecute()
{
$command = $this->getApplication()->find('list');
$commandTester = new CommandTester($command);
$commandTester->execute(
array(
'command' => 'list',
)
);
$this->assertContains(
sprintf('n98-magerun version %s by netz98 new media GmbH', $this->getApplication()->getVersion()),
$commandTester->getDisplay()
);
}
}
|
Use uint64 for bandwidth capability
Signed-off-by: Johannes M. Scheuermann <84221072773eb526ff46440bf01afde36bd32e36@gmail.com>
|
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cni
const (
CNIPluginName = "cni"
DefaultNetDir = "/etc/cni/net.d"
DefaultCNIDir = "/opt/cni/bin"
VendorCNIDirTemplate = "%s/opt/%s/bin"
DefaultPrefix = "eth"
)
type config struct {
pluginDirs []string
pluginConfDir string
prefix string
}
type PortMapping struct {
HostPort int32
ContainerPort int32
Protocol string
HostIP string
}
type IPRanges struct {
Subnet string
RangeStart string
RangeEnd string
Gateway string
}
// BandWidth defines the ingress/egress rate and burst limits
type BandWidth struct {
IngressRate uint64
IngressBurst uint64
EgressRate uint64
EgressBurst uint64
}
|
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cni
const (
CNIPluginName = "cni"
DefaultNetDir = "/etc/cni/net.d"
DefaultCNIDir = "/opt/cni/bin"
VendorCNIDirTemplate = "%s/opt/%s/bin"
DefaultPrefix = "eth"
)
type config struct {
pluginDirs []string
pluginConfDir string
prefix string
}
type PortMapping struct {
HostPort int32
ContainerPort int32
Protocol string
HostIP string
}
type IPRanges struct {
Subnet string
RangeStart string
RangeEnd string
Gateway string
}
// BandWidth defines the ingress/egress rate and burst limits
type BandWidth struct {
IngressRate int
IngressBurst int
EgressRate int
EgressBurst int
}
|
Use linear models by default
|
import data
import model
import numpy as np
from keras import optimizers
# Localize data through file system relative indexing method
path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy'
# Use data loading library to load data
a, b, y = data.generate_learning_set(np.load(path))
# Generate the model
embedding_model, siamese_model = model.make_linear_models(a.shape[1])
optimizer = optimizers.SGD(lr=0.00001, momentum=0.9, nesterov=True)
# optimizer = optimizers.Adam(lr=0.0001)
siamese_model.compile(optimizer=optimizer, loss='binary_crossentropy',
metrics=['accuracy'])
print("data shapes:")
print(a.shape)
print(b.shape)
print(y.shape)
trace = siamese_model.fit([a, b], y, validation_split=0.2, epochs=30,
batch_size=16, shuffle=True)
print(trace.history['acc'][-1])
print(trace.history['val_acc'][-1])
|
import data
import model
import numpy as np
from keras import optimizers
# Localize data through file system relative indexing method
path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy'
# Use data loading library to load data
a, b, y = data.generate_learning_set(np.load(path))
# Generate the model
embedding_model, siamese_model = model.make_mlp_models(a.shape[1], embedding_dropout=0.2)
optimizer = optimizers.SGD(lr=0.00001, momentum=0.9, nesterov=True)
# optimizer = optimizers.Adam(lr=0.0001)
siamese_model.compile(optimizer=optimizer, loss='binary_crossentropy',
metrics=['accuracy'])
print(a.shape)
print(a[:10])
trace = siamese_model.fit([a, b], y, validation_split=0.2, epochs=30,
batch_size=16)
print(trace.history['acc'][-1])
print(trace.history['val_acc'][-1])
|
Add IL relevant article body links
|
$(function() {
// Body headings
$('h1.juttuotsikko span.otsikko:last-of-type').each(function() {
// Some of the center title spans on Iltalehti have manual <br /> elements
// inside of them, which our satanify plugin isn't smart enough to handle
// yet. Hack around it with this for now.
var contents = $(this).contents();
if (contents != null && contents.length > 0) {
var last = contents.last()[0];
last.textContent = satanify(last.textContent);
}
});
$('li a[class^=bi3dArtId-]').satanify();
// Left
$('#container_vasen p a:not(.palstakuva)').satanify(' ');
// Right
$('#container_oikea [class$=link-list] p a:not(.palstakuva)').satanify(' ');
$('#container_oikea .widget a .list-title').satanify();
// Footer
$('.footer_luetuimmat_container .list-title').satanify();
});
|
$(function() {
// Body headings
$('h1.juttuotsikko span.otsikko:last-of-type').each(function() {
// Some of the center title spans on Iltalehti have manual <br /> elements
// inside of them, which our satanify plugin isn't smart enough to handle
// yet. Hack around it with this for now.
var contents = $(this).contents();
if (contents != null && contents.length > 0) {
var last = contents.last()[0];
last.textContent = satanify(last.textContent);
}
});
// Left
$('#container_vasen p a:not(.palstakuva)').satanify(' ');
// Right
$('#container_oikea [class$=link-list] p a:not(.palstakuva)').satanify(' ');
$('#container_oikea .widget a .list-title').satanify();
// Footer
$('.footer_luetuimmat_container .list-title').satanify();
});
|
openstack: Disable template rendering for OpenStack
|
package machines
import (
"bytes"
"encoding/base64"
"text/template"
"github.com/pkg/errors"
)
var userDataListTmpl = template.Must(template.New("user-data-list").Parse(`
kind: List
apiVersion: v1
metadata:
resourceVersion: ""
selfLink: ""
items:
{{- range $name, $content := . }}
- apiVersion: v1
kind: Secret
metadata:
name: {{$name}}
namespace: openshift-machine-api
type: Opaque
data:
disableTemplating: "dHJ1ZQo="
userData: {{$content}}
{{- end}}
`))
func userDataList(data map[string][]byte) ([]byte, error) {
encodedData := map[string]string{}
for name, content := range data {
encodedData[name] = base64.StdEncoding.EncodeToString(content)
}
buf := &bytes.Buffer{}
if err := userDataListTmpl.Execute(buf, encodedData); err != nil {
return nil, errors.Wrap(err, "failed to execute content.UserDataListTmpl")
}
return buf.Bytes(), nil
}
|
package machines
import (
"bytes"
"encoding/base64"
"text/template"
"github.com/pkg/errors"
)
var userDataListTmpl = template.Must(template.New("user-data-list").Parse(`
kind: List
apiVersion: v1
metadata:
resourceVersion: ""
selfLink: ""
items:
{{- range $name, $content := . }}
- apiVersion: v1
kind: Secret
metadata:
name: {{$name}}
namespace: openshift-machine-api
type: Opaque
data:
userData: {{$content}}
{{- end}}
`))
func userDataList(data map[string][]byte) ([]byte, error) {
encodedData := map[string]string{}
for name, content := range data {
encodedData[name] = base64.StdEncoding.EncodeToString(content)
}
buf := &bytes.Buffer{}
if err := userDataListTmpl.Execute(buf, encodedData); err != nil {
return nil, errors.Wrap(err, "failed to execute content.UserDataListTmpl")
}
return buf.Bytes(), nil
}
|
Remove dependency to jQuery library
|
(function(window) {
"use strict";
var
prev = window.oops || null,
curr = function(){};
curr.prev = function(){ return prev; };
curr.typing = {
isObject: function( value, strict ){
var result = ( typeof value === 'object' );
strict = strict || false;
result = result || ( strict ? false : (typeof value === 'function'));
result = result && ( strict ? !Array.isArray(value) : true );
return !!( value && result );
},
isCallable: function( value ){
return (typeof value === 'function');
},
isArray: Array.isArray,
isString: function( value ) { return (typeof value === 'string'); }
};
curr.core = {
expand: function( target, source, overwrite ){
overwrite = overwrite || false;
if ( !curr.typing.isObject( source ) || !curr.typing.isObject( target ) ) return;
for ( var prop in source )
{
if ( !source.hasOwnProperty( prop ) ) continue;
if ( !overwrite && target.hasOwnProperty( prop ) ) continue;
target[ prop ] = source[ prop ];
}
}
};
window.oops = curr;
})(window);
|
(function($, window) {
"use strict";
var
prev = window.oops || null,
curr = function(){};
curr.prev = function(){ return prev; };
curr.typing = {
isObject: function( value, strict ){
var result = ( typeof value === 'object' );
strict = strict || false;
result = result || ( strict ? false : (typeof value === 'function'));
result = result && ( strict ? !Array.isArray(value) : true );
return !!( value && result );
},
isCallable: function( value ){
return (typeof value === 'function');
},
isArray: Array.isArray,
isString: function( value ) { return (typeof value === 'string'); }
};
curr.core = {
expand: function( target, source, overwrite ){
overwrite = overwrite || false;
if ( !curr.typing.isObject( source ) || !curr.typing.isObject( target ) ) return;
for ( var prop in source )
{
if ( !source.hasOwnProperty( prop ) ) continue;
if ( !overwrite && target.hasOwnProperty( prop ) ) continue;
target[ prop ] = source[ prop ];
}
}
};
window.oops = curr;
})(jQuery, window);
|
Use implicit ordering of AsyncIndicator model
|
from __future__ import absolute_import
from __future__ import division
from datetime import datetime
from django.db.models import Min
from corehq.apps.userreports.models import AsyncIndicator
from corehq.apps.userreports.reports.view import CustomConfigurableReport
class MonitoredReport(CustomConfigurableReport):
"""For reports backed by an async datasource, shows an indication of how far
behind the report might be, in increments of 12 hours.
"""
template_name = 'enikshay/ucr/monitored_report.html'
@property
def page_context(self):
context = super(MonitoredReport, self).page_context
context['hours_behind'] = self.hours_behind()
return context
def hours_behind(self):
"""returns the number of hours behind this report is, to the nearest 12 hour bucket.
"""
now = datetime.utcnow()
try:
oldest_indicator = (
AsyncIndicator.objects
.filter(indicator_config_ids__contains=[self.spec.config_id])
)[0]
hours_behind = (now - oldest_indicator.date_created).total_seconds() / (60 * 60)
return int(1 + (hours_behind // 12)) * 12
except IndexError:
return None
|
from __future__ import absolute_import
from __future__ import division
from datetime import datetime
from django.db.models import Min
from corehq.apps.userreports.models import AsyncIndicator
from corehq.apps.userreports.reports.view import CustomConfigurableReport
class MonitoredReport(CustomConfigurableReport):
"""For reports backed by an async datasource, shows an indication of how far
behind the report might be, in increments of 12 hours.
"""
template_name = 'enikshay/ucr/monitored_report.html'
@property
def page_context(self):
context = super(MonitoredReport, self).page_context
context['hours_behind'] = self.hours_behind()
return context
def hours_behind(self):
"""returns the number of hours behind this report is, to the nearest 12 hour bucket.
"""
now = datetime.utcnow()
oldest_indicator = (
AsyncIndicator.objects
.filter(indicator_config_ids__contains=[self.spec.config_id])
.aggregate(Min('date_created'))
)
if oldest_indicator['date_created__min'] is not None:
hours_behind = (now - oldest_indicator['date_created__min']).total_seconds() / (60 * 60)
return int(1 + (hours_behind // 12)) * 12
return None
|
Unittests: Remove some more unneccesary code.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
def test_do_GET(self):
for mock_recovery in [True, False]:
for page in [b'GET /pg_master', b'GET /pg_slave', b'GET /pg_status', b'GET /not_found']:
self.http_server = MockServer(('0.0.0.0', 8888), StatusPage, page, mock_recovery)
class MockRequest(object):
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
return IO(self.path)
class MockServer(object):
def __init__(self, ip_port, Handler, path, mock_recovery=False):
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
if __name__ == '__main__':
unittest.main()
|
Update DiscordBot: Shorter game setting & don't respond to bots
|
const Discord = require('discord.js');
const client = new Discord.Client();
// https://discordapp.com/oauth2/authorize?&client_id=368144406181838861&scope=bot&permissions=3072
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setGame('WoWAnalyzer.com');
});
client.on('message', msg => {
if (msg.author.bot) {
return;
}
const content = msg.content;
// TODO: create a group for the # part of the WCL URL
const match = content.trim().match(/^(.*reports\/)?([a-zA-Z0-9]{16})\/?(#.*)?(.*)?$/);
if (match && match[2]) {
// TODO: filter for fight=XX and source=XX for #444
msg.channel.send(`https://wowanalyzer.com/report/${match[2]}`);
}
});
client.login(process.env.DISCORD_TOKEN);
|
const Discord = require('discord.js');
const client = new Discord.Client();
// https://discordapp.com/oauth2/authorize?&client_id=368144406181838861&scope=bot&permissions=3072
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
game: {
name: 'WoWAnalyzer.com',
type: 0,
},
});
});
client.on('message', msg => {
const content = msg.content;
// TODO: create a group for the # part of the WCL URL
const match = content.trim().match(/^(.*reports\/)?([a-zA-Z0-9]{16})\/?(#.*)?(.*)?$/);
if (match && match[2]) {
// TODO: filter for fight=XX and source=XX for #444
msg.channel.send(`https://wowanalyzer.com/report/${match[2]}`);
}
});
client.login(process.env.DISCORD_TOKEN);
|
[desk-tool] Handle drafts/missing documents when checking for type mismatch
|
import React from 'react'
import styles from './styles/DeskTool.css'
import SchemaPaneResolver from './SchemaPaneResolver'
import client from 'part:@sanity/base/client'
import {withRouterHOC} from 'part:@sanity/base/router'
import PropTypes from 'prop-types'
export default withRouterHOC(class DeskTool extends React.Component {
static propTypes = {
router: PropTypes.shape({
state: PropTypes.object
}).isRequired
}
componentDidMount() {
const {router} = this.props
const {selectedType, selectedDocumentId} = router.state
if (selectedDocumentId && selectedType) {
client.fetch(`*[_id == "${selectedDocumentId}" || _id == "drafts.${selectedDocumentId}"][0]._type`)
.then(type => {
if (type && type !== selectedType) {
router.navigate({...router.state, selectedType: type}, {replace: true})
}
})
}
}
render() {
const {router} = this.props
return (
<div className={styles.deskTool}>
<SchemaPaneResolver router={router} />
</div>
)
}
})
|
import React from 'react'
import styles from './styles/DeskTool.css'
import SchemaPaneResolver from './SchemaPaneResolver'
import client from 'part:@sanity/base/client'
import {withRouterHOC} from 'part:@sanity/base/router'
import PropTypes from 'prop-types'
export default withRouterHOC(class DeskTool extends React.Component {
static propTypes = {
router: PropTypes.shape({
state: PropTypes.object
}).isRequired
}
componentDidMount() {
const {router} = this.props
const {selectedType, selectedDocumentId} = router.state
if (selectedDocumentId && selectedType) {
client.fetch('*[_id == $id][0]._type', {id: selectedDocumentId})
.then(type => {
if (type !== selectedType) {
router.navigate({...router.state, selectedType: type}, {replace: true})
}
})
}
}
render() {
const {router} = this.props
return (
<div className={styles.deskTool}>
<SchemaPaneResolver router={router} />
</div>
)
}
})
|
Change algorithmia-api-client dependency from a version to a version range
|
import os
from setuptools import setup
setup(
name='algorithmia',
version='1.1.4',
description='Algorithmia Python Client',
long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithmia.',
url='http://github.com/algorithmiaio/algorithmia-python',
license='MIT',
author='Algorithmia',
author_email='support@algorithmia.com',
packages=['Algorithmia'],
install_requires=[
'requests',
'six',
'enum34',
'algorithmia-api-client>=1.0.0,<2.0'
],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'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.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
import os
from setuptools import setup
setup(
name='algorithmia',
version='1.1.4',
description='Algorithmia Python Client',
long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithmia.',
url='http://github.com/algorithmiaio/algorithmia-python',
license='MIT',
author='Algorithmia',
author_email='support@algorithmia.com',
packages=['Algorithmia'],
install_requires=[
'requests',
'six',
'enum34',
'algorithmia-api-client==1.0.0'
],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'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.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Trim fetch data to remove errors with extra spaces in data
|
import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import qs from 'query-string';
const fetchGhgEmissionsInit = createAction('fetchGhgEmissionsInit');
const fetchGhgEmissionsFail = createAction('fetchGhgEmissionsFail');
const fetchGhgEmissionsDataReady = createAction('fetchGhgEmissionsDataReady');
const fetchGhgEmissionsData = createThunkAction(
'fetchGhgEmissionsData',
filters => dispatch => {
dispatch(fetchGhgEmissionsInit());
fetch(`/api/v1/emissions?${qs.stringify(filters)}`)
.then(response => {
if (response.ok) return response.json();
throw Error(response.statusText);
})
.then(data => {
const parsedData = data.map(d => ({
...d,
gas: d.gas.trim(),
sector: d.sector.trim(),
location: d.location.trim()
}));
dispatch(fetchGhgEmissionsDataReady(parsedData));
})
.catch(error => {
console.warn(error);
dispatch(fetchGhgEmissionsFail());
});
}
);
export default {
fetchGhgEmissionsInit,
fetchGhgEmissionsFail,
fetchGhgEmissionsData,
fetchGhgEmissionsDataReady
};
|
import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import qs from 'query-string';
const fetchGhgEmissionsInit = createAction('fetchGhgEmissionsInit');
const fetchGhgEmissionsFail = createAction('fetchGhgEmissionsFail');
const fetchGhgEmissionsDataReady = createAction('fetchGhgEmissionsDataReady');
const fetchGhgEmissionsData = createThunkAction(
'fetchGhgEmissionsData',
filters => dispatch => {
dispatch(fetchGhgEmissionsInit());
fetch(`/api/v1/emissions?${qs.stringify(filters)}`)
.then(response => {
if (response.ok) return response.json();
throw Error(response.statusText);
})
.then(data => {
dispatch(fetchGhgEmissionsDataReady(data));
})
.catch(error => {
console.warn(error);
dispatch(fetchGhgEmissionsFail());
});
}
);
export default {
fetchGhgEmissionsInit,
fetchGhgEmissionsFail,
fetchGhgEmissionsData,
fetchGhgEmissionsDataReady
};
|
Disable Sunrise/Sunset in Config option
|
/* Magic Mirror Test config default weather
*
* By fewieden https://github.com/fewieden
*
* MIT Licensed.
*/
let config = {
port: 8080,
ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"],
language: "en",
timeFormat: 24,
units: "metric",
electronOptions: {
webPreferences: {
nodeIntegration: true
}
},
modules: [
{
module: "weather",
position: "bottom_bar",
config: {
location: "Munich",
apiKey: "fake key",
initialLoadDelay: 3000,
useBeaufort: false,
showWindDirectionAsArrow: true,
showSun: false,
showHumidity: true,
roundTemp: true,
degreeLabel: true
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}
|
/* Magic Mirror Test config default weather
*
* By fewieden https://github.com/fewieden
*
* MIT Licensed.
*/
let config = {
port: 8080,
ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"],
language: "en",
timeFormat: 24,
units: "metric",
electronOptions: {
webPreferences: {
nodeIntegration: true
}
},
modules: [
{
module: "weather",
position: "bottom_bar",
config: {
location: "Munich",
apiKey: "fake key",
initialLoadDelay: 3000,
useBeaufort: false,
showWindDirectionAsArrow: true,
showHumidity: true,
roundTemp: true,
degreeLabel: true
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}
|
Break down possible transformer errors for debugability
|
var _ = require('underscore');
var path = require('path');
module.exports = function (transformer) {
transformer = _.clone(transformer);
if (_.isString(transformer)) transformer = {name: transformer};
if (!transformer.options) transformer.options = {};
var name = transformer.name;
var packageName = 'cogs-transformer-' + name;
var requirePath;
try { requirePath = require.resolve(path.resolve(name)); } catch (er) {
try { requirePath = require.resolve(packageName); } catch (er) {
throw new Error(
"Cannot find transformer '" + name + "'\n" +
' Did you forget to `npm install ' + packageName + '`?'
);
}}
try { transformer.fn = require(requirePath); } catch (er) {
throw _.extend(er, {
message: "Failed to load '" + name + "'\n " + er.message
});
}
var package;
try { package = require(path.dirname(requirePath) + '/package'); }
catch (er) {
try { package = require(packageName + '/package'); } catch (er) {
throw new Error(
"Cannot find package file for '" + name + "'\n" +
' Transformers are required to have a package file'
);
}}
try {
transformer.version = package.version;
if (!transformer.version) throw new Error();
} catch (er) {
throw new Error(
"Cannot find version in package file for '" + name + "'\n" +
' Transformers are required to specify a version in their package file'
);
}
return transformer;
};
|
var _ = require('underscore');
var path = require('path');
module.exports = function (transformer) {
transformer = _.clone(transformer);
if (_.isString(transformer)) transformer = {name: transformer};
if (!transformer.options) transformer.options = {};
var name = transformer.name;
var packageName = 'cogs-transformer-' + name;
var requirePath;
try { requirePath = require.resolve(path.resolve(name)); } catch (er) {
try { requirePath = require.resolve(packageName); } catch (er) {
throw new Error(
"Cannot find transformer '" + name + "'\n" +
' Did you forget to `npm install ' + packageName + '`?'
);
}}
try { transformer.fn = require(requirePath); } catch (er) {
throw _.extend(er, {
message: "Failed to load '" + name + "'\n " + er.message
});
}
try {
transformer.version = require(packageName + '/package').version;
if (!transformer.version) throw new Error();
} catch (er) {
throw new Error(
"Cannot find package version for '" + name + "'\n" +
' Transformers are required to specifiy a version in their package file'
);
}
return transformer;
};
|
Update clear:archives to clear archives older than a month instead of a week
|
<?php
namespace App\Console\Commands;
use File;
use Artisan;
use App\Archive;
use Illuminate\Console\Command;
class ClearOldArchives extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'clear:archives';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Delete archives that are older than a month';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if (env('APP_ENV') == 'local')
$archives = Archive::all();
else
$archives = Archive::where('created_at', '<', \Carbon\Carbon::now()->subMonth())->get();
foreach ($archives as $archive) {
File::delete(storage_path('app/Archives/' . $archive->filename));
$archive->delete();
}
}
}
|
<?php
namespace App\Console\Commands;
use File;
use Artisan;
use App\Archive;
use Illuminate\Console\Command;
class ClearOldArchives extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'clear:archives';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Delete archives that are older than a week';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if (env('APP_ENV') == 'local')
$archives = Archive::all();
else
$archives = Archive::where('created_at', '<', \Carbon\Carbon::now()->subWeek())->get();
foreach ($archives as $archive) {
File::delete(storage_path('app/Archives/' . $archive->filename));
$archive->delete();
}
}
}
|
Handle no protocols in tests
|
const protocols = require("../lib")
, tester = require("tester")
;
tester.describe("check urls", test => {
test.it("should support mutiple protocols", () => {
test.expect(protocols("git+ssh://git@some-host.com/and-the-path/name")).toEqual(["git", "ssh"]);
});
test.it("should detect no protocols", () => {
test.expect(protocols("//foo.com/bar.js")).toEqual([]);
});
test.it("should support one protocol", () => {
test.expect(protocols("ssh://git@some-host.com/and-the-path/name")).toEqual(["ssh"]);
});
test.it("should support taking the first protocol", () => {
test.expect(protocols("git+ssh://git@some-host.com/and-the-path/name", true)).toBe("git");
});
test.it("should support taking the second protocol", () => {
test.expect(protocols("git+ssh://git@some-host.com/and-the-path/name", 1)).toBe("ssh");
});
});
|
const protocols = require("../lib")
, tester = require("tester")
;
tester.describe("check urls", test => {
test.it("should support mutiple protocols", () => {
test.expect(protocols("git+ssh://git@some-host.com/and-the-path/name")).toEqual(["git", "ssh"]);
});
test.it("should support one protocol", () => {
test.expect(protocols("ssh://git@some-host.com/and-the-path/name")).toEqual(["ssh"]);
});
test.it("should support taking the first protocol", () => {
test.expect(protocols("git+ssh://git@some-host.com/and-the-path/name", true)).toBe("git");
});
test.it("should support taking the second protocol", () => {
test.expect(protocols("git+ssh://git@some-host.com/and-the-path/name", 1)).toBe("ssh");
});
});
|
Delete unused import of NOT_READY_YET
|
# -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from twisted.web.resource import Resource
import synapse.metrics
METRICS_PREFIX = "/_synapse/metrics"
class MetricsResource(Resource):
isLeaf = True
def __init__(self, hs):
Resource.__init__(self) # Resource is old-style, so no super()
self.hs = hs
def render_GET(self, request):
response = synapse.metrics.render_all()
request.setHeader("Content-Type", "text/plain")
request.setHeader("Content-Length", str(len(response)))
# Encode as UTF-8 (default)
return response.encode()
|
# -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
import synapse.metrics
METRICS_PREFIX = "/_synapse/metrics"
class MetricsResource(Resource):
isLeaf = True
def __init__(self, hs):
Resource.__init__(self) # Resource is old-style, so no super()
self.hs = hs
def render_GET(self, request):
response = synapse.metrics.render_all()
request.setHeader("Content-Type", "text/plain")
request.setHeader("Content-Length", str(len(response)))
# Encode as UTF-8 (default)
return response.encode()
|
Remove events_type from alert test case
|
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
|
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], events_type='event', expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.events_type = events_type
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.