text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix typo in class name
|
const BaseChecker = require('./../base-checker');
class BaseDeprecation extends BaseChecker {
constructor(reporter) {
super(reporter);
this.active = false;
this.deprecationVersion(); // to ensure we have one.
}
exitPragmaDirective(ctx) {
const pragma = ctx.children[1].getText();
const value = ctx.children[2].getText();
if(pragma === 'solidity') {
var contextVersion = value.replace(/[^0-9.]/g, '').split('.');
var deprecationAt = this.deprecationVersion().split('.');
this.active =
contextVersion[0] > deprecationAt[0] ||
contextVersion[1] > deprecationAt[1] ||
contextVersion[2] >= deprecationAt[2];
this.version = value;
}
}
deprecationVersion() {
throw new Error('Implementations must supply a deprecation version!');
}
}
module.exports = BaseDeprecation;
|
const BaseChecker = require('./../base-checker');
class BaseDecprecation extends BaseChecker {
constructor(reporter) {
super(reporter);
this.active = false;
this.deprecationVersion(); // to ensure we have one.
}
exitPragmaDirective(ctx) {
const pragma = ctx.children[1].getText();
const value = ctx.children[2].getText();
if(pragma === 'solidity') {
var contextVersion = value.replace(/[^0-9.]/g, '').split('.');
var deprecationAt = this.deprecationVersion().split('.');
this.active =
contextVersion[0] > deprecationAt[0] ||
contextVersion[1] > deprecationAt[1] ||
contextVersion[2] >= deprecationAt[2];
this.version = value;
}
}
deprecationVersion() {
throw new Error('Implementations must supply a deprecation version!');
}
}
module.exports = BaseDecprecation;
|
Breaking: Switch settle flag to an env variable
|
'use strict';
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var DefaultRegistry = require('undertaker-registry');
var get = require('./lib/get');
var set = require('./lib/set');
var tree = require('./lib/tree');
var task = require('./lib/task');
var series = require('./lib/series');
var lastRun = require('./lib/last-run');
var parallel = require('./lib/parallel');
var registry = require('./lib/registry');
var validateRegistry = require('./lib/helpers/validateRegistry');
function Undertaker(Registry){
var self = this;
EventEmitter.call(this);
Registry = Registry || DefaultRegistry;
this._registry = new Registry();
this._settle = (process.env.UNDERTAKER_SETTLE === 'true');
validateRegistry(this._registry);
this._lastRuns = {};
this.on('stop', function(e){
self._lastRuns[e.name] = e.time;
});
}
inherits(Undertaker, EventEmitter);
Undertaker.prototype.get = get;
Undertaker.prototype.set = set;
Undertaker.prototype.tree = tree;
Undertaker.prototype.task = task;
Undertaker.prototype.series = series;
Undertaker.prototype.lastRun = lastRun;
Undertaker.prototype.parallel = parallel;
Undertaker.prototype.registry = registry;
module.exports = Undertaker;
|
'use strict';
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var DefaultRegistry = require('undertaker-registry');
var get = require('./lib/get');
var set = require('./lib/set');
var tree = require('./lib/tree');
var task = require('./lib/task');
var series = require('./lib/series');
var lastRun = require('./lib/last-run');
var parallel = require('./lib/parallel');
var registry = require('./lib/registry');
var validateRegistry = require('./lib/helpers/validateRegistry');
function Undertaker(Registry){
var self = this;
EventEmitter.call(this);
Registry = Registry || DefaultRegistry;
this._registry = new Registry();
this._settle = (process.argv.indexOf('--undertaker-settle') !== -1);
validateRegistry(this._registry);
this._lastRuns = {};
this.on('stop', function(e){
self._lastRuns[e.name] = e.time;
});
}
inherits(Undertaker, EventEmitter);
Undertaker.prototype.get = get;
Undertaker.prototype.set = set;
Undertaker.prototype.tree = tree;
Undertaker.prototype.task = task;
Undertaker.prototype.series = series;
Undertaker.prototype.lastRun = lastRun;
Undertaker.prototype.parallel = parallel;
Undertaker.prototype.registry = registry;
module.exports = Undertaker;
|
Fix whitespace errors and line lengths
|
# pipeunion.py
#
from pipe2py import util
def pipe_union(context, _INPUT, **kwargs):
"""This operator merges up to 5 source together.
Keyword arguments:
context -- pipeline context
_INPUT -- source generator
kwargs -- _OTHER1 - another source generator
_OTHER2 etc.
Yields (_OUTPUT):
union of all source items
"""
#TODO the multiple sources should be pulled in parallel
# check David Beazely for suggestions (co-routines with queues?)
# or maybe use multiprocessing and Queues (perhaps over multiple servers too)
#Single thread and sequential pulling will do for now...
for item in _INPUT:
#this is being fed forever, i.e. not a real source so just use _OTHERs
if item == True:
break
yield item
for other in kwargs:
if other.startswith('_OTHER'):
for item in kwargs[other]:
yield item
|
# pipeunion.py
#
from pipe2py import util
def pipe_union(context, _INPUT, **kwargs):
"""This operator merges up to 5 source together.
Keyword arguments:
context -- pipeline context
_INPUT -- source generator
kwargs -- _OTHER1 - another source generator
_OTHER2 etc.
Yields (_OUTPUT):
union of all source items
"""
#TODO the multiple sources should be pulled in parallel
# check David Beazely for suggestions (co-routines with queues?)
# or maybe use multiprocessing and Queues (perhaps over multiple servers too)
#Single thread and sequential pulling will do for now...
for item in _INPUT:
if item == True: #i.e. this is being fed forever, i.e. not a real source so just use _OTHERs
break
yield item
for other in kwargs:
if other.startswith('_OTHER'):
for item in kwargs[other]:
yield item
|
Fix package data (str to [])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from distutils.core import setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-zxcvbn-password',
version='1.0.3.0',
packages=['zxcvbn_password'],
package_data={'': ['*.js']},
include_package_data=True,
license='BSD License',
author='Timothée Mazzucotelli',
author_email='timothee.mazzucotelli@gmail.com',
url='https://github.com/Pawamoy/django-zxcvbn-password',
# download_url = 'https://github.com/Pawamoy/django-zxcvbn-password/tarball/1.0.2',
keywords="password validation front back zxcvbn confirmation field",
description="A front-end and back-end password validation field using ZXCVBN.",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Programming Language :: Python",
"Operating System :: OS Independent",
"License :: OSI Approved :: BSD License",
]
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from distutils.core import setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-zxcvbn-password',
version='1.0.3.0',
packages=['zxcvbn_password'],
package_data={'': '*.js'},
include_package_data=True,
license='BSD License',
author='Timothée Mazzucotelli',
author_email='timothee.mazzucotelli@gmail.com',
url='https://github.com/Pawamoy/django-zxcvbn-password',
# download_url = 'https://github.com/Pawamoy/django-zxcvbn-password/tarball/1.0.2',
keywords="password validation front back zxcvbn confirmation field",
description="A front-end and back-end password validation field using ZXCVBN.",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Programming Language :: Python",
"Operating System :: OS Independent",
"License :: OSI Approved :: BSD License",
]
)
|
Fix test vs parameterized setup/teardown function names
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
def track_param(n):
return 42
track_param.params = [10, 20]
def mem_param(n, m):
return [[0]*m]*n
mem_param.params = ([10, 20], [2, 3])
mem_param.param_names = ['number', 'depth']
class ParamSuite:
params = ['a', 'b', 'c']
def setup(self):
self.values = {'a': 1, 'b': 2, 'c': 3}
self.count = 0
def setup_params(self, p):
self.value = self.values[p]
def track_value(self, p):
return self.value + self.count
def teardown_params(self, p):
self.count += 1
del self.value
def teardown(self):
del self.values
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
def track_param(n):
return 42
track_param.params = [10, 20]
def mem_param(n, m):
return [[0]*m]*n
mem_param.params = ([10, 20], [2, 3])
mem_param.param_names = ['number', 'depth']
class ParamSuite:
params = ['a', 'b', 'c']
def setup(self):
self.values = {'a': 1, 'b': 2, 'c': 3}
self.count = 0
def setup_param(self, p):
self.value = self.values[p]
def track_value(self, p):
return self.value + self.count
def teardown_param(self, p):
self.count += 1
del self.value
def teardown(self):
del self.values
|
Fix the use of runtimeCatalogueLocal
|
import SandboxBrowser from '../sandboxes/SandboxBrowser';
import AppSandboxBrowser from '../sandboxes/AppSandboxBrowser';
import Request from '../browser/Request';
import {RuntimeCatalogue} from 'service-framework/dist/RuntimeCatalogue';
import PersistenceManager from 'service-framework/dist/PersistenceManager';
const runtimeFactory = Object.create({
createSandbox() {
return new SandboxBrowser();
},
createAppSandbox() {
return new AppSandboxBrowser();
},
createHttpRequest() {
let request = new Request();
return request;
},
atob(b64) {
return atob(b64);
},
persistenceManager() {
let localStorage = window.localStorage;
return new PersistenceManager(localStorage);
},
createRuntimeCatalogue(development) {
if (!this.catalogue)
this.catalogue = new RuntimeCatalogue(this);
return this.catalogue;
}
});
export default runtimeFactory;
|
import SandboxBrowser from '../sandboxes/SandboxBrowser';
import AppSandboxBrowser from '../sandboxes/AppSandboxBrowser';
import Request from '../browser/Request';
import {RuntimeCatalogue, RuntimeCatalogueLocal} from 'service-framework/dist/RuntimeCatalogue';
import PersistenceManager from 'service-framework/dist/PersistenceManager';
const runtimeFactory = Object.create({
createSandbox() {
return new SandboxBrowser();
},
createAppSandbox() {
return new AppSandboxBrowser();
},
createHttpRequest() {
let request = new Request();
return request;
},
atob(b64) {
return atob(b64);
},
persistenceManager() {
let localStorage = window.localStorage;
return new PersistenceManager(localStorage);
},
createRuntimeCatalogue(development) {
if (!this.catalogue)
this.catalogue = development ? new RuntimeCatalogueLocal(this) : new RuntimeCatalogue(this);
return this.catalogue;
}
});
export default runtimeFactory;
|
Make sure tumor-type config ignores spaces
|
#!/usr/bin/env python
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True)
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
|
#!/usr/bin/env python
import os.path as path
import sys
import csv
TUMOR_CONFIG_DIALECT = "tumor-type-config"
csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n')
_relpath_configfile = path.join('config', 'tumorTypesConfig.csv')
_configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT}', _relpath_configfile))
print (_configfile)
if not path.exists(_configfile):
# KLUDGE
_configfile = path.join(path.dirname(path.dirname(path.dirname(path.abspath(sys.modules[__name__].__file__)))), _relpath_configfile)
if not path.exists(_configfile):
print("cannot find tumor-type configuration file")
sys.exit(1)
tumorTypeConfig = { }
with open(_configfile) as tsv:
for tumorType in csv.DictReader(tsv, dialect=TUMOR_CONFIG_DIALECT):
tumorTypeConfig[tumorType['name']] = tumorType
|
Remove '-' as valid char for a named prepared value
Otherwise it might break code like "SELECT :value1-:value2"
|
var SqlString = require('mysql/lib/protocol/SqlString');
//save the original format function
var formatIndexArray = SqlString.format;
/*
This functiona allows to pass an object as value container
to insert those values into the sql query the following format is used:
::indentifier
:value
*/
var formatNamedObject = function formatNamedObject(sql, values, stringifyObjects, timeZone) {
values = values || {};
return sql.replace(/(::?)([a-zA-Z][a-zA-Z0-9_]*)/g, function(match, type, name) {
/*
TODO why was this added in the original code of the mysql library?
if (!values.length) {
return match;
}
*/
//TODO check if name is in values
if (type === '::') {
return SqlString.escapeId(values[name]);
}
return SqlString.escape(values[name], stringifyObjects, timeZone);
});
};
SqlString.format = function(sql, values, stringifyObjects, timeZone) {
if (values instanceof Array) {
//TODO we have to check if it is array like object.
// only array-link or array object will work.
return formatIndexArray.apply(this, arguments);
} else {
return formatNamedObject.apply(this, arguments);
}
};
|
var SqlString = require('mysql/lib/protocol/SqlString');
//save the original format function
var formatIndexArray = SqlString.format;
/*
This functiona allows to pass an object as value container
to insert those values into the sql query the following format is used:
::indentifier
:value
*/
var formatNamedObject = function formatNamedObject(sql, values, stringifyObjects, timeZone) {
values = values || {};
return sql.replace(/(::?)([a-zA-Z][a-zA-Z0-9_-]*)/g, function(match, type, name) {
/*
TODO why was this added in the original code of the mysql library?
if (!values.length) {
return match;
}
*/
//TODO check if name is in values
if (type === '::') {
return SqlString.escapeId(values[name]);
}
return SqlString.escape(values[name], stringifyObjects, timeZone);
});
};
SqlString.format = function(sql, values, stringifyObjects, timeZone) {
if (values instanceof Array) {
//TODO we have to check if it is array like object.
// only array-link or array object will work.
return formatIndexArray.apply(this, arguments);
} else {
return formatNamedObject.apply(this, arguments);
}
};
|
Add API for derivative, vector root
|
var eng = require('./node/engine');
var index = module.exports = {
localMinimize: function(func, options, callback) {
eng.runPython('local', func, options, callback);
},
globalMinimize: function(func, options, callback) {
eng.runPython('global', func, options, callback);
},
minimizeEuclideanNorm: function(A, b, callback) {
eng.runPython('nnls', A, b, callback);
},
fitCurve: function(func, xData, yData, options, callback) {
eng.runPython('fit', func, options, callback, xData, yData);
},
findRoot: function(func, lower, upper, options, callback) {
eng.runPython('root', func, options, callback, lower, upper);
},
findVectorRoot: function(func, guess, options, callback) {
eng.runPython('vectorRoot', func, options, callback, guess);
},
calcDerivatives: function(func, point, options, callback) {
eng.runPython('derivative', func, options, callback, point);
}
};
index.fitCurve.linear = function(xData, yData, callback) {
eng.runPython('fit', 'a * x + b', { variables: ['x', 'a', 'b'] }, callback, xData, yData);
};
index.fitCurve.quadratic = function(xData, yData, callback) {
eng.runPython('fit', 'a * (x**2) + b * x + c', { variables: ['x', 'a', 'b', 'c'] }, callback, xData, yData);
};
|
var eng = require('./node/engine');
var index = module.exports = {
localMinimize: function(func, options, callback) {
eng.runPython('local', func, options, callback);
},
globalMinimize: function(func, options, callback) {
eng.runPython('global', func, options, callback);
},
nonNegLeastSquares: function(A, b, callback) {
eng.runPython('nnls', A, b, callback);
},
fitCurve: function(func, xData, yData, options, callback) {
eng.runPython('fit', func, options, callback, xData, yData);
},
findRoot: function(func, lower, upper, options, callback) {
eng.runPython('root', func, options, callback, lower, upper);
}
};
index.fitCurve.linear = function(xData, yData, callback) {
eng.runPython('fit', 'a * x + b', { variables: ['x', 'a', 'b'] }, callback, xData, yData);
};
index.fitCurve.quadratic = function(xData, yData, callback) {
eng.runPython('fit', 'a * (x**2) + b * x + c', { variables: ['x', 'a', 'b', 'c'] }, callback, xData, yData);
};
|
Fix proxy variable that was not adjusted
|
package info.u_team.u_team_core;
import org.apache.logging.log4j.*;
import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@Mod(UCoreMain.MODID)
public class UCoreMain {
public static final String MODID = "uteamcore";
public static final Logger LOGGER = LogManager.getLogger("UTeamCore");
private static final IModProxy PROXY = DistExecutor.runForDist(() -> ClientProxy::new, () -> CommonProxy::new);
public UCoreMain() {
FMLJavaModLoadingContext.get().getModEventBus().register(this);
PROXY.construct();
}
@SubscribeEvent
public void setup(FMLCommonSetupEvent event) {
PROXY.setup();
}
@SubscribeEvent
public void ready(FMLLoadCompleteEvent event) {
PROXY.complete();
}
}
|
package info.u_team.u_team_core;
import org.apache.logging.log4j.*;
import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@Mod(UCoreMain.MODID)
public class UCoreMain {
public static final String MODID = "uteamcore";
public static final Logger LOGGER = LogManager.getLogger("UTeamCore");
private static final IModProxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> CommonProxy::new);
public UCoreMain() {
FMLJavaModLoadingContext.get().getModEventBus().register(this);
proxy.construct();
}
@SubscribeEvent
public void setup(FMLCommonSetupEvent event) {
proxy.setup();
}
@SubscribeEvent
public void ready(FMLLoadCompleteEvent event) {
proxy.complete();
}
}
|
Change assertEquals to assertEqual due to deprecation warnings
|
import flask_testing
import logging
import unittest
import urllib
import server
logging.disable(logging.CRITICAL)
class TestIndex(unittest.TestCase):
def test_index_returns_greeting(self):
self.assertEqual(server.index(), 'Hello World')
class TestLiveIndex(flask_testing.LiveServerTestCase):
def create_app(self):
app = server.Flask(server.__name__)
app = server.app
app.config['TESTING'] = True
app.config['LIVE_SERVERPORT'] = 0
return app
def test_server_awake(self):
res = urllib.request.urlopen(self.get_server_url())
self.assertEqual(res.code, 200)
if __name__ == '__main__':
unittest.main()
|
import flask_testing
import logging
import unittest
import urllib
import server
logging.disable(logging.CRITICAL)
class TestIndex(unittest.TestCase):
def test_index_returns_greeting(self):
self.assertEquals(server.index(), 'Hello World')
class TestLiveIndex(flask_testing.LiveServerTestCase):
def create_app(self):
app = server.Flask(server.__name__)
app = server.app
app.config['TESTING'] = True
app.config['LIVE_SERVERPORT'] = 0
return app
def test_server_awake(self):
res = urllib.request.urlopen(self.get_server_url())
self.assertEquals(res.code, 200)
if __name__ == '__main__':
unittest.main()
|
Add end for api output
|
<?php
use Pagon\Route\Rest;
use Pagon\Url;
use Pagon\View;
class Api extends Rest
{
protected $data = array();
/**
* Show error error message
*
* @param $message
*/
protected function error($message)
{
$this->output->status(400);
$this->output->json(array('message' => $message, 'status' => 'ERROR'))->end();
}
/**
* Show ok message
*/
protected function ok()
{
$this->output->status(200);
$this->output->json(array('status' => 'OK'))->end();
}
/**
* Before
*/
protected function before()
{
$this->loadOrm();
}
/**
* After
*/
protected function after()
{
if (!$this->app->output->body) {
$this->output->json($this->data);
}
}
/**
* Load ORM and database
*/
protected function loadOrm()
{
$this->app->loadOrm();
}
}
|
<?php
use Pagon\Route\Rest;
use Pagon\Url;
use Pagon\View;
class Api extends Rest
{
protected $data = array();
/**
* Show error error message
*
* @param $message
*/
protected function error($message)
{
$this->output->status(400);
$this->output->json(array('message' => $message, 'status' => 'ERROR'));
}
/**
* Show ok message
*/
protected function ok()
{
$this->output->status(200);
$this->output->json(array('status' => 'OK'));
}
/**
* Before
*/
protected function before()
{
$this->loadOrm();
}
/**
* After
*/
protected function after()
{
if (!$this->app->output->body) {
$this->output->json($this->data);
}
}
/**
* Load ORM and database
*/
protected function loadOrm()
{
$this->app->loadOrm();
}
}
|
Convert Transform to ES class.
|
import { toArray, Class } from './lib/objects';
import { uuid } from './lib/uuid';
/**
Transforms represent a set of operations that are applied against a
source. After a transform has been applied, it should be assigned the
`result`, a `TransformResult` that represents the result of the transform.
Transforms are automatically assigned a UUID `id`.
@class Transform
@namespace Orbit
@param {Array} [operations] Operations to apply
@param {Object} [options]
@param {String} [options.id] Unique id for this transform (will be assigned a uuid by default)
@constructor
*/
export default class Transform {
constructor(ops, _options) {
this.operations = toArray(ops);
let options = _options || {};
this.id = options.id || uuid();
}
isEmpty() {
return this.operations.length === 0;
}
}
Transform.from = function(transformOrOperations) {
if (transformOrOperations instanceof Transform) { return transformOrOperations; }
return new Transform(transformOrOperations);
};
|
import { toArray, Class } from './lib/objects';
import { uuid } from './lib/uuid';
/**
Transforms represent a set of operations that are applied against a
source. After a transform has been applied, it should be assigned the
`result`, a `TransformResult` that represents the result of the transform.
Transforms are automatically assigned a UUID `id`.
@class Transform
@namespace Orbit
@param {Array} [operations] Operations to apply
@param {Object} [options]
@param {String} [options.id] Unique id for this transform (will be assigned a uuid by default)
@constructor
*/
var Transform = Class.extend({
operations: null,
init: function(ops, options) {
this.operations = toArray(ops);
options = options || {};
this.id = options.id || uuid();
},
isEmpty: function() {
return this.operations.length === 0;
}
});
Transform.from = function(transformOrOperations) {
if (transformOrOperations instanceof Transform) { return transformOrOperations; }
return new Transform(transformOrOperations);
};
export default Transform;
|
Rename variable, prefix private function
|
"""
byceps.blueprints.ticketing.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import abort, g
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
current_user = _get_current_user_or_403()
tickets = ticket_service.find_tickets_related_to_user_for_party(
current_user.id, g.party.id)
current_user_uses_any_ticket = find(
lambda t: t.used_by_id == current_user.id, tickets)
return {
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def _get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user
|
"""
byceps.blueprints.ticketing.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from flask import abort, g
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
me = get_current_user_or_403()
tickets = ticket_service.find_tickets_related_to_user_for_party(
me.id, g.party.id)
current_user_uses_any_ticket = find(lambda t: t.used_by_id == me.id, tickets)
return {
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user
|
Fix admin/model where bad config item was added on install
|
<?php
class ModelPaymentOmiseOffsite extends Model {
private $_group = 'omise_offsite';
/**
* Install a table that need to use in Omise Payment Gateway module
* @return boolean
*/
public function install()
{
$this->load->model('setting/setting');
$this->model_setting_setting->editSetting($this->_group, array(
'omise_offsite_status' => 0,
'omise_offsite_payment_title' => 'Internet Banking (Powered by Omise)'
));
return true;
}
/**
* Drop table when uninstall Omise Payment Gateway module
* @return boolean
*/
public function uninstall()
{
// ...
}
/**
* Get config from table
* @return array|boolean
*/
public function getConfig()
{
try {
$this->load->model('setting/setting');
$this->model_setting_setting->getSetting($this->_group);
} catch (Exception $e) {
return false;
}
}
}
|
<?php
class ModelPaymentOmiseOffsite extends Model
{
/**
* Install a table that need to use in Omise Payment Gateway module
* @return boolean
*/
public function install()
{
$this->load->model('setting/setting');
$this->model_setting_setting->editSetting($this->_group, array(
'omise_offsite_status' => 0,
'omise_offsite_payment_title' => 'Internet Banking (Powered by Omise)'
));
return true;
}
/**
* Drop table when uninstall Omise Payment Gateway module
* @return boolean
*/
public function uninstall()
{
// ...
}
/**
* Get config from table
* @return array|boolean
*/
public function getConfig()
{
try {
$this->load->model('setting/setting');
$this->model_setting_setting->getSetting($this->_group);
} catch (Exception $e) {
return false;
}
}
}
|
Add command-line option for program version.
|
from __future__ import print_function
import argparse
import shcol
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
parser.add_argument('items', nargs='+', help='an item to columnize')
parser.add_argument(
'-s', '--spacing', metavar='N', type=int, default=2,
help='number of blank characters between two columns'
)
parser.add_argument(
'-w', '--width', metavar='N', type=int, default=80,
help='maximal amount of characters per line'
)
args = parser.parse_args(cmd_args[1:])
print(shcol.columnize(args.items, args.spacing, args.width))
|
from __future__ import print_function
import argparse
import shcol
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.'
)
parser.add_argument('items', nargs='+', help='an item to columnize')
parser.add_argument(
'-s', '--spacing', metavar='N', type=int, default=2,
help='number of blank characters between two columns'
)
parser.add_argument(
'-w', '--width', metavar='N', type=int, default=80,
help='maximal amount of characters per line'
)
args = parser.parse_args(cmd_args[1:])
print(shcol.columnize(args.items, args.spacing, args.width))
|
Add .git to git url
|
Package.describe({
git: 'https://github.com/zimme/meteor-collection-softremovable.git',
name: 'zimme:collection-softremovable',
summary: 'Add soft remove to collections',
version: '1.0.3-rc.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'coffeescript',
'underscore'
]);
api.use([
'matb33:collection-hooks@0.7.6',
'zimme:collection-behaviours@1.0.2'
]);
api.use([
'aldeed:autoform@4.0.0',
'aldeed:collection2@2.0.0',
'aldeed:simple-schema@1.0.3'
], ['client', 'server'], {weak: true});
api.imply('zimme:collection-behaviours');
api.addFiles('softremovable.coffee');
});
|
Package.describe({
git: 'https://github.com/zimme/meteor-collection-softremovable',
name: 'zimme:collection-softremovable',
summary: 'Add soft remove to collections',
version: '1.0.3-rc.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'coffeescript',
'underscore'
]);
api.use([
'matb33:collection-hooks@0.7.6',
'zimme:collection-behaviours@1.0.2'
]);
api.use([
'aldeed:autoform@4.0.0',
'aldeed:collection2@2.0.0',
'aldeed:simple-schema@1.0.3'
], ['client', 'server'], {weak: true});
api.imply('zimme:collection-behaviours');
api.addFiles('softremovable.coffee');
});
|
Change signature so sources can be treated as configurable items
|
/******************************************************************
* File: MapSource.java
* Created by: Dave Reynolds
* Created on: 13 Dec 2013
*
* (c) Copyright 2013, Epimorphics Limited
*
*****************************************************************/
package com.epimorphics.dclib.framework;
import org.apache.jena.riot.system.StreamRDF;
import com.epimorphics.appbase.monitor.ConfigInstance;
import com.hp.hpl.jena.graph.Node;
/**
* Signature for utilities the support mapping of input values
* to normalized RDF values (normally URIs).
*
* @author <a href="mailto:dave@epimorphics.com">Dave Reynolds</a>
*/
public interface MapSource extends ConfigInstance {
/**
* Return the matching normalized RDF value or none if there no
* match (or no unambiguous match)
*/
public Node lookup(String key);
/**
* Return the name of this suorce, may be null
*/
public String getName();
/**
* Enrich the RDF outstream from other properties of a matched node
*/
public void enrich(StreamRDF stream, Node match);
}
|
/******************************************************************
* File: MapSource.java
* Created by: Dave Reynolds
* Created on: 13 Dec 2013
*
* (c) Copyright 2013, Epimorphics Limited
*
*****************************************************************/
package com.epimorphics.dclib.framework;
import org.apache.jena.riot.system.StreamRDF;
import com.hp.hpl.jena.graph.Node;
/**
* Signature for utilities the support mapping of input values
* to normalized RDF values (normally URIs).
*
* @author <a href="mailto:dave@epimorphics.com">Dave Reynolds</a>
*/
public interface MapSource {
/**
* Return the matching normalized RDF value or none if there no
* match (or no unambiguous match)
*/
public Node lookup(String key);
/**
* Return the name of this suorce, may be null
*/
public String getName();
/**
* Enrich the RDF outstream from other properties of a matched node
*/
public void enrich(StreamRDF stream, Node match);
}
|
Add missing dependency to clowder_test
|
"""
Setup file for clowder test runner
"""
from setuptools import setup
# Written according to the docs at
# https://packaging.python.org/en/latest/distributing.html
setup(
name='clowder-test',
description='Test runner for clowder command',
version='0.1.0',
url='http://clowder.cat',
author='Joe DeCapo',
author_email='joe@polka.cat',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6'
],
packages=['clowder_test',
'clowder_test.cli'],
entry_points={
'console_scripts': [
'clowder-test=clowder_test.clowder_test_app:main',
]
},
install_requires=['argcomplete', 'cement', 'colorama', 'cprint', 'psutil', 'termcolor']
)
|
"""
Setup file for clowder test runner
"""
from setuptools import setup
# Written according to the docs at
# https://packaging.python.org/en/latest/distributing.html
setup(
name='clowder-test',
description='Test runner for clowder command',
version='0.1.0',
url='http://clowder.cat',
author='Joe DeCapo',
author_email='joe@polka.cat',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6'
],
packages=['clowder_test',
'clowder_test.cli'],
entry_points={
'console_scripts': [
'clowder-test=clowder_test.clowder_test_app:main',
]
},
install_requires=['argcomplete', 'cement', 'cprint', 'psutil', 'termcolor']
)
|
Rename an argument to be more precisely represent the use purpose
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
def __null_line_strip(line):
return line
def __line_strip(line):
return line.strip()
def split_line_list(
line_list, re_block_separator=re.compile("^$"),
is_include_match_line=False, is_strip=True):
block_list = []
block = []
strip_func = __line_strip if is_strip else __null_line_strip
for line in line_list:
line = strip_func(line)
if re_block_separator.search(line):
if block:
block_list.append(block)
block = []
if is_include_match_line:
block.append(line)
continue
block.append(line)
if block:
block_list.append(block)
return block_list
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import re
def __null_line_strip(line):
return line
def __line_strip(line):
return line.strip()
def split_line_list(
line_list, re_line_separator=re.compile("^$"),
is_include_match_line=False, is_strip=True):
block_list = []
block = []
strip_func = __line_strip if is_strip else __null_line_strip
for line in line_list:
line = strip_func(line)
if re_line_separator.search(line):
if block:
block_list.append(block)
block = []
if is_include_match_line:
block.append(line)
continue
block.append(line)
if block:
block_list.append(block)
return block_list
|
Update order of patient attributes in model.
|
from app import db
class User(db.Model):
__tablename__ = 'users'
username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True)
password = db.Column(db.String(192), nullable=False)
def __init__(self, username, password):
self.username = username
self.password = password
def __repr__(self):
return 'The users name is: %r' % self.username
class Patient(db.Model):
__tablename__ = 'patients'
forename = db.Column(db.String(64), nullable=False)
surname = db.Column(db.String(64), nullable=False)
dob = db.Column(db.Date)
mobile = db.Column(db.String(30), nullable=False, unique=True, primary_key=True)
def __init__(self, forename, surname, dob, mobile):
self.forename = forename
self.surname = surname
self.dob = dob
self.mobile = mobile
def __repr__(self):
return 'The patients name & mobile number are: %r %r, %r' % (self.forename, self.surname, self.mobile)
|
from app import db
class User(db.Model):
__tablename__ = 'users'
username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True)
password = db.Column(db.String(192), nullable=False)
def __init__(self, username, password):
self.username = username
self.password = password
def __repr__(self):
return 'The users name is: %r' % self.username
class Patient(db.Model):
__tablename__ = 'patients'
# Used to determine which nurse triaged a patient.
# clientname = db.Column(db.String(64), db.ForeignKey('users.username'))
mobile = db.Column(db.Integer, unique=True, primary_key=True)
forename = db.Column(db.String(64), nullable=False)
surname = db.Column(db.String(64), nullable=False)
dob = db.Column(db.Date)
def __init__(self, mobile, forename, surname, dob):
self.mobile = mobile
self.forename = forename
self.surname = surname
self.dob = dob
def __repr__(self):
return 'The mobile number and name are: %r, %r %r' % (self.mobile, self.forename, self.surname)
|
Fix modifiers for ebook format
|
var svgToImg = require('./svgToImg');
var svgToPng = require('./svgToPng');
var resolveImages = require('./resolveImages');
var fetchRemoteImages = require('./fetchRemoteImages');
var Promise = require('../../utils/promise');
/**
Inline all assets in a page
@param {String} rootFolder
*/
function inlineAssets(rootFolder, currentFile) {
return function($) {
return Promise()
// Resolving images and fetching external images should be
// done before svg conversion
.then(resolveImages.bind(null, currentFile, $))
.then(fetchRemoteImages.bind(null, rootFolder, currentFile, $))
.then(svgToImg.bind(null, rootFolder, currentFile, $))
.then(svgToPng.bind(null, rootFolder, currentFile, $));
};
}
module.exports = inlineAssets;
|
var svgToImg = require('./svgToImg');
var svgToPng = require('./svgToPng');
var resolveImages = require('./resolveImages');
var fetchRemoteImages = require('./fetchRemoteImages');
var Promise = require('../../utils/promise');
/**
Inline all assets in a page
@param {String} rootFolder
*/
function inlineAssets(rootFolder, currentFile) {
return function($) {
return Promise()
// Resolving images and fetching external images should be
// done before svg conversion
.then(resolveImages.bind(null, currentFile))
.then(fetchRemoteImages.bind(null, rootFolder, currentFile))
.then(svgToImg.bind(null, rootFolder, currentFile))
.then(svgToPng.bind(null, rootFolder, currentFile));
};
}
module.exports = inlineAssets;
|
Return the output rather than print
|
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
class Command(BaseCommand):
help = 'Generate redux boilerplate'
def add_arguments(self, parser):
parser.add_argument('action_name', type=str)
parser.add_argument('--thunk',
action='store_true',
dest='thunk',
default=False,
help='Generate a redux thunk')
def handle(self, *args, **options):
if options['thunk']:
template_name = 'django_redux_generator/thunk_fetch.js'
else:
template_name = 'django_redux_generator/action_creator.js'
return render_to_string(template_name, {
'action_name': options['action_name'],
})
|
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
class Command(BaseCommand):
help = 'Generate redux boilerplate'
def add_arguments(self, parser):
parser.add_argument('action_name', type=str)
parser.add_argument('--thunk',
action='store_true',
dest='thunk',
default=False,
help='Generate a redux thunk')
def handle(self, *args, **options):
if options['thunk']:
template_name = 'django_redux_generator/thunk_fetch.js'
else:
template_name = 'django_redux_generator/action_creator.js'
print(render_to_string(template_name, {
'action_name': options['action_name'],
}))
|
test: Fix deprecation warning with mongoose `open()` method
|
/* @flow */
/* eslint-disable no-param-reassign, no-console */
import mongoose, { Schema } from 'mongoose';
import MongodbMemoryServer from 'mongodb-memory-server';
mongoose.Promise = Promise;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
const originalConnect = mongoose.connect;
mongoose.connect = async () => {
const mongoServer = new MongodbMemoryServer();
const mongoUri = await mongoServer.getConnectionString();
originalConnect.bind(mongoose)(mongoUri, { useMongoClient: true });
mongoose.connection.on('error', e => {
if (e.message.code === 'ETIMEDOUT') {
console.error(e);
} else {
throw e;
}
});
mongoose.connection.once('open', () => {
// console.log(`MongoDB successfully connected to ${mongoUri}`);
});
mongoose.connection.once('disconnected', () => {
// console.log('MongoDB disconnected!');
mongoServer.stop();
});
};
export { mongoose, Schema };
|
/* @flow */
/* eslint-disable no-param-reassign, no-console */
import mongoose, { Schema } from 'mongoose';
import MongodbMemoryServer from 'mongodb-memory-server';
mongoose.Promise = Promise;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
const originalConnect = mongoose.connect;
mongoose.connect = async () => {
const mongoServer = new MongodbMemoryServer();
const mongoUri = await mongoServer.getConnectionString();
originalConnect.bind(mongoose)(mongoUri);
mongoose.connection.on('error', e => {
if (e.message.code === 'ETIMEDOUT') {
console.error(e);
} else {
throw e;
}
});
mongoose.connection.once('open', () => {
// console.log(`MongoDB successfully connected to ${mongoUri}`);
});
mongoose.connection.once('disconnected', () => {
// console.log('MongoDB disconnected!');
mongoServer.stop();
});
};
export { mongoose, Schema };
|
Fix import for Kotti > 0.8x.
|
from __future__ import absolute_import
from fanstatic import Library
from fanstatic import Resource
from kotti.resources import Image
from kotti.fanstatic import view_css
from kotti.fanstatic import view_needed
lib_kotti_site_gallery = Library('kotti_site_gallery', 'static')
ksg_view_css = Resource(lib_kotti_site_gallery,
"kotti_site_gallery.css",
minified="kotti_site_gallery.min.css",
depends=[view_css])
def kotti_configure(settings):
settings['kotti.available_types'] += ' kotti_site_gallery.resources.Site'
settings['kotti.available_types'] += ' kotti_site_gallery.resources.SiteGallery'
settings['pyramid.includes'] += ' kotti_site_gallery.includeme'
settings['pyramid.includes'] += ' kotti_site_gallery.views.includeme'
Image.type_info.addable_to.append(u'Site')
def includeme(config):
view_needed.add(ksg_view_css)
|
from fanstatic import Library
from fanstatic import Resource
from kotti.resources import Image
import kotti.static as ks
lib_kotti_site_gallery = Library('kotti_site_gallery', 'static')
view_css = Resource(lib_kotti_site_gallery,
"kotti_site_gallery.css",
minified="kotti_site_gallery.min.css",
depends=[ks.view_css])
def kotti_configure(settings):
settings['kotti.available_types'] += ' kotti_site_gallery.resources.Site'
settings['kotti.available_types'] += ' kotti_site_gallery.resources.SiteGallery'
settings['pyramid.includes'] += ' kotti_site_gallery.includeme'
settings['pyramid.includes'] += ' kotti_site_gallery.views.includeme'
Image.type_info.addable_to.append(u'Site')
def includeme(config):
ks.view_needed.add(view_css)
|
Monitor body for changes to catch modal edit box
|
// ==UserScript==
// @name JIRA Enhancements for CSC
// @namespace http://csc.com/
// @version 0.2
// @description Adds a description template to new JIRA tasks.
// @homepageURL https://github.com/scytalezero/JIRA-CSC-Utils
// @updateURL https://github.com/scytalezero/JIRA-CSC-Utils/raw/master/JIRA-CSC-Utils.user.js
// @downloadURL https://github.com/scytalezero/JIRA-CSC-Utils/raw/master/JIRA-CSC-Utils.user.js
// @author bcreel2@csc.com
// @match https://cscjranor004.csc-fsg.com/browse/*
// @grant none
// ==/UserScript==
//Observe changes to the description section
Out("Adding description watcher");
jQuery("body").on('DOMSubtreeModified',function() {
if ( (jQuery("#description").length > 0) && (jQuery("#description").text().length === 0) ) {
Out("Adding description template");
jQuery("#description").text("*Business impact:*\n\n*Description:*\n\n*Steps to recreate:*\n# \n\n*Resolution Description:*\n* \n");
}
})
function Out(buffer) {
console.log("[JIRA CSC] " + buffer);
}
|
// ==UserScript==
// @name JIRA Enhancements for CSC
// @namespace http://csc.com/
// @version 0.1
// @description Adds a description template to new JIRA tasks.
// @homepageURL https://github.com/scytalezero/JIRA-CSC-Utils
// @updateURL https://github.com/scytalezero/JIRA-CSC-Utils/raw/master/JIRA-CSC-Utils.user.js
// @downloadURL https://github.com/scytalezero/JIRA-CSC-Utils/raw/master/JIRA-CSC-Utils.user.js
// @author bcreel2@csc.com
// @match https://cscjranor004.csc-fsg.com/browse/*
// @grant none
// ==/UserScript==
//Observe changes to the description section
Out("Adding description watcher");
jQuery("#descriptionmodule").on('DOMSubtreeModified',function() {
if ( (jQuery("#description").length > 0) && (jQuery("#description").text().length === 0) ) {
Out("Adding description template");
jQuery("#description").text("*Business impact:*\n\n*Description:*\n\n*Steps to recreate:*\n# \n\n*Resolution Description:*\n* \n");
}
})
function Out(buffer) {
console.log("[JIRA CSC] " + buffer);
}
|
[infra] Add required service account permission to docs
Change-Id: If0f6782d35bb50bafa55d0279e8506e0e06ab63f
Reviewed-on: https://skia-review.googlesource.com/c/buildbot/+/480214
Auto-Submit: Kevin Lubick <7cdab2cfab351f23814786ba39716e90eed69047@google.com>
Reviewed-by: Joe Gregorio <b9cf2471ff6d33504cafe8e6f356b732b2cadced@google.com>
|
// Package tracing consolidates the setup logic for using opencensus tracing and exporting the
// metrics to https://cloud.google.com/trace. In order to authenticate to the correct API, any
// service account that uses this package must have the Cloud Trace Agent Role in gcp.
package tracing
import (
"time"
"contrib.go.opencensus.io/exporter/stackdriver"
"go.opencensus.io/trace"
"go.skia.org/infra/go/skerr"
)
// Initialize sets up trace options and exporting for this application. It will sample the given
// proportion of traces. All traces will have the given key-value pairs attached.
func Initialize(traceSampleProportion float64, projectID string, defaultAttrs map[string]interface{}) error {
exporter, err := stackdriver.NewExporter(stackdriver.Options{
ProjectID: projectID,
// Use 10 times the default
TraceSpansBufferMaxBytes: 80_000_000,
// It is not clear what the default interval is. One minute seems to be a good value since
// that is the same as our Prometheus metrics are reported.
ReportingInterval: time.Minute,
DefaultTraceAttributes: defaultAttrs,
})
if err != nil {
return skerr.Wrap(err)
}
trace.RegisterExporter(exporter)
sampler := trace.ProbabilitySampler(traceSampleProportion)
trace.ApplyConfig(trace.Config{DefaultSampler: sampler})
return nil
}
|
// Package tracing consolidates the setup logic for using opencensus tracing and exporting the
// metrics.
package tracing
import (
"time"
"contrib.go.opencensus.io/exporter/stackdriver"
"go.opencensus.io/trace"
"go.skia.org/infra/go/skerr"
)
// Initialize sets up trace options and exporting for this application. It will sample the given
// proportion of traces. All traces will have the given key-value pairs attached.
func Initialize(traceSampleProportion float64, projectID string, defaultAttrs map[string]interface{}) error {
exporter, err := stackdriver.NewExporter(stackdriver.Options{
ProjectID: projectID,
// Use 10 times the default
TraceSpansBufferMaxBytes: 80_000_000,
// It is not clear what the default interval is. One minute seems to be a good value since
// that is the same as our Prometheus metrics are reported.
ReportingInterval: time.Minute,
DefaultTraceAttributes: defaultAttrs,
})
if err != nil {
return skerr.Wrap(err)
}
trace.RegisterExporter(exporter)
sampler := trace.ProbabilitySampler(traceSampleProportion)
trace.ApplyConfig(trace.Config{DefaultSampler: sampler})
return nil
}
|
Fix logging for testing environment
|
from .base_settings import *
import os
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
SECRET_KEY = '$1B&VUf$OdUEfMJXd40qdakA36@%2NE_41Dz9tFs6l=z4v_3P-'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'puzzlehunt_db',
'HOST': '127.0.0.1',
'USER': 'root',
'PASSWORD': '',
'OPTIONS': {'charset': 'utf8mb4'},
}
}
INTERNAL_IPS = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
ALLOWED_HOSTS = ['*']
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
},
}
|
from .base_settings import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
SECRET_KEY = '$1B&VUf$OdUEfMJXd40qdakA36@%2NE_41Dz9tFs6l=z4v_3P-'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'puzzlehunt_db',
'HOST': '127.0.0.1',
'USER': 'root',
'PASSWORD': '',
'OPTIONS': {'charset': 'utf8mb4'},
}
}
INTERNAL_IPS = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
ALLOWED_HOSTS = ['*']
|
Add waiting for new data to parse
|
from time import sleep
from tsparser import config
from tsparser.parser import BaseParser, ParseException
from tsparser.parser.gps import GPSParser
from tsparser.parser.imu import IMUParser
from tsparser.sender import Sender
def parse(input_file=None):
"""
Parse the file specified as input.
:param input_file: file to read input from. If None, then pipe specified
in config is used
:type input_file: file
"""
Sender(daemon=True).start()
if input_file is None:
input_file = open(config.PIPE_NAME, 'r')
parsers = _get_parsers()
while True:
line = input_file.readline()
if not line:
sleep(0.01)
continue
_parse_line(parsers, line)
def _get_parsers():
return [
IMUParser(),
GPSParser()
]
def _parse_line(parsers, line):
values = line.split(',')
BaseParser.timestamp = values.pop().strip()
for parser in parsers:
if parser.parse(line, *values):
break
else:
raise ParseException('Output line was not parsed by any parser: {}'
.format(line))
|
from tsparser import config
from tsparser.parser import BaseParser, ParseException
from tsparser.parser.gps import GPSParser
from tsparser.parser.imu import IMUParser
from tsparser.sender import Sender
def parse(input_file=None):
"""
Parse the file specified as input.
:param input_file: file to read input from. If None, then pipe specified
in config is used
:type input_file: file
"""
Sender(daemon=True).start()
if input_file is None:
input_file = open(config.PIPE_NAME, 'r')
parsers = _get_parsers()
while True:
line = input_file.readline()
if not line:
continue
_parse_line(parsers, line)
def _get_parsers():
return [
IMUParser(),
GPSParser()
]
def _parse_line(parsers, line):
values = line.split(',')
BaseParser.timestamp = values.pop().strip()
for parser in parsers:
if parser.parse(line, *values):
break
else:
raise ParseException('Output line was not parsed by any parser: {}'
.format(line))
|
Change build script to node
|
var builder = require('./lib/nebula-builder');
var baseConfig = require('./lib/base-config');
var configBuilder = require('./lib/config-builder');
var fs = require('fs');
module.exports = function(grunt) {
grunt.initConfig({
watch: {
styles: {
files: ['scss/**/*.scss'], // which files to watch
tasks: ['sass'],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['sass', 'watch']);
grunt.registerTask('buildVanilla' , function() {
var modules = ['banner', 'config', 'mixins', 'reset', 'helpers', 'base'];
var done = this.async();
builder(modules, './nebula.css', null, done);
});
grunt.registerTask('sass' , function() {
var done = this.async();
builder(null, './css/styles.css', null, done);
});
grunt.registerTask('buildConfig' , function() {
fs.writeFileSync('./scss/nebula/_config.scss', configBuilder(baseConfig));
});
};
|
var builder = require('./lib/nebula-builder');
var baseConfig = require('./lib/base-config');
var configBuilder = require('./lib/config-builder');
var fs = require('fs');
module.exports = function(grunt) {
grunt.initConfig({
watch: {
styles: {
files: ['scss/**/*.scss'], // which files to watch
tasks: ['sass'],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['sass', 'watch']);
grunt.registerTask('buildVanilla' , function() {
var modules = ['banner', 'config', 'mixins', 'reset', 'helpers', 'base'];
var done = this.async();
builder(modules, './nebula.css', null, done);
});
grunt.registerTask('buildConfig' , function() {
fs.writeFileSync('./scss/nebula/_config.scss', configBuilder(baseConfig));
});
};
|
Change migration to add currency and issuer
|
'use strict';
exports.up = function(knex, Promise) {
return knex.schema.createTable('Transactions', function (table) {
table.increments("id").primary();
table.string("address", 128);
table.integer("amount");
table.string("currency", 3);
table.string("issuer", 128);
table.string("memo", 512);
table.text("txblob");
table.string("txhash", 128);
table.integer("sequence");
table.text("error");
table.timestamp("signedAt").nullable();
table.timestamp("submittedAt").nullable();
table.timestamp("confirmedAt").nullable();
table.timestamp("abortedAt").nullable();
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable("Transactions");
};
|
'use strict';
exports.up = function(knex, Promise) {
return knex.schema.createTable('Transactions', function (table) {
table.increments("id").primary();
table.string("address", 128);
table.integer("amount");
table.string("memo", 512);
table.text("txblob");
table.string("txhash", 128);
table.integer("sequence");
table.text("error");
table.timestamp("signedAt").nullable();
table.timestamp("submittedAt").nullable();
table.timestamp("confirmedAt").nullable();
table.timestamp("abortedAt").nullable();
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable("Transactions");
};
|
Include includeSubData parameter true, so we show the loading indicator if petriNetData or agreementData is loading as well
|
/**
* Created by quasarchimaere on 21.01.2019.
*/
import { get } from "../utils.js";
import {
isProcessingInitialLoad,
isProcessingLogin,
isProcessingLogout,
isProcessingPublish,
isProcessingAcceptTermsOfService,
isProcessingVerifyEmailAddress,
isProcessingResendVerificationEmail,
isProcessingSendAnonymousLinkEmail,
isAnyNeedLoading,
isAnyConnectionLoading,
isAnyMessageLoading,
} from "../process-utils.js";
/**
* Check if anything in the state sub-map of process is currently marked as loading
* @param state (full redux-state)
* @returns true if anything is currently loading
*/
export function isLoading(state) {
const process = get(state, "process");
return (
isProcessingInitialLoad(process) ||
isProcessingLogin(process) ||
isProcessingLogout(process) ||
isProcessingPublish(process) ||
isProcessingAcceptTermsOfService(process) ||
isProcessingVerifyEmailAddress(process) ||
isProcessingResendVerificationEmail(process) ||
isProcessingSendAnonymousLinkEmail(process) ||
isAnyNeedLoading(process) ||
isAnyConnectionLoading(process, true) ||
isAnyMessageLoading(process)
);
}
|
/**
* Created by quasarchimaere on 21.01.2019.
*/
import { get } from "../utils.js";
import {
isProcessingInitialLoad,
isProcessingLogin,
isProcessingLogout,
isProcessingPublish,
isProcessingAcceptTermsOfService,
isProcessingVerifyEmailAddress,
isProcessingResendVerificationEmail,
isProcessingSendAnonymousLinkEmail,
isAnyNeedLoading,
isAnyConnectionLoading,
isAnyMessageLoading,
} from "../process-utils.js";
/**
* Check if anything in the state sub-map of process is currently marked as loading
* @param state (full redux-state)
* @returns true if anything is currently loading
*/
export function isLoading(state) {
const process = get(state, "process");
return (
isProcessingInitialLoad(process) ||
isProcessingLogin(process) ||
isProcessingLogout(process) ||
isProcessingPublish(process) ||
isProcessingAcceptTermsOfService(process) ||
isProcessingVerifyEmailAddress(process) ||
isProcessingResendVerificationEmail(process) ||
isProcessingSendAnonymousLinkEmail(process) ||
isAnyNeedLoading(process) ||
isAnyConnectionLoading(process) ||
isAnyMessageLoading(process)
);
}
|
Set sass base as root of project
|
const browser = require('browser-sync');
const config = require('../../config');
const gulp = require('gulp');
const handleError = require('../../utilities/handleError');
const importer = require('sass-module-importer');
const path = require('path');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
/**
* HyperBolts ϟ (https://hyperbolts.io)
*
* Copyright © 2015-present Pace IT Systems Ltd.
* All rights reserved.
*
* @author Pace IT Systems Ltd
* @license MIT
*/
module.exports = paths => () => gulp.src(paths.src)
// Compile
.pipe(sourcemaps.init())
.pipe(sass({
importer: importer({
basedir: process.cwd()
})
}))
.on('error', handleError)
.pipe(sourcemaps.write())
// Output
.pipe(gulp.dest(
path.resolve(config.base, paths.dest)
))
// Reload browser
.pipe(browser.reload({
stream: true
}));
|
const browser = require('browser-sync');
const config = require('../../config');
const gulp = require('gulp');
const handleError = require('../../utilities/handleError');
const importer = require('sass-module-importer');
const path = require('path');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
/**
* HyperBolts ϟ (https://hyperbolts.io)
*
* Copyright © 2015-present Pace IT Systems Ltd.
* All rights reserved.
*
* @author Pace IT Systems Ltd
* @license MIT
*/
module.exports = paths => () => gulp.src(paths.src)
// Compile
.pipe(sourcemaps.init())
.pipe(sass({
importer: importer({
basedir: path.join(process.cwd(), 'node_modules')
})
}))
.on('error', handleError)
.pipe(sourcemaps.write())
// Output
.pipe(gulp.dest(
path.resolve(config.base, paths.dest)
))
// Reload browser
.pipe(browser.reload({
stream: true
}));
|
Use absolute filepath instead of relative
|
import os
import unittest
from ooni.utils import pushFilenameStack
basefilename = os.path.abspath('dummyfile')
class TestUtils(unittest.TestCase):
def test_pushFilenameStack(self):
f = open(basefilename, "w+")
f.write("0\n")
f.close()
for i in xrange(1, 5):
f = open(basefilename+".%s" % i, "w+")
f.write("%s\n" % i)
f.close()
pushFilenameStack(basefilename)
for i in xrange(1, 5):
f = open(basefilename+".%s" % i)
c = f.readlines()[0].strip()
self.assertEqual(str(i-1), str(c))
f.close()
|
import unittest
from ooni.utils import pushFilenameStack
class TestUtils(unittest.TestCase):
def test_pushFilenameStack(self):
f = open("dummyfile", "w+")
f.write("0\n")
f.close()
for i in xrange(1, 5):
f = open("dummyfile.%s" % i, "w+")
f.write("%s\n" % i)
f.close()
pushFilenameStack("dummyfile")
for i in xrange(1, 5):
f = open("dummyfile.%s" % i)
c = f.readlines()[0].strip()
self.assertEqual(str(i-1), str(c))
f.close()
|
Move development status from Alpha to Beta
|
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
import kitchen.release
setup(name='kitchen',
version=str(kitchen.release.__version__),
description=kitchen.release.DESCRIPTION,
author=kitchen.release.AUTHOR,
author_email=kitchen.release.EMAIL,
license=kitchen.release.LICENSE,
url=kitchen.release.URL,
download_url=kitchen.release.DOWNLOAD_URL,
keywords='Useful Small Code Snippets',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: General',
],
packages=find_packages(),
data_files = [],
)
|
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
import kitchen.release
setup(name='kitchen',
version=str(kitchen.release.__version__),
description=kitchen.release.DESCRIPTION,
author=kitchen.release.AUTHOR,
author_email=kitchen.release.EMAIL,
license=kitchen.release.LICENSE,
url=kitchen.release.URL,
download_url=kitchen.release.DOWNLOAD_URL,
keywords='Useful Small Code Snippets',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.3',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: General',
],
packages=find_packages(),
data_files = [],
)
|
Add cors header to example
|
const http = require("http")
const url = require("url")
const namor = require("namor")
const server = http.createServer((req, res) => {
const { query } = url.parse(req.url, true)
const payload = JSON.stringify(
{
generated_name: namor.generate({
words: query.words,
saltLength: query.saltLength,
saltType: query.saltType,
separator: query.separator,
subset: query.subset,
}),
},
null,
2,
)
res.setHeader("Content-Type", "application/json")
res.setHeader("Content-Length", Buffer.byteLength(payload))
res.setHeader("Access-Control-Allow-Origin", "*")
res.end(payload)
})
const port = process.env.PORT || 5000
const host = process.env.HOST || "0.0.0.0"
server.listen(port, host, () => {
console.log(`=> running at http://${host}:${port}`)
})
|
const http = require("http")
const url = require("url")
const namor = require("namor")
const server = http.createServer((req, res) => {
const { query } = url.parse(req.url, true)
const payload = JSON.stringify(
{
generated_name: namor.generate({
words: query.words,
saltLength: query.saltLength,
saltType: query.saltType,
separator: query.separator,
subset: query.subset,
}),
},
null,
2,
)
res.setHeader("Content-Type", "application/json")
res.setHeader("Content-Length", Buffer.byteLength(payload))
res.setHeader("Access-Control-Allow-Headers", "*")
res.end(payload)
})
const port = process.env.PORT || 5000
const host = process.env.HOST || "0.0.0.0"
server.listen(port, host, () => {
console.log(`=> running at http://${host}:${port}`)
})
|
[tests] Clean up the SWIG test. Add comments. NFC
|
# RUN: python %s | display-check -
import uwhd
def main():
version = 1
black_score = 3
white_score = 5
time = 42
# Build a GameModelManager with a known state:
mgr = uwhd.GameModelManager()
mgr.setGameStateFirstHalf()
mgr.setBlackScore(black_score)
mgr.setWhiteScore(white_score)
mgr.setGameClock(time)
# Render that state to a canvas:
canvas = uwhd.UWHDCanvas.create(32 * 3, 32)
uwhd.renderGameDisplay(version, mgr.getModel(), canvas)
# Print out the expected and actual display state
# for display-check to verify:
print('# SET-VERSION: %d' % (version,))
print('# SET-STATE: FirstHalf')
print('# SET-BLACK: %d' % (black_score,))
print('# SET-WHITE: %d' % (white_score,))
print('# SET-TIME: %d' % (time,))
print(uwhd.asPPMString(canvas))
if __name__ == '__main__':
main()
|
# RUN: python %s | display-check -
import uwhd
def main():
version = 1
black_score = 3
white_score = 5
time = 42
mgr = uwhd.GameModelManager()
print('# SET-VERSION: %d' % (version,))
print('# SET-STATE: FirstHalf')
print('# SET-BLACK: %d' % (black_score,))
print('# SET-WHITE: %d' % (white_score,))
print('# SET-TIME: %d' % (time,))
mgr.setGameStateFirstHalf()
mgr.setBlackScore(black_score)
mgr.setWhiteScore(white_score)
mgr.setGameClock(time)
canvas = uwhd.UWHDCanvas.create(32 * 3, 32)
uwhd.renderGameDisplay(1, mgr.getModel(), canvas)
ppmstr = uwhd.asPPMString(canvas)
print(ppmstr)
if __name__ == '__main__':
main()
|
Add comments: explain why we do not use path.relative
|
var path = require('path');
var flat = require('./util/flat');
var Set = require('./util/set');
function getOutput(pkg, www) {
return flat(pkg.commands.map(function (command) {
return command.output;
})).filter(function (file) {
return file.substr(-3) === '.js' || file.substr(-4) === '.css';
}).map(function (file) {
// NOTE: here we do NOT use `path.relative`, cause all output MUST stay in the www directory.
if (file.substr(0, www.length) !== www) {
throw new Error('Output [' + file + '] out of www [' + www + ']!');
}
return file.substr(www.length);
});
}
module.exports = function (report, www) {
var linked = Object.create(null);
function fr(fn) {
for (var pkgName in report) {
fn(report[pkgName], pkgName);
}
}
// Ensure `www.substr(-1) === '/'` is constant.
www = path.resolve(www) + (www.substr(-1) === '/' ? '/' : '');
fr(function (pkg) {
pkg.output = getOutput(pkg, www);
});
fr(function (pkg, pkgName) {
var output = new Set();
output.addBatch(pkg.output);
pkg.dependencies.forEach(function (name) {
output.addBatch(report[name].output);
});
linked[pkgName] = output.array;
});
return linked;
};
|
var path = require('path');
var flat = require('./util/flat');
var Set = require('./util/set');
function getOutput(pkg, www) {
return flat(pkg.commands.map(function (command) {
return command.output;
})).filter(function (file) {
return file.substr(-3) === '.js' || file.substr(-4) === '.css';
}).map(function (file) {
if (file.substr(0, www.length) !== www) {
throw new Error('Output [' + file + '] out of www [' + www + ']!');
}
return file.substr(www.length);
});
}
module.exports = function (report, www) {
var linked = Object.create(null);
function fr(fn) {
for (var pkgName in report) {
fn(report[pkgName], pkgName);
}
}
// Ensure `www.substr(-1) === '/'` is constant.
www = path.resolve(www) + (www.substr(-1) === '/' ? '/' : '');
fr(function (pkg) {
pkg.output = getOutput(pkg, www);
});
fr(function (pkg, pkgName) {
var output = new Set();
output.addBatch(pkg.output);
pkg.dependencies.forEach(function (name) {
output.addBatch(report[name].output);
});
linked[pkgName] = output.array;
});
return linked;
};
|
Fix the "Get Started" button link
|
@extends('layouts.app')
@section('page-type')home @stop
@section('content')
<div class="jumbotron jumbotron-home">
<h1 class="impact-text">Pack right for every trip.</h1>
<h3 class="subtitle">Put your packing list online and never pack too much or too little.</h3>
</div>
<div class="shortblurb">
<h3>What does it do?</h3>
<p>Most people pack way too much when they travel, forget to bring
essential things, or both. FillMySuitcase helps you pack
everything you need, but nothing you don't. It's an online packing
list that you use every time you travel.
</div>
<div class="container-fluid">
<div class="row">
<div class="col-xs-2 col-sm-4"></div>
<div class="col-xs-8 col-sm-4">
<a class="btn btn-primary btn-lg btn-block" href="/login">Get started</a>
</div>
<div class="col-xs-2 col-sm-4"></div>
</div>
</div>
@stop
|
@extends('layouts.app')
@section('page-type')home @stop
@section('content')
<div class="jumbotron jumbotron-home">
<h1 class="impact-text">Pack right for every trip.</h1>
<h3 class="subtitle">Put your packing list online and never pack too much or too little.</h3>
</div>
<div class="shortblurb">
<h3>What does it do?</h3>
<p>Most people pack way too much when they travel, forget to bring
essential things, or both. FillMySuitcase helps you pack
everything you need, but nothing you don't. It's an online packing
list that you use every time you travel.
</div>
<div class="container-fluid">
<div class="row">
<div class="col-xs-2 col-sm-4"></div>
<div class="col-xs-8 col-sm-4">
<a class="btn btn-primary btn-lg btn-block" href="/auth/login">Get started</a>
</div>
<div class="col-xs-2 col-sm-4"></div>
</div>
</div>
@stop
|
Use PHP $_REQUEST variable to also allow POST-ing.
|
<?php
$date =& $_REQUEST["date"];
$user =& $_REQUEST["user"];
$priority =& $_REQUEST["priority"];
$text =& $_REQUEST["text"];
require_once 'icat.php';
$db = init_db();
$_SESSION['entry_username'] = $user;
$result = mysqli_query($db,
"insert into entries (contest_time, user, priority, text) values " .
sprintf("((SELECT MAX(contest_time) AS last_submission FROM submissions), '%s', %d, '%s')",
mysqli_escape_string($db, $user), $priority, mysqli_escape_string($db, $text))
);
if ($result) {
print("okay");
} else {
print("error: " . mysqli_error($db));
}
?>
|
<?php
$date =& $_GET["date"];
$user =& $_GET["user"];
$priority =& $_GET["priority"];
$text =& $_GET["text"];
require_once 'icat.php';
$db = init_db();
$_SESSION['entry_username'] = $user;
$result = mysqli_query($db,
"insert into entries (contest_time, user, priority, text) values " .
sprintf("((SELECT MAX(contest_time) AS last_submission FROM submissions), '%s', %d, '%s')",
mysqli_escape_string($db, $user), $priority, mysqli_escape_string($db, $text))
);
if ($result) {
print("okay");
} else {
print("error: " . mysqli_error($db));
}
?>
|
Fix build breaking checkstyle issue
|
package pl.tomaszdziurko.jvm_bloggers.mailing;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPost;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPostRepository;
import pl.tomaszdziurko.jvm_bloggers.utils.NowProvider;
import java.time.LocalDateTime;
import java.util.List;
@Component
@Slf4j
public class BlogSummaryMailSender {
private BlogPostRepository blogPostRepository;
private BlogSummaryMailGenerator mailGenerator;
private NowProvider nowProvider;
@Autowired
public BlogSummaryMailSender(BlogPostRepository blogPostRepository, BlogSummaryMailGenerator blogSummaryMailGenerator, NowProvider nowProvider) {
this.blogPostRepository = blogPostRepository;
this.mailGenerator = blogSummaryMailGenerator;
this.nowProvider = nowProvider;
}
public void sendSummary(int numberOfDaysBackInThePast) {
LocalDateTime publishedDate = nowProvider.now().minusDays(numberOfDaysBackInThePast).withHour(0).withMinute(0).withSecond(0).withNano(0);
List<BlogPost> newBlogPosts = blogPostRepository.findByPublishedDateAfterOrderByPublishedDateAsc(publishedDate);
String mailTemplate = mailGenerator.generateSummaryMail(newBlogPosts, numberOfDaysBackInThePast);
log.info("Mail content = \n" + mailTemplate);
}
}
|
package pl.tomaszdziurko.jvm_bloggers.mailing;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPost;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPostRepository;
import pl.tomaszdziurko.jvm_bloggers.utils.NowProvider;
import java.time.LocalDateTime;
import java.util.List;
@Component
@Slf4j
public class BlogSummaryMailSender {
private BlogPostRepository blogPostRepository;
private BlogSummaryMailGenerator mailGenerator;
private NowProvider nowProvider;
@Autowired
public BlogSummaryMailSender(BlogPostRepository blogPostRepository, BlogSummaryMailGenerator blogSummaryMailGenerator, NowProvider nowProvider) {
this.blogPostRepository = blogPostRepository;
this.mailGenerator = blogSummaryMailGenerator;
this.nowProvider = nowProvider;
}
public void sendSummary(int numberOfDaysBackInThePast) {
LocalDateTime publishedDate = nowProvider.now().minusDays(numberOfDaysBackInThePast).withHour(0).withMinute(0).withSecond(0).withNano(0);
List<BlogPost> newBlogPosts = blogPostRepository.findByPublishedDateAfterOrderByPublishedDateAsc(publishedDate);
String mailTemplate = mailGenerator.generateSummaryMail(newBlogPosts, numberOfDaysBackInThePast);
log.info("Mail content = \n" + mailTemplate );
}
}
|
Use Tested for UDP connection tests
|
package net.kencochrane.raven.connection;
import mockit.Injectable;
import mockit.Tested;
import mockit.Verifications;
import net.kencochrane.raven.event.Event;
import net.kencochrane.raven.marshaller.Marshaller;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.OutputStream;
import java.net.InetAddress;
public class UdpConnectionTest {
@Injectable
private final String hostname = "127.0.0.1";
@Injectable
private final int port = 1234;
@Injectable
private final String publicKey = "44850120-9d2a-451b-8e00-998bddaa2800";
@Injectable
private final String secretKey = "1de38091-6e8c-42df-8298-cf7f8098617a";
@Tested
private UdpConnection udpConnection;
@Injectable
private Marshaller mockMarshaller;
@BeforeMethod
public void setUp() throws Exception {
udpConnection = null;
}
@Test
public void testContentMarshalled(@Injectable final Event event) throws Exception {
udpConnection.send(event);
new Verifications() {{
mockMarshaller.marshall(event, (OutputStream) any);
}};
}
}
|
package net.kencochrane.raven.connection;
import mockit.Injectable;
import mockit.Verifications;
import net.kencochrane.raven.event.Event;
import net.kencochrane.raven.marshaller.Marshaller;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.OutputStream;
public class UdpConnectionTest {
private UdpConnection udpConnection;
@Injectable
private Marshaller mockMarshaller;
@BeforeMethod
public void setUp() throws Exception {
udpConnection = new UdpConnection("", "", "");
udpConnection.setMarshaller(mockMarshaller);
}
@Test
public void testContentMarshalled(@Injectable final Event event) throws Exception {
udpConnection.send(event);
new Verifications() {{
mockMarshaller.marshall(event, (OutputStream) any);
}};
}
}
|
Update command category from Storage to Networking
|
// Copyright 2017-2020 The Usacloud 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 bridge
import (
"reflect"
"github.com/sacloud/libsacloud/v2/helper/service/bridge"
"github.com/sacloud/usacloud/pkg/cmd/core"
)
var Resource = &core.Resource{
Name: "bridge",
ServiceType: reflect.TypeOf(&bridge.Service{}),
Category: core.ResourceCategoryNetworking,
CommandCategories: []core.Category{
{
Key: "basic",
DisplayName: "Basic Commands",
Order: 10,
},
{
Key: "operation",
DisplayName: "Operation Commands",
Order: 20,
},
{
Key: "other",
DisplayName: "Other Commands",
Order: 1000,
},
},
}
|
// Copyright 2017-2020 The Usacloud 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 bridge
import (
"reflect"
"github.com/sacloud/libsacloud/v2/helper/service/bridge"
"github.com/sacloud/usacloud/pkg/cmd/core"
)
var Resource = &core.Resource{
Name: "bridge",
ServiceType: reflect.TypeOf(&bridge.Service{}),
Category: core.ResourceCategoryStorage,
CommandCategories: []core.Category{
{
Key: "basic",
DisplayName: "Basic Commands",
Order: 10,
},
{
Key: "operation",
DisplayName: "Operation Commands",
Order: 20,
},
{
Key: "other",
DisplayName: "Other Commands",
Order: 1000,
},
},
}
|
Fix crash on no options
|
'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
if (!opts) opts = {};
function minifier(req, res, next) {
if (opts.override !== true) {
res.renderMin = function (view, renderOpts) {
this.render(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
}
} else {
res.oldRender = res.render;
res.render = function (view, renderOpts) {
this.oldRender(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
};
}
return next();
}
return (minifier);
}
module.exports = minifyHTML;
|
'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
function minifier(req, res, next) {
if (opts.override !== true) {
res.renderMin = function (view, renderOpts) {
this.render(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
}
} else {
res.oldRender = res.render;
res.render = function (view, renderOpts) {
this.oldRender(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
};
}
return next();
}
return (minifier);
}
module.exports = minifyHTML;
|
Fix typo: avaiableLanguages -> availableLanguages
|
#!/usr/bin/env node
var cli = require('cli'),
hljs = require('highlight.js'),
availableLanguages = hljs.listLanguages(),
cheerio = require('cheerio'),
Entities = require('html-entities').AllHtmlEntities,
entities = new Entities(),
fs = require('fs'),
opts = cli.parse({
selector: [
's',
'jQuery style selector which specifies on which elements highlighting is applied',
'string',
'pre code'
],
output: [
'o',
'Output file path',
'file',
false
]
});
cli.withStdin(function(input) {
var $ = cheerio.load(input);
$(opts.selector).each(function(_, elem) {
var lang = $(elem).attr('class');
var highlighted;
if (lang && availableLanguages.indexOf(lang.toLower) != -1) {
highlighted = hljs.highlight(lang, $(elem).text()).value;
} else {
highlighted = hljs.highlightAuto($(elem).text()).value;
}
$(elem).text(highlighted).addClass('hljs');
});
var out = entities.decode($.html());
if (opts.output) {
fs.writeFileSync(opts.output, out);
} else {
this.output(out);
}
});
|
#!/usr/bin/env node
var cli = require('cli'),
hljs = require('highlight.js'),
avaiableLanguages = hljs.listLanguages(),
cheerio = require('cheerio'),
Entities = require('html-entities').AllHtmlEntities,
entities = new Entities(),
fs = require('fs'),
opts = cli.parse({
selector: [
's',
'jQuery style selector which specifies on which elements highlighting is applied',
'string',
'pre code'
],
output: [
'o',
'Output file path',
'file',
false
]
});
cli.withStdin(function(input) {
var $ = cheerio.load(input);
$(opts.selector).each(function(_, elem) {
var lang = $(elem).attr('class');
var highlighted;
if (lang && avaiableLanguages.indexOf(lang.toLower) != -1) {
highlighted = hljs.highlight(lang, $(elem).text()).value;
} else {
highlighted = hljs.highlightAuto($(elem).text()).value;
}
$(elem).text(highlighted).addClass('hljs');
});
var out = entities.decode($.html());
if (opts.output) {
fs.writeFileSync(opts.output, out);
} else {
this.output(out);
}
});
|
Fix TLS support in socket test
|
import logging
import kaa
from kaa.net.tls import TLSSocket
log = logging.getLogger('tls').ensureRootHandler()
@kaa.coroutine()
def new_client(client):
ip, port = client.peer[:2]
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = TLSSocket()
yield remote.connect('www.google.com:443')
yield remote.starttls_client()
yield remote.write('GET / HTTP/1.0\n\n')
while remote.readable:
data = yield remote.read()
yield client.write(data)
client.write('\n\nBye!\n')
client.close()
server = kaa.Socket()
server.signals['new-client'].connect(new_client)
server.listen(8080)
print "Connect to localhost:8080"
kaa.main.run()
|
import kaa
@kaa.coroutine()
def new_client(client):
ip, port = client.address
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = tls.TLSSocket()
#remote = kaa.Socket()
yield remote.connect('www.freevo.org:80')
#yield remote.connect('urandom.ca:443')
#try:
# yield remote.starttls_client()
#except:
# print "TLS ERROR"
# return
remote.write('GET / HTTP/1.0\n\n')
while remote.connected:
data = yield remote.read()
yield client.write(data)
client.write('\n\nBye!\n')
client.close()
from kaa.net import tls
#server = tls.TLSSocket()
server = kaa.Socket()
server.signals['new-client'].connect(new_client)
server.listen(8080)
print "Connect to localhost:8080"
kaa.main.run()
|
Test upload with a small file
|
import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')
qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY
QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)
def test_put_file():
ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
print "Test text: %s" % text
token = QINIU_PUT_POLICY.token()
ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
if err:
raise IOError(
"Error message: %s" % err)
|
import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.environ.get('QINIU_BUCKET_DOMAIN')
qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY
qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY
QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)
def test_put_file():
ASSET_FILE_NAME = 'bootstrap.min.css'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
print "Test text: %s" % text
token = QINIU_PUT_POLICY.token()
ret, err = qiniu.io.put(token, join(str(uuid.uuid4()), ASSET_FILE_NAME), text)
if err:
raise IOError(
"Error message: %s" % err)
|
Update benchmark for setting fields of this type.
git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@269 c7a0535c-eda6-11de-83d8-6d5adf01d787
|
/*
* Mutability Detector
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Further licensing information for this project can be found in
* license/LICENSE.txt
*/
package org.mutabilitydetector.benchmarks.settermethod;
@SuppressWarnings("unused")
public class ImmutableButSetsPrivateFieldOfInstanceOfSelf {
private int myField = 0;
private ImmutableButSetsPrivateFieldOfInstanceOfSelf fieldOfSelfType = null;
public ImmutableButSetsPrivateFieldOfInstanceOfSelf setPrivateFieldOnInstanceOfSelf() {
ImmutableButSetsPrivateFieldOfInstanceOfSelf i = new ImmutableButSetsPrivateFieldOfInstanceOfSelf();
this.hashCode();
i.myField = 10;
this.hashCode();
i.myField = 11;
return i;
}
}
class MutableBySettingFieldOnThisInstanceAndOtherInstance {
@SuppressWarnings("unused")
private int myField = 0;
public void setMyField(int newMyField, MutableBySettingFieldOnThisInstanceAndOtherInstance otherInstance) {
this.myField = newMyField;
otherInstance.myField = 42;
}
}
|
/*
* Mutability Detector
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Further licensing information for this project can be found in
* license/LICENSE.txt
*/
package org.mutabilitydetector.benchmarks.settermethod;
@SuppressWarnings("unused")
public class ImmutableButSetsPrivateFieldOfInstanceOfSelf {
private int myField = 0;
private ImmutableButSetsPrivateFieldOfInstanceOfSelf fieldOfSelfType = null;
public ImmutableButSetsPrivateFieldOfInstanceOfSelf setPrivateFieldOnInstanceOfSelf() {
ImmutableButSetsPrivateFieldOfInstanceOfSelf i = new ImmutableButSetsPrivateFieldOfInstanceOfSelf();
this.hashCode();
i.myField = 10;
this.hashCode();
i.myField = 11;
return i;
}
}
class MutableBySettingFieldOnThisInstance {
@SuppressWarnings("unused")
private int myField = 0;
public void setMyField(int newMyField) {
this.myField = newMyField;
}
}
|
Update changesNotifier to only call underlying Notifier if repos is non-empty
|
// Copyright 2015, David Howden
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"log"
"sort"
"time"
)
type Notifier interface {
Notify(map[string]time.Time) error
}
type logNotifier struct{}
func (logNotifier) Notify(repos map[string]time.Time) error {
keys := make([]string, 0, len(repos))
for k := range repos {
keys = append(keys, k)
}
sort.Sort(sort.StringSlice(keys))
for _, k := range keys {
log.Printf("%v\t: %v", k, repos[k])
}
return nil
}
type changesNotifier struct {
Notifier
last map[string]time.Time
}
func (d changesNotifier) Notify(repos map[string]time.Time) error {
changes := make(map[string]time.Time)
for k, v := range repos {
if d.last[k] != v {
changes[k] = v
d.last[k] = v
}
}
if len(changes) == 0 {
return nil
}
return d.Notifier.Notify(changes)
}
|
// Copyright 2015, David Howden
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"log"
"sort"
"time"
)
type Notifier interface {
Notify(map[string]time.Time) error
}
type logNotifier struct{}
func (logNotifier) Notify(repos map[string]time.Time) error {
keys := make([]string, 0, len(repos))
for k := range repos {
keys = append(keys, k)
}
sort.Sort(sort.StringSlice(keys))
for _, k := range keys {
log.Printf("%v\t: %v", k, repos[k])
}
return nil
}
type changesNotifier struct {
Notifier
last map[string]time.Time
}
func (d changesNotifier) Notify(repos map[string]time.Time) error {
changes := make(map[string]time.Time)
for k, v := range repos {
if d.last[k] != v {
changes[k] = v
d.last[k] = v
}
}
return d.Notifier.Notify(changes)
}
|
Support static files via new Pelican API
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Lex Toumbourou'
SITENAME = u'LexToumbourou.com'
SITEURL = 'http://lextoumbourou.com'
TIMEZONE = 'Australia/Melbourne'
DEFAULT_LANG = u'en'
ARTICLE_URL = 'blog/posts/{slug}/'
ARTICLE_SAVE_AS = 'blog/posts/{slug}/index.html'
# Feed generation is usually not desired when developing
FEED_DOMAIN = SITEURL
FEED_ATOM = 'atom.xml'
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = None
THEME = "themes/lextoumbourou-theme"
STATIC_PATHS = ['images', 'extra']
EXTRA_PATH_METADATA = {
'extra/robots.txt': {'path': 'robots.txt'},
'extra/favicon.ico': {'path': 'favicon.ico'},
}
DISQUS_SITENAME = 'lextoumbouroucom'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Lex Toumbourou'
SITENAME = u'LexToumbourou.com'
SITEURL = 'http://lextoumbourou.com'
TIMEZONE = 'Australia/Melbourne'
DEFAULT_LANG = u'en'
ARTICLE_URL = 'blog/posts/{slug}/'
ARTICLE_SAVE_AS = 'blog/posts/{slug}/index.html'
# Feed generation is usually not desired when developing
FEED_DOMAIN = SITEURL
FEED_ATOM = 'atom.xml'
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = None
THEME = "themes/lextoumbourou-theme"
STATIC_PATHS = ['images']
FILES_TO_COPY = (
('extra/robots.txt', 'robots.txt'),
('extra/favicon.ico', 'favicon.ico'),
)
DISQUS_SITENAME = 'lextoumbouroucom'
|
Refresh data on app going foreground
|
/* application entry point */
// require mithril globally for convenience
window.m = require('mithril');
// cordova plugins polyfills for browser
if (!window.cordova) require('./cordovaPolyfills.js');
var utils = require('./utils');
var session = require('./session');
var i18n = require('./i18n');
var home = require('./ui/home');
var login = require('./ui/login');
var play = require('./ui/play');
var seek = require('./ui/seek');
function onResume() {
session.refresh(true);
}
function main() {
m.route(document.body, '/', {
'/': home,
'/login': login,
'/seek/:id': seek,
'/play/:id': play
});
// refresh data once and on app resume
if (utils.hasNetwork()) session.refresh(true);
document.addEventListener('resume', onResume, false);
// iOs keyboard hack
// TODO we may want to remove this and call only on purpose
window.cordova.plugins.Keyboard.disableScroll(true);
if (window.gaId) window.analytics.startTrackerWithId(window.gaId);
setTimeout(function() {
window.navigator.splashscreen.hide();
}, 500);
}
document.addEventListener('deviceready',
// i18n must be loaded before any rendering happens
utils.ƒ(i18n.loadPreferredLanguage, main),
false
);
|
/* application entry point */
// require mithril globally for convenience
window.m = require('mithril');
// cordova plugins polyfills for browser
if (!window.cordova) require('./cordovaPolyfills.js');
var utils = require('./utils');
var session = require('./session');
var i18n = require('./i18n');
var home = require('./ui/home');
var login = require('./ui/login');
var play = require('./ui/play');
var seek = require('./ui/seek');
function main() {
m.route(document.body, '/', {
'/': home,
'/login': login,
'/seek/:id': seek,
'/play/:id': play
});
if (utils.hasNetwork()) session.refresh(true);
window.cordova.plugins.Keyboard.disableScroll(true);
if (window.gaId) window.analytics.startTrackerWithId(window.gaId);
setTimeout(function() {
window.navigator.splashscreen.hide();
}, 500);
}
document.addEventListener('deviceready',
// i18n must be loaded before any rendering happens
utils.ƒ(i18n.loadPreferredLanguage, main),
false
);
|
Move Alert into events package
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.alerts.api.model.data;
/**
* Severity set for a {@link org.hawkular.alerts.api.model.trigger.Trigger} and assigned to an
* {@link Alert} it generates.
*
* @author jay shaughnessy
* @author lucas ponce
*/
public enum AvailabilityType {
UP, DOWN, UNAVAILABLE
}
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.alerts.api.model.data;
/**
* Severity set for a {@link org.hawkular.alerts.api.model.trigger.Trigger} and assigned to an
* {@link Alert} it generates.
*
* @author jay shaughnessy
* @author lucas ponce
*/
public enum AvailabilityType {
UP, DOWN, UNAVAILABLE
}
|
Test for navigating to the Dependent Crates page
|
import { test } from 'qunit';
import moduleForAcceptance from 'cargo/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | crate page');
test('visiting a crate page from the front page', function(assert) {
visit('/');
click('#just-updated ul > li:first a');
andThen(function() {
assert.equal(currentURL(), '/crates/nanomsg');
assert.equal(document.title, 'nanomsg - Cargo: packages for Rust');
});
});
test('visiting a crate page directly', function(assert) {
visit('/crates/nanomsg');
andThen(function() {
assert.equal(currentURL(), '/crates/nanomsg');
assert.equal(document.title, 'nanomsg - Cargo: packages for Rust');
});
});
test('navigating to the all versions page', function(assert) {
visit('/crates/nanomsg');
click('#crate-versions span.small a');
andThen(function() {
matchesText(assert, '.info', /All 12 versions of nanomsg since December \d+, 2014/);
});
});
test('navigating to the reverse dependencies page', function(assert) {
visit('/crates/nanomsg');
click('a:contains("Dependent crates")');
andThen(function() {
assert.equal(currentURL(), '/crates/nanomsg/reverse_dependencies');
const $revDep = findWithAssert('#crate-all-reverse-dependencies a[href="/crates/unicorn-rpc"]:first');
hasText(assert, $revDep, 'unicorn-rpc');
});
});
|
import { test } from 'qunit';
import moduleForAcceptance from 'cargo/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | crate page');
test('visiting a crate page from the front page', function(assert) {
visit('/');
click('#just-updated ul > li:first a');
andThen(function() {
assert.equal(currentURL(), '/crates/nanomsg');
assert.equal(document.title, 'nanomsg - Cargo: packages for Rust');
});
});
test('visiting a crate page directly', function(assert) {
visit('/crates/nanomsg');
andThen(function() {
assert.equal(currentURL(), '/crates/nanomsg');
assert.equal(document.title, 'nanomsg - Cargo: packages for Rust');
});
});
test('navigating to the all versions page', function(assert) {
visit('/crates/nanomsg');
click('#crate-versions span.small a');
andThen(function() {
matchesText(assert, '.info', /All 12 versions of nanomsg since December \d+, 2014/);
});
});
|
Fix ordering issue in test
|
import pytest
import sys
def test_1(m):
m.touch("/somefile") # NB: is found with or without initial /
m.touch("afiles/and/anothers")
files = m.find("")
if "somefile" in files:
assert files == ["afiles/and/anothers", "somefile"]
else:
assert files == ["/somefile", "afiles/and/anothers"]
files = sorted(m.get_mapper(""))
if "somefile" in files:
assert files == ["afiles/and/anothers", "somefile"]
else:
assert files == ["/somefile", "afiles/and/anothers"]
@pytest.mark.xfail(
sys.version_info < (3, 6),
reason="py35 error, see https://github.com/intake/filesystem_spec/issues/148",
)
def test_ls(m):
m.touch("/dir/afile")
m.touch("/dir/dir1/bfile")
m.touch("/dir/dir1/cfile")
assert m.ls("/", False) == ["/dir/"]
assert m.ls("/dir", False) == ["/dir/afile", "/dir/dir1/"]
assert m.ls("/dir", True)[0]["type"] == "file"
assert m.ls("/dir", True)[1]["type"] == "directory"
assert len(m.ls("/dir/dir1")) == 2
|
import pytest
import sys
def test_1(m):
m.touch("/somefile") # NB: is found with or without initial /
m.touch("afiles/and/anothers")
files = m.find("")
if "somefile" in files:
assert files == ["afiles/and/anothers", "somefile"]
else:
assert files == ["/somefile", "afiles/and/anothers"]
files = list(m.get_mapper(""))
if "somefile" in files:
assert files == ["afiles/and/anothers", "somefile"]
else:
assert files == ["/somefile", "afiles/and/anothers"]
@pytest.mark.xfail(
sys.version_info < (3, 6),
reason="py35 error, see https://github.com/intake/filesystem_spec/issues/148",
)
def test_ls(m):
m.touch("/dir/afile")
m.touch("/dir/dir1/bfile")
m.touch("/dir/dir1/cfile")
assert m.ls("/", False) == ["/dir/"]
assert m.ls("/dir", False) == ["/dir/afile", "/dir/dir1/"]
assert m.ls("/dir", True)[0]["type"] == "file"
assert m.ls("/dir", True)[1]["type"] == "directory"
assert len(m.ls("/dir/dir1")) == 2
|
Fix wrong Zed in Yves usage.
|
<?php
/**
* This file is part of the Spryker Demoshop.
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Pyz\Yves\Category\ResourceCreator;
use Pyz\Yves\Collector\Creator\AbstractResourceCreator;
use Silex\Application;
use Spryker\Shared\Category\CategoryConfig;
use Spryker\Yves\Kernel\BundleControllerAction;
use Spryker\Yves\Kernel\Controller\BundleControllerActionRouteNameResolver;
class CategoryResourceCreator extends AbstractResourceCreator
{
/**
* @return string
*/
public function getType()
{
return CategoryConfig::RESOURCE_TYPE_CATEGORY_NODE;
}
/**
* @param \Silex\Application $application
* @param array $data
*
* @return array
*/
public function createResource(Application $application, array $data)
{
$bundleControllerAction = new BundleControllerAction('Catalog', 'Catalog', 'index');
$routeResolver = new BundleControllerActionRouteNameResolver($bundleControllerAction);
$service = $this->createServiceForController($application, $bundleControllerAction, $routeResolver);
return [
'_controller' => $service,
'_route' => $routeResolver->resolve(),
'categoryNode' => $data,
];
}
}
|
<?php
/**
* This file is part of the Spryker Demoshop.
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Pyz\Yves\Category\ResourceCreator;
use Pyz\Yves\Collector\Creator\AbstractResourceCreator;
use Silex\Application;
use Spryker\Yves\Kernel\BundleControllerAction;
use Spryker\Yves\Kernel\Controller\BundleControllerActionRouteNameResolver;
use Spryker\Zed\Category\CategoryConfig;
class CategoryResourceCreator extends AbstractResourceCreator
{
/**
* @return string
*/
public function getType()
{
return CategoryConfig::RESOURCE_TYPE_CATEGORY_NODE;
}
/**
* @param \Silex\Application $application
* @param array $data
*
* @return array
*/
public function createResource(Application $application, array $data)
{
$bundleControllerAction = new BundleControllerAction('Catalog', 'Catalog', 'index');
$routeResolver = new BundleControllerActionRouteNameResolver($bundleControllerAction);
$service = $this->createServiceForController($application, $bundleControllerAction, $routeResolver);
return [
'_controller' => $service,
'_route' => $routeResolver->resolve(),
'categoryNode' => $data,
];
}
}
|
Check for router platform in auto-deploy script.
|
from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = ('Deploy configurations each IX having a router and a configuration'
' template attached.')
logger = logging.getLogger('peering.manager.peering')
def handle(self, *args, **options):
self.logger.info('Deploying configurations...')
for ix in InternetExchange.objects.all():
# Only deploy config if there are at least a configuration
# template, a router and a platform for the router
if ix.configuration_template and ix.router and ix.router.platform:
self.logger.info(
'Deploying configuration on {}'.format(ix.name))
ix.router.set_napalm_configuration(ix.generate_configuration(),
commit=True)
else:
self.logger.info(
'No configuration to deploy on {}'.format(ix.name))
self.logger.info('Configurations deployed')
|
from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = ('Deploy configurations each IX having a router and a configuration'
' template attached.')
logger = logging.getLogger('peering.manager.peering')
def handle(self, *args, **options):
self.logger.info('Deploying configurations...')
for ix in InternetExchange.objects.all():
if ix.configuration_template and ix.router:
self.logger.info(
'Deploying configuration on {}'.format(ix.name))
ix.router.set_napalm_configuration(ix.generate_configuration(),
commit=True)
else:
self.logger.info(
'No configuration to deploy on {}'.format(ix.name))
self.logger.info('Configurations deployed')
|
INclude README as long description.
|
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='pandocfilters',
version='1.0',
description='Utilities for writing pandoc filters in python',
long_description=read('README.rst'),
author='John MacFarlane',
author_email='fiddlosopher@gmail.com',
url='http://github.com/jgm/pandocfilters',
py_modules=['pandocfilters'],
keywords=['pandoc'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Text Processing :: Filters'
],
)
|
from distutils.core import setup
setup(name='pandocfilters',
version='1.0',
description='Utilities for writing pandoc filters in python',
author='John MacFarlane',
author_email='fiddlosopher@gmail.com',
url='http://github.com/jgm/pandocfilters',
py_modules=['pandocfilters'],
keywords=['pandoc'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Text Processing :: Filters'
],
)
|
Remove HTTP as part of POST handler response
|
'use strict';
const BaseHandler = require('./BaseHandler');
const ERRORS = require('../constants').ERRORS;
const EVENT_ENDPOINT_CREATED = require('../constants').EVENT_ENDPOINT_CREATED;
class PostHandler extends BaseHandler {
/**
* Create a file in the DataStore.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(req, res) {
return this.store.create(req)
.then((File) => {
const url = `//${req.headers.host}${this.store.path}/${File.id}`;
this.emit(EVENT_ENDPOINT_CREATED, { url });
return super.send(res, 201, { Location: url });
})
.catch((error) => {
console.warn('[PostHandler]', error);
const status_code = error.status_code || ERRORS.UNKNOWN_ERROR.status_code;
const body = error.body || `${ERRORS.UNKNOWN_ERROR.body}${error.message || ''}\n`;
return super.send(res, status_code, {}, body);
});
}
}
module.exports = PostHandler;
|
'use strict';
const BaseHandler = require('./BaseHandler');
const ERRORS = require('../constants').ERRORS;
const EVENT_ENDPOINT_CREATED = require('../constants').EVENT_ENDPOINT_CREATED;
class PostHandler extends BaseHandler {
/**
* Create a file in the DataStore.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(req, res) {
return this.store.create(req)
.then((File) => {
const url = `http://${req.headers.host}${this.store.path}/${File.id}`;
this.emit(EVENT_ENDPOINT_CREATED, { url });
return super.send(res, 201, { Location: url });
})
.catch((error) => {
console.warn('[PostHandler]', error);
const status_code = error.status_code || ERRORS.UNKNOWN_ERROR.status_code;
const body = error.body || `${ERRORS.UNKNOWN_ERROR.body}${error.message || ''}\n`;
return super.send(res, status_code, {}, body);
});
}
}
module.exports = PostHandler;
|
[WIP] BB-3589: Create generator’s extension for root and namespace replaces
- cs fixes
|
<?php
namespace Oro\Component\Layout\Tests\Unit\Extension\Theme\Stubs;
use Oro\Component\Layout\LayoutItemInterface;
use Oro\Component\Layout\ImportsAwareLayoutUpdateInterface;
use Oro\Component\Layout\LayoutManipulatorInterface;
use Oro\Component\Layout\LayoutUpdateImportInterface;
use Oro\Component\Layout\LayoutUpdateInterface;
use Oro\Component\Layout\Model\LayoutUpdateImport;
class ImportedLayoutUpdateWithImports implements
LayoutUpdateInterface,
LayoutUpdateImportInterface,
ImportsAwareLayoutUpdateInterface
{
public function setImport(LayoutUpdateImport $import)
{
}
/**
* @return array
*/
public function getImports()
{
}
/**
* {@inheritDoc}
*/
public function updateLayout(LayoutManipulatorInterface $layoutManipulator, LayoutItemInterface $item)
{
}
}
|
<?php
namespace Oro\Component\Layout\Tests\Unit\Extension\Theme\Stubs;
use Oro\Component\Layout\LayoutItemInterface;
use Oro\Component\Layout\ImportsAwareLayoutUpdateInterface;
use Oro\Component\Layout\LayoutManipulatorInterface;
use Oro\Component\Layout\LayoutUpdateImportInterface;
use Oro\Component\Layout\LayoutUpdateInterface;
use Oro\Component\Layout\Model\LayoutUpdateImport;
class ImportedLayoutUpdateWithImports implements LayoutUpdateInterface, LayoutUpdateImportInterface, ImportsAwareLayoutUpdateInterface
{
public function setImport(LayoutUpdateImport $import)
{
}
/**
* @return array
*/
public function getImports()
{
}
/**
* {@inheritDoc}
*/
public function updateLayout(LayoutManipulatorInterface $layoutManipulator, LayoutItemInterface $item)
{
}
}
|
Add useCache option to loadModels
|
import { STATUS } from './cache';
export const loadModels = async (models = [], { api, cache, useCache = true }) => {
const result = await Promise.all(
models.map((model) => {
// Special case to not re-fetch the model if it exists. This can happen for
// the user model which is set at login.
if (useCache && cache.has(model.key)) {
return cache.get(model.key).value;
}
return model.get(api);
})
);
models.forEach((model, i) => {
cache.set(model.key, {
value: result[i],
status: STATUS.RESOLVED
});
});
return result;
};
|
import { STATUS } from './cache';
/**
* Given a list of models, preload them and set them in the cache.
* TODO: Add support for dependencies. E.g. to know if we can fetch
* subscription model or organization model, we have fetch the user model first.
* @param {Array} models
* @param {Function} api
* @param {Map} cache
* @return {Promise<Array>}
*/
export const loadModels = async (models = [], { api, cache }) => {
const result = await Promise.all(
models.map((model) => {
// Special case to not re-fetch the model if it exists. This can happen for
// the user model which is set at login.
if (cache.has(model.key)) {
return cache.get(model.key).value;
}
return model.get(api);
})
);
models.forEach((model, i) => {
cache.set(model.key, {
value: result[i],
status: STATUS.RESOLVED
});
});
return result;
};
|
Exit with return code from called script
|
import click
import lib
@click.group()
def cli():
"""
Install From Source
When the version in the package manager has gone stale, get a fresh,
production-ready version from a source tarball or precompiled archive.
Send issues or improvements to https://github.com/cbednarski/ifs
"""
pass
@cli.command()
def ls():
for app in lib.list_apps():
click.echo(app)
@cli.command()
@click.argument('term')
def search(term):
for app in lib.list_apps():
if term in app:
click.echo(app)
@cli.command()
@click.argument('application')
def install(application):
cmd = lib.install(application)
click.echo(cmd.output)
exit(cmd.returncode)
@cli.command()
@click.argument('application')
def info(application):
"""
Show information about an application from ifs ls
"""
info = lib.app_info(application)
for k, v in info.iteritems():
if type(v) is list:
v = ' '.join(v)
click.echo('%s: %s' % (k, v))
if __name__ == '__main__':
cli()
|
import click
import lib
@click.group()
def cli():
"""
Install From Source
When the version in the package manager has gone stale, get a fresh,
production-ready version from a source tarball or precompiled archive.
Send issues or improvements to https://github.com/cbednarski/ifs
"""
pass
@cli.command()
def ls():
for app in lib.list_apps():
click.echo(app)
@cli.command()
@click.argument('term')
def search(term):
for app in lib.list_apps():
if term in app:
click.echo(app)
@cli.command()
@click.argument('application')
def install(application):
click.echo(lib.install(application))
@cli.command()
@click.argument('application')
def info(application):
"""
Show information about an application from ifs ls
"""
info = lib.app_info(application)
for k, v in info.iteritems():
if type(v) is list:
v = ' '.join(v)
click.echo('%s: %s' % (k, v))
if __name__ == '__main__':
cli()
|
Fix local time test case for logged-out viewers using global settings
Summary:
In D16936, I changed logged-out viewers so they use global settings.
This can lead to a `SELECT` from an isolated unit test. Instead, give the test fixtures and use standard `generateNewUser()` stuff.
Test Plan: Ran `arc unit --everything`.
Reviewers: chad
Reviewed By: chad
Differential Revision: https://secure.phabricator.com/D16952
|
<?php
final class PhabricatorLocalTimeTestCase extends PhabricatorTestCase {
protected function getPhabricatorTestCaseConfiguration() {
return array(
self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
);
}
public function testLocalTimeFormatting() {
$user = $this->generateNewTestUser();
$user->overrideTimezoneIdentifier('America/Los_Angeles');
$utc = $this->generateNewTestUser();
$utc->overrideTimezoneIdentifier('UTC');
$this->assertEqual(
'Jan 1 2000, 12:00 AM',
phabricator_datetime(946684800, $utc),
pht('Datetime formatting'));
$this->assertEqual(
'Jan 1 2000',
phabricator_date(946684800, $utc),
pht('Date formatting'));
$this->assertEqual(
'12:00 AM',
phabricator_time(946684800, $utc),
pht('Time formatting'));
$this->assertEqual(
'Dec 31 1999, 4:00 PM',
phabricator_datetime(946684800, $user),
pht('Localization'));
$this->assertEqual(
'',
phabricator_datetime(0, $user),
pht('Missing epoch should fail gracefully'));
}
}
|
<?php
final class PhabricatorLocalTimeTestCase extends PhabricatorTestCase {
public function testLocalTimeFormatting() {
$user = new PhabricatorUser();
$user->overrideTimezoneIdentifier('America/Los_Angeles');
$utc = new PhabricatorUser();
$utc->overrideTimezoneIdentifier('UTC');
$this->assertEqual(
'Jan 1 2000, 12:00 AM',
phabricator_datetime(946684800, $utc),
pht('Datetime formatting'));
$this->assertEqual(
'Jan 1 2000',
phabricator_date(946684800, $utc),
pht('Date formatting'));
$this->assertEqual(
'12:00 AM',
phabricator_time(946684800, $utc),
pht('Time formatting'));
$this->assertEqual(
'Dec 31 1999, 4:00 PM',
phabricator_datetime(946684800, $user),
pht('Localization'));
$this->assertEqual(
'',
phabricator_datetime(0, $user),
pht('Missing epoch should fail gracefully'));
}
}
|
Rename the 'Avatar' class to 'ProjectAvatar'
|
from panoptes_client.panoptes import (
Panoptes,
PanoptesObject,
LinkResolver,
)
from panoptes_client.project import Project
class ProjectAvatar(PanoptesObject):
_api_slug = 'avatar'
_link_slug = 'avatars'
_edit_attributes = ()
@classmethod
def http_get(cls, path, params={}, headers={}):
project = params.pop('project')
# print()
# print(Project.url(project.id))
# print()
avatar_response = Panoptes.client().get(
Project.url(project.id) + cls.url(path),
params,
headers,
)
print(avatar_response.raw)
return avatar_response
LinkResolver.register(Avatar)
LinkResolver.register(Avatar, 'avatar')
|
from panoptes_client.panoptes import (
Panoptes,
PanoptesObject,
LinkResolver,
)
from panoptes_client.project import Project
class Avatar(PanoptesObject):
_api_slug = 'avatar'
_link_slug = 'avatars'
_edit_attributes = ()
@classmethod
def http_get(cls, path, params={}, headers={}):
project = params.pop('project')
# print()
# print(Project.url(project.id))
# print()
avatar_response = Panoptes.client().get(
Project.url(project.id) + cls.url(path),
params,
headers,
)
print(avatar_response.raw)
return avatar_response
LinkResolver.register(Avatar)
LinkResolver.register(Avatar, 'avatar')
|
Add a doc for the PanicLogger
|
package handler
import (
"fmt"
"net/http"
"runtime/debug"
"time"
)
var PanicDateFormat = "Jan 2, 2006 at 3:04pm (MST)"
// PanicLogger is used to print out detailed messages when a panic occurs.
type PanicLogger interface {
Print(v ...interface{})
}
// Panic returns a handler that invokes the passed handler h, catching any
// panics. If one occurs, an HTTP 500 response is produced. If the logger l is
// not nil, it will be used to print out a detailed message, including the
// timestamp and stack trace. If showStack is true, the detailed message is
// also written to the ResponseWriter.
func Panic(l PanicLogger, showStack bool, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
stack := debug.Stack()
timestamp := time.Now().Format(PanicDateFormat)
message := fmt.Sprintf("%s - %s\n%s\n", timestamp, rec, stack)
if l != nil {
l.Print(message)
}
w.WriteHeader(http.StatusInternalServerError)
if !showStack {
message = "Internal Server Error"
}
w.Write([]byte(message))
}
}()
h.ServeHTTP(w, r)
})
}
|
package handler
import (
"fmt"
"net/http"
"runtime/debug"
"time"
)
var PanicDateFormat = "Jan 2, 2006 at 3:04pm (MST)"
type PanicLogger interface {
Print(v ...interface{})
}
// Panic returns a handler that invokes the passed handler h, catching any
// panics. If one occurs, an HTTP 500 response is produced. If the logger l is
// not nil, it will be used to print out a detailed message, including the
// timestamp and stack trace. If showStack is true, the detailed message is
// also written to the ResponseWriter.
func Panic(l PanicLogger, showStack bool, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
stack := debug.Stack()
timestamp := time.Now().Format(PanicDateFormat)
message := fmt.Sprintf("%s - %s\n%s\n", timestamp, rec, stack)
if l != nil {
l.Print(message)
}
w.WriteHeader(http.StatusInternalServerError)
if !showStack {
message = "Internal Server Error"
}
w.Write([]byte(message))
}
}()
h.ServeHTTP(w, r)
})
}
|
Fix wrong function call for XML batches
|
var utils = require('./test-utils');
var assert = require('chai').assert;
var fs = require('fs');
var path = require('path');
var xml = require('../lib/batch/xml');
var fixtures = path.join(__dirname, 'fixture/companies');
function readJSONBatch(filePath) {
var jsonBatch = fs.readFileSync(filePath, 'UTF-8');
jsonBatch = JSON.parse(jsonBatch);
return sortBatches(jsonBatch);
}
function readXMLBatch(filePath) {
var xmlBatch = fs.readFileSync(filePath, 'UTF-8');
xmlBatch = xml.toJSON(xmlBatch);
return sortBatches(xmlBatch);
}
function sortBatches(batches) {
return batches.sort(function(a, b) {
return a.type - b.type ||
a.id - b.id ||
a.version - b.version;
});
}
suite('batch/xml', function() {
test('add, multiple items, single values', function() {
var jsonBatch = readJSONBatch(path.join(fixtures, 'add.sdf.json'));
var xmlBatch = readXMLBatch(path.join(fixtures, 'add.sdf.xml'));
assert.deepEqual(xmlBatch, jsonBatch);
});
test('delete, single item', function() {
var jsonBatch = readJSONBatch(path.join(fixtures, 'delete.sdf.json'));
var xmlBatch = readXMLBatch(path.join(fixtures, 'delete.sdf.xml'));
assert.deepEqual(xmlBatch, jsonBatch);
});
});
|
var utils = require('./test-utils');
var assert = require('chai').assert;
var fs = require('fs');
var path = require('path');
var xml = require('../lib/batch/xml');
var fixtures = path.join(__dirname, 'fixture/companies');
function readJSONBatch(filePath) {
var jsonBatch = fs.readFileSync(filePath, 'UTF-8');
jsonBatch = JSON.parse(jsonBatch);
return sortBatches(jsonBatch);
}
function readXMLBatch(filePath) {
var xmlBatch = fs.readFileSync(filePath, 'UTF-8');
xmlBatch = xml.toJSON(xmlBatch);
return sortBatches(xmlBatch);
}
function sortBatches(batches) {
return batches.sort(function(a, b) {
return a.type - b.type ||
a.id - b.id ||
a.version - b.version;
});
}
suite('batch/xml', function() {
test('add, multiple items, single values', function() {
var jsonBatch = readJSONBatch(path.join(fixtures, 'add.sdf.json'));
var xmlBatch = readJSONBatch(path.join(fixtures, 'add.sdf.xml'));
assert.deepEqual(xmlBatch, jsonBatch);
});
test('delete, single item', function() {
var jsonBatch = readJSONBatch(path.join(fixtures, 'delete.sdf.json'));
var xmlBatch = readJSONBatch(path.join(fixtures, 'delete.sdf.xml'));
assert.deepEqual(xmlBatch, jsonBatch);
});
});
|
Fix React import for Jest
|
import * as React from 'react';
// From https://gist.github.com/turadg/9bcf08a7279e82a030a645250639fe6e
// Also needed for TypeScript, not just Flow
/**
* Since React v15.5, there's a warning printed if you access `React.createClass` or `React.PropTypes`
* https://reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings
*
* `import * as React from 'react'` is required by Flowtype https://flow.org/en/docs/react/types/ ,
* but the * causes both those deprecated getters to be called.
* This is particularly annoying in Jest since every test prints two useless warnings.
*
* This file can be used as a Jest setup file to simply delete those features of the `react` package.
* You don't need the deprecation warning. Your tests will simply fail if you're still using the old ways.
* https://facebook.github.io/jest/docs/en/configuration.html#setupfiles-array
*/
delete React.createClass;
delete React.PropTypes;
|
import React from 'react';
// From https://gist.github.com/turadg/9bcf08a7279e82a030a645250639fe6e
// Also needed for TypeScript, not just Flow
/**
* Since React v15.5, there's a warning printed if you access `React.createClass` or `React.PropTypes`
* https://reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings
*
* `import * as React from 'react'` is required by Flowtype https://flow.org/en/docs/react/types/ ,
* but the * causes both those deprecated getters to be called.
* This is particularly annoying in Jest since every test prints two useless warnings.
*
* This file can be used as a Jest setup file to simply delete those features of the `react` package.
* You don't need the deprecation warning. Your tests will simply fail if you're still using the old ways.
* https://facebook.github.io/jest/docs/en/configuration.html#setupfiles-array
*/
delete React.createClass;
delete React.PropTypes;
|
Fix for old numpy versions without cbrt
|
# -*- coding: utf-8 -*-
"""A small module for computing the smoothing length of a Gadget/Arepo simulation."""
import numpy as np
def get_smooth_length(bar):
"""Figures out if the particles are from AREPO or GADGET
and computes the smoothing length.
Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length
The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885)
gives a normalisation so that rho_p = m_p / h^3
So the smoothing length for Arepo is Volume^{1/3}
For gadget the kernel is defined so that the smoothing length is 2*h.
Arguments:
Baryon particles from a simulation
Returns:
Array of smoothing lengths in code units.
"""
#Are we arepo? If we are a modern version we should have this array.
try:
radius = np.cbrt(bar["Volume"], dtype=np.float32)
except KeyError:
#If we don't have a Volume array we are gadget, and
#the SmoothingLength array is actually the smoothing length.
#There is a different kernel definition, as in gadget the kernel goes from 0 to 2,
#whereas I put it between zero and 1.
radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2
except AttributeError:
#This is for really old numpys without cbrts
radius = np.power(bar["Volume"], 1./3, dtype=np.float32)
return radius
|
# -*- coding: utf-8 -*-
"""A small module for computing the smoothing length of a Gadget/Arepo simulation."""
import numpy as np
def get_smooth_length(bar):
"""Figures out if the particles are from AREPO or GADGET
and computes the smoothing length.
Note the Volume array in HDF5 is comoving and this returns a comoving smoothing length
The SPH kernel definition used in Gadget (Price 2011: arxiv 1012.1885)
gives a normalisation so that rho_p = m_p / h^3
So the smoothing length for Arepo is Volume^{1/3}
For gadget the kernel is defined so that the smoothing length is 2*h.
Arguments:
Baryon particles from a simulation
Returns:
Array of smoothing lengths in code units.
"""
#Are we arepo? If we are a modern version we should have this array.
try:
radius = np.cbrt(bar["Volume"], dtype=np.float32)
except KeyError:
#If we don't have a Volume array we are gadget, and
#the SmoothingLength array is actually the smoothing length.
#There is a different kernel definition, as in gadget the kernel goes from 0 to 2,
#whereas I put it between zero and 1.
radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2
return radius
|
Fix requestFrame in IE, where splice requires the deleteCount argument.
|
/*
requestFrame / cancelFrame
*/"use strict"
var array = require("prime/es5/array")
var requestFrame = global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function(callback){
return setTimeout(callback, 1e3 / 60)
}
var callbacks = []
var iterator = function(time){
var split = callbacks.splice(0, callbacks.length)
for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date)))
}
var cancel = function(callback){
var io = array.indexOf(callbacks, callback)
if (io > -1) callbacks.splice(io, 1)
}
var request = function(callback){
var i = callbacks.push(callback)
if (i === 1) requestFrame(iterator)
return function(){
cancel(callback)
}
}
exports.request = request
exports.cancel = cancel
|
/*
requestFrame / cancelFrame
*/"use strict"
var array = require("prime/es5/array")
var requestFrame = global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function(callback){
return setTimeout(callback, 1e3 / 60)
}
var callbacks = []
var iterator = function(time){
var split = callbacks.splice(0)
for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date)))
}
var cancel = function(callback){
var io = array.indexOf(callbacks, callback)
if (io > -1) callbacks.splice(io, 1)
}
var request = function(callback){
var i = callbacks.push(callback)
if (i === 1) requestFrame(iterator)
return function(){
cancel(callback)
}
}
exports.request = request
exports.cancel = cancel
|
Fix load file passing params too
|
'use strict'
var fs = require('fs')
var path = require('path')
var existFile = require('exists-file')
var minimistPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'minimist')
var minimist = require(minimistPath)
var trimNewlinesPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'trim-newlines')
var trimNewlines = require(trimNewlinesPath)
var FILENAME = 'worker-farm.opts'
function readConfig (filepath) {
var yargs = process.argv.slice(2)
if (yargs.length === 0) return yargs
var filepath = path.resolve(yargs[yargs.length - 1], FILENAME)
if (!existFile(filepath)) return yargs
var config = fs.readFileSync(filepath, 'utf8')
config = trimNewlines(config).split('\n')
return config.concat(yargs)
}
module.exports = readConfig()
|
'use strict'
var fs = require('fs')
var path = require('path')
var existFile = require('exists-file')
var minimistPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'minimist')
var minimist = require(minimistPath)
var trimNewlinesPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'trim-newlines')
var trimNewlines = require(trimNewlinesPath)
var FILENAME = 'worker-farm.opts'
function readConfig (filepath) {
var yargs = process.argv.slice(2)
if (yargs.length === 0) return yargs
var filepath = path.resolve(yargs[0], FILENAME)
if (!existFile(filepath)) return yargs
var config = fs.readFileSync(filepath, 'utf8')
config = trimNewlines(config).split('\n')
return config.concat(yargs)
}
module.exports = readConfig()
|
Add middleware for react-router-redux navigation
|
// This file merely configures the store for hot reloading.
// This boilerplate file is likely to be the same for each project that uses Redux.
// With Redux, the actual stores are in /reducers.
import {createStore, compose, applyMiddleware} from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';
import {routerMiddleware} from 'react-router-redux';
import {browserHistory} from 'react-router';
export default function configureStore(initialState) {
const middewares = [
// Add other middleware on this line...
// Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
reduxImmutableStateInvariant(),
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunkMiddleware,
routerMiddleware(browserHistory)
];
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(...middewares),
window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools
)
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers').default; // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
|
// This file merely configures the store for hot reloading.
// This boilerplate file is likely to be the same for each project that uses Redux.
// With Redux, the actual stores are in /reducers.
import {createStore, compose, applyMiddleware} from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
const middewares = [
// Add other middleware on this line...
// Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
reduxImmutableStateInvariant(),
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunkMiddleware,
];
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(...middewares),
window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools
)
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers').default; // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
|
Test migrations with continuous deployment.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
import django_extensions.db.fields
# Comment for testing migrations in Travis continuous deployment.
class Migration(migrations.Migration):
dependencies = [
('notes', '0009_remove_polymorphic_data_migrate'),
]
operations = [
migrations.AlterField(
model_name='NewNote',
name='created',
field=django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')
),
migrations.AlterField(
model_name='NewNote',
name='modified',
field=django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')
),
migrations.DeleteModel('Note'),
migrations.RenameModel('NewNote', 'Note')
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('notes', '0009_remove_polymorphic_data_migrate'),
]
operations = [
migrations.AlterField(
model_name='NewNote',
name='created',
field=django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')
),
migrations.AlterField(
model_name='NewNote',
name='modified',
field=django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')
),
migrations.DeleteModel('Note'),
migrations.RenameModel('NewNote', 'Note')
]
|
Migrate from AndroidSupportInjectionModule to AndroidInjectionModule.
PiperOrigin-RevId: 220291186
|
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.material.catalog.application;
import android.app.Application;
import dagger.BindsInstance;
import dagger.android.AndroidInjectionModule;
import io.material.catalog.application.scope.ApplicationScope;
import io.material.catalog.main.MainActivity;
/** The Application's root component. */
@ApplicationScope
@dagger.Component(
modules = {
AndroidInjectionModule.class,
MainActivity.Module.class,
})
public interface CatalogApplicationComponent {
void inject(CatalogApplication app);
/** The root component's builder. */
@dagger.Component.Builder
interface Builder {
@BindsInstance
CatalogApplicationComponent.Builder application(Application application);
CatalogApplicationComponent build();
}
}
|
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.material.catalog.application;
import android.app.Application;
import dagger.BindsInstance;
import dagger.android.support.AndroidSupportInjectionModule;
import io.material.catalog.application.scope.ApplicationScope;
import io.material.catalog.main.MainActivity;
/** The Application's root component. */
@ApplicationScope
@dagger.Component(
modules = {
AndroidSupportInjectionModule.class,
MainActivity.Module.class,
}
)
public interface CatalogApplicationComponent {
void inject(CatalogApplication app);
/** The root component's builder. */
@dagger.Component.Builder
interface Builder {
@BindsInstance
CatalogApplicationComponent.Builder application(Application application);
CatalogApplicationComponent build();
}
}
|
Add logging in case of process termination
|
import express from 'express';
import log, {INFO, ERR} from "./log";
import {getOpengraphData, removeOpengraphData} from "./opengraph";
const HTTP_TIMEOUT = Number(process.env.HTTP_TIMEOUT) || 10000;
process.on('uncaughtException', function (err) {
log(ERR, `uncaughtException: ${err}`);
process.exit(1);
});
process.on('unhandledRejection', function (err) {
log(ERR, `unhandledRejection: ${err}`);
process.exit(1);
});
log(INFO, "Using a HTTP timeout of " + HTTP_TIMEOUT + " milliseconds");
function respondWithData(res, data) {
res.status(data.status).json(data.json).end();
}
const app = express();
app.get('/opengraph', async (req, res) => {
const data = await getOpengraphData(req.query.url);
respondWithData(res, data);
});
app.delete('/opengraph', async (req, res) => {
const data = await removeOpengraphData(req.query.url);
respondWithData(res, data);
});
app.get('/_health', (req, res) => res.end('Jolly good here'));
app.listen(7070, () => log(INFO, 'Server is listening'));
|
import express from 'express';
import log, {INFO} from "./log";
import {getOpengraphData, removeOpengraphData} from "./opengraph";
const HTTP_TIMEOUT = Number(process.env.HTTP_TIMEOUT) || 10000;
log(INFO, "Using a HTTP timeout of " + HTTP_TIMEOUT + " milliseconds");
function respondWithData(res, data) {
res.status(data.status).json(data.json).end();
}
const app = express();
app.get('/opengraph', async (req, res) => {
const data = await getOpengraphData(req.query.url);
respondWithData(res, data);
});
app.delete('/opengraph', async (req, res) => {
const data = await removeOpengraphData(req.query.url);
respondWithData(res, data);
});
app.get('/_health', (req, res) => res.end('Jolly good here'));
app.listen(7070, () => log(INFO, 'Server is listening'));
|
Add test coverage for \Itafroma\Zork\newstruc().
|
<?php
/**
* @file
* Tests for Prim.php
*/
namespace Itafroma\Zork\Tests;
use Itafroma\Zork\Exception\ConstantAlreadyDefinedException;
use \PHPUnit_Framework_TestCase;
use function Itafroma\Zork\msetg;
use function Itafroma\Zork\newstruc;
class PrimTest extends PHPUnit_Framework_TestCase
{
/**
* Test \Itafroma\Zork\msetg().
*/
public function testMsetg()
{
global $zork;
msetg('foo', 'bar');
$this->assertEquals($zork['foo'], 'bar');
try {
msetg('foo', 'bar');
}
catch (ConstantAlreadyDefinedException $e) {
$this->fail('Itafroma\Zork\Exception\ConstantAlreadyDefinedException should not be thrown when global value is reassigned the same value.');
}
$this->setExpectedException('Itafroma\Zork\Exception\ConstantAlreadyDefinedException');
msetg('foo', 'baz');
}
/**
* Test \Itafroma\Zork\newstruc().
*
* @expectedException \BadFunctionCallException
*/
public function testNewstruc()
{
newstruc('foo', 'bar', ...['one', 'two', 'three']);
}
}
|
<?php
/**
* @file
* Tests for Prim.php
*/
namespace Itafroma\Zork\Tests;
use Itafroma\Zork\Exception\ConstantAlreadyDefinedException;
use \PHPUnit_Framework_TestCase;
use function Itafroma\Zork\msetg;
class PrimTest extends PHPUnit_Framework_TestCase
{
/**
* Test \Itafroma\Zork\msetg().
*/
public function testMsetg()
{
global $zork;
msetg('foo', 'bar');
$this->assertEquals($zork['foo'], 'bar');
try {
msetg('foo', 'bar');
}
catch (ConstantAlreadyDefinedException $e) {
$this->fail('Itafroma\Zork\Exception\ConstantAlreadyDefinedException should not be thrown when global value is reassigned the same value.');
}
$this->setExpectedException('Itafroma\Zork\Exception\ConstantAlreadyDefinedException');
msetg('foo', 'baz');
}
}
|
refactor: Split filter paths into separate vars and check for size in session payload
|
const jsonStringify = require('@bugsnag/safe-json-stringify')
const REPORT_FILTER_PATHS = [
'events.[].app',
'events.[].metaData',
'events.[].user',
'events.[].breadcrumbs',
'events.[].request',
'events.[].device'
]
const SESSION_FILTER_PATHS = [
'device',
'app',
'user'
]
module.exports.report = (report, filterKeys) => {
let payload = jsonStringify(report, null, null, { filterPaths: REPORT_FILTER_PATHS, filterKeys })
if (payload.length > 10e5) {
delete report.events[0].metaData
report.events[0].metaData = {
notifier:
`WARNING!
Serialized payload was ${payload.length / 10e5}MB (limit = 1MB)
metaData was removed`
}
payload = jsonStringify(report, null, null, { filterPaths: REPORT_FILTER_PATHS, filterKeys })
if (payload.length > 10e5) throw new Error('payload exceeded 1MB limit')
}
return payload
}
module.exports.session = (report, filterKeys) => {
const payload = jsonStringify(report, null, null, { filterPaths: SESSION_FILTER_PATHS, filterKeys })
if (payload.length > 10e5) throw new Error('payload exceeded 1MB limit')
return payload
}
|
const jsonStringify = require('@bugsnag/safe-json-stringify')
const filterPaths = [
// report
'events.[].app',
'events.[].metaData',
'events.[].user',
'events.[].breadcrumbs',
'events.[].request',
'events.[].device',
// session
'device',
'app',
'user'
]
module.exports.report = (report, filterKeys) => {
let payload = jsonStringify(report, null, null, { filterPaths, filterKeys })
if (payload.length > 10e5) {
delete report.events[0].metaData
report.events[0].metaData = {
notifier:
`WARNING!
Serialized payload was ${payload.length / 10e5}MB (limit = 1MB)
metaData was removed`
}
payload = jsonStringify(report, null, null, { filterPaths, filterKeys })
if (payload.length > 10e5) throw new Error('payload exceeded 1MB limit')
}
return payload
}
module.exports.session = (report, filterKeys) => {
return jsonStringify(report, null, null, { filterPaths, filterKeys })
}
|
Fix for python2/3 compatibility issue with urllib
|
"""
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
__all__ = ['mstack', 'wget']
def mstack(vs, fs):
import chumpy as ch
import numpy as np
lengths = [v.shape[0] for v in vs]
f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))])
v = ch.vstack(vs)
return v, f
def wget(url, dest_fname=None):
try: #python3
from urllib.request import urlopen
except: #python2
from urllib2 import urlopen
from os.path import split, join
curdir = split(__file__)[0]
print(url)
if dest_fname is None:
dest_fname = join(curdir, split(url)[1])
try:
contents = urlopen(url).read()
except:
raise Exception('Unable to get url: %s' % (url,))
open(dest_fname, 'w').write(contents)
|
"""
Author(s): Matthew Loper
See LICENCE.txt for licensing and contact information.
"""
__all__ = ['mstack', 'wget']
def mstack(vs, fs):
import chumpy as ch
import numpy as np
lengths = [v.shape[0] for v in vs]
f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))])
v = ch.vstack(vs)
return v, f
def wget(url, dest_fname=None):
import urllib.request, urllib.error, urllib.parse
from os.path import split, join
curdir = split(__file__)[0]
print(url)
if dest_fname is None:
dest_fname = join(curdir, split(url)[1])
try:
contents = urllib.request.urlopen(url).read()
except:
raise Exception('Unable to get url: %s' % (url,))
open(dest_fname, 'w').write(contents)
|
Initialize logging very first thing
|
#!/usr/bin/python
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
# Turn on extra info for event exceptions
import pox.lib.revent.revent as revent
revent.showEventExceptions = True
def startup ():
core.register("topology", pox.topology.topology.Topology())
core.register("openflow", pox.openflow.openflow.OpenFlowHub())
core.register("switch", pox.dumb_l3_switch.dumb_l3_switch.dumb_l3_switch())
pox.openflow.of_01.start()
if __name__ == '__main__':
try:
startup()
core.goUp()
except:
import traceback
traceback.print_exc()
import code
code.interact('Ready.', local=locals())
pox.core.core.quit()
|
#!/usr/bin/python
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
# Turn on extra info for event exceptions
import pox.lib.revent.revent as revent
revent.showEventExceptions = True
def startup ():
core.register("topology", pox.topology.topology.Topology())
core.register("openflow", pox.openflow.openflow.OpenFlowHub())
core.register("switch", pox.dumb_l3_switch.dumb_l3_switch.dumb_l3_switch())
pox.openflow.of_01.start()
if __name__ == '__main__':
try:
startup()
core.goUp()
except:
import traceback
traceback.print_exc()
import code
code.interact('Ready.', local=locals())
pox.core.core.quit()
|
Add a default value for the language flag
|
"use strict";
angular.module('arethusa.core').directive('translateLanguage', [
'$translate',
'translator',
function($translate, translator) {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
var langKey;
function useKey(key) {
langKey = key || $translate.use() || 'en';
$translate.use(langKey);
scope.flag = 'images/flags/' + langKey + '.png';
}
var langs = ['en', 'de'];
function toggleLang() {
var i;
i = langs.indexOf(langKey) + 1;
i = i > langs.length - 1 ? 0 : i;
useKey(langs[i]);
}
element.bind('click', function() {
scope.$apply(toggleLang);
});
var parent = element.parent();
translator('language', function(translation) {
parent.attr('title', translation);
});
useKey();
},
templateUrl: 'templates/arethusa.core/translate_language.html'
};
}
]);
|
"use strict";
angular.module('arethusa.core').directive('translateLanguage', [
'$translate',
'translator',
function($translate, translator) {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
var langKey;
function useKey(key) {
langKey = key || $translate.use();
$translate.use(langKey);
scope.flag = 'images/flags/' + langKey + '.png';
}
var langs = ['en', 'de'];
function toggleLang() {
var i;
i = langs.indexOf(langKey) + 1;
i = i > langs.length - 1 ? 0 : i;
useKey(langs[i]);
}
element.bind('click', function() {
scope.$apply(toggleLang);
});
var parent = element.parent();
translator('language', function(translation) {
parent.attr('title', translation);
});
useKey();
},
templateUrl: 'templates/arethusa.core/translate_language.html'
};
}
]);
|
Adjust user filtering logic to 404 only if user does not exist
|
from django.http import Http404
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext as _
from django.views.generic import ListView
from .models import Message
class MessageList(ListView):
template_name = "message_list.html"
model = Message
class MyMessageList(MessageList):
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user=self.request.user)
class FilteredMessageList(MessageList):
def get_queryset(self):
# Check to see if user exists. 404 if not.
username = self.kwargs.get('username')
user = get_object_or_404(get_user_model(), username=username)
# Filter messages by the user as author.
queryset = super().get_queryset()
return queryset.filter(user=user)
return queryset
|
from django.http import Http404
from django.shortcuts import render
from django.utils.translation import ugettext as _
from django.views.generic import ListView
from .models import Message
class MessageList(ListView):
template_name = "message_list.html"
model = Message
class MyMessageList(MessageList):
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user=self.request.user)
class FilteredMessageList(MessageList):
def get_queryset(self):
queryset = super().get_queryset()
queryset = queryset.filter(user__username=self.kwargs.get('username'))
if not queryset:
raise Http404(_('Username not found.'))
return queryset
|
Remove the package registration for L5
|
<?php namespace Jenssegers\Date;
use Illuminate\Support\ServiceProvider;
class DateServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
// Use the Laravel translator.
Date::setTranslator($this->app['translator']);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('Date');
}
}
|
<?php namespace Jenssegers\Date;
use Illuminate\Support\ServiceProvider;
class DateServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('jenssegers/date');
// Use the Laravel translator.
Date::setTranslator($this->app['translator']);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('Date');
}
}
|
Add `err.url` to match `res.url`
|
'use strict';
module.exports = Response;
/**
* A response from a web request
*
* @param {Number} statusCode
* @param {Object} headers
* @param {Buffer} body
* @param {String} url
*/
function Response(statusCode, headers, body, url) {
if (typeof statusCode !== 'number') {
throw new TypeError('statusCode must be a number but was ' + (typeof statusCode));
}
if (headers === null) {
throw new TypeError('headers cannot be null');
}
if (typeof headers !== 'object') {
throw new TypeError('headers must be an object but was ' + (typeof headers));
}
this.statusCode = statusCode;
this.headers = {};
for (var key in headers) {
this.headers[key.toLowerCase()] = headers[key];
}
this.body = body;
this.url = url;
}
Response.prototype.getBody = function (encoding) {
if (this.statusCode >= 300) {
var err = new Error('Server responded with status code '
+ this.statusCode + ':\n' + this.body.toString());
err.statusCode = this.statusCode;
err.headers = this.headers;
err.body = this.body;
err.url = this.url;
throw err;
}
return encoding ? this.body.toString(encoding) : this.body;
};
|
'use strict';
module.exports = Response;
/**
* A response from a web request
*
* @param {Number} statusCode
* @param {Object} headers
* @param {Buffer} body
*/
function Response(statusCode, headers, body, url) {
if (typeof statusCode !== 'number') {
throw new TypeError('statusCode must be a number but was ' + (typeof statusCode));
}
if (headers === null) {
throw new TypeError('headers cannot be null');
}
if (typeof headers !== 'object') {
throw new TypeError('headers must be an object but was ' + (typeof headers));
}
this.statusCode = statusCode;
this.headers = {};
for (var key in headers) {
this.headers[key.toLowerCase()] = headers[key];
}
this.body = body;
this.url = url;
}
Response.prototype.getBody = function (encoding) {
if (this.statusCode >= 300) {
var err = new Error('Server responded with status code '
+ this.statusCode + ':\n' + this.body.toString());
err.statusCode = this.statusCode;
err.headers = this.headers;
err.body = this.body;
throw err;
}
return encoding ? this.body.toString(encoding) : this.body;
};
|
Fix access restriction to /accounts/profile/
LoginRequiredMixin needs to come first for it to be applied. Otherwise,
/accounts/profile/ is accessible even when the user is not
authenticated.
|
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_required
def list_consents(request):
# if a revoke request was done, process it
revoke = request.POST.get('revoke', None)
if revoke is not None:
consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke)
if consent:
revoked_client = consent[0].client
consent[0].delete()
messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name))
else:
client = Client.objects.filter(client_id=revoke)
if client:
messages.error(request, "You have no consent for client \"{}\".".format(client[0].name))
else:
messages.error(request, "Unknown client.")
# render the result
consents = UserConsent.objects.filter(user=request.user)
return render(request, 'list_consents.html', {
'consents': consents
})
class ProfileView(LoginRequiredMixin, TemplateView):
template_name = 'profile.html'
|
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_required
def list_consents(request):
# if a revoke request was done, process it
revoke = request.POST.get('revoke', None)
if revoke is not None:
consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke)
if consent:
revoked_client = consent[0].client
consent[0].delete()
messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name))
else:
client = Client.objects.filter(client_id=revoke)
if client:
messages.error(request, "You have no consent for client \"{}\".".format(client[0].name))
else:
messages.error(request, "Unknown client.")
# render the result
consents = UserConsent.objects.filter(user=request.user)
return render(request, 'list_consents.html', {
'consents': consents
})
class ProfileView(TemplateView, LoginRequiredMixin):
template_name = 'profile.html'
|
Add differentiation between GET and POST requests
|
const url = require('url')
const level = require('level')
const then = require('then-levelup')
const { send, createError, sendError } = require('micro')
const db = then(level('blog-views'))
module.exports = async function (req, res) {
// Check that a page is provided
const { pathname } = url.parse(req.url)
if (pathname.length <= 1) {
throw createError(400, 'Please include a path to a page.')
}
if (req.method !== 'GET' && req.method !== 'POST') {
throw createError(400, 'Please make a GET or a POST request.')
}
try {
const views = parseInt(await db.get(pathname), 10)
// Increment the views and send them back to client
await db.put(pathname, views + 1)
if (req.method === 'GET') {
send(res, 200, { views: views + 1 })
} else {
send(res, 200)
}
} catch (err) {
if (err.notFound) {
// Initialise the page with one view
await db.put(pathname, 1)
if (req.method === 'GET') {
send(res, 200, { views: 1 })
} else {
send(res, 200)
}
} else {
throw createError(500, 'Internal server error.')
}
}
}
|
const url = require('url')
const level = require('level')
const then = require('then-levelup')
const { send, createError, sendError } = require('micro')
const db = then(level('blog-views'))
module.exports = async function (req, res) {
// Check that a page is provided
const { pathname } = url.parse(req.url)
if (pathname.length <= 1) {
throw createError(400, 'Please include a path to a page.')
}
if (req.method !== 'GET') {
throw createError(400, 'Please make a GET request.')
}
try {
const views = parseInt(await db.get(pathname), 10)
// Increment the views and send them back to client
await db.put(pathname, views + 1)
send(res, 200, { views: views + 1 })
} catch (err) {
if (err.notFound) {
// Initialise the page with one view
await db.put(pathname, 1)
send(res, 200, { views: 1 })
} else {
throw createError(500, 'Something went wrong, sorry about that.')
}
}
}
|
Fix abbreviation list not showing
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import Endpoints from './Endpoints';
import './styles/HeaderBoardList.css';
class HeaderBoardList extends Component {
componentDidMount() { this.fetchBoards(); }
componentWillReceiveProps() { this.fetchBoards(); }
render() {
let abbreviations = [];
if (this.state && this.state.data) {
abbreviations = this.state.data.map(d => d.board.abbreviation).sort();
}
const list = abbreviations.map(abbr => <HeaderBoardListItem abbr={abbr} key={abbr} />);
return (
<div className='HeaderBoardList'>
<ul className='HeaderBoardList__list'>
{list}
</ul>
</div>
);
}
fetchBoards() {
Endpoints.Boards().getData()
.then(data => {
this.setState({data: data});
})
.catch(err => {
console.error("HeaderBoardList::fetchBoards", "Couldn't get Boards endpoint!", err);
})
}
}
const HeaderBoardListItem = ({abbr}) => (
<li className='HeaderBoardList__list__item'>
<Link className='HeaderBoardList__list__item__anchor' to={'/boards/' + abbr + '/'}>
{abbr}
</Link>
</li>
);
export default HeaderBoardList;
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import Endpoints from './Endpoints';
import './styles/HeaderBoardList.css';
class HeaderBoardList extends Component {
componentDidMount() { this.fetchBoards(); }
componentWillReceiveProps() { this.fetchBoards(); }
render() {
let abbreviations = [];
if (this.state && this.state.data) {
abbreviations = this.state.data.map(b => b.abbreviation).sort();
}
const list = abbreviations.map(abbr => <HeaderBoardListItem abbr={abbr} key={abbr} />);
return (
<div className='HeaderBoardList'>
<ul className='HeaderBoardList__list'>
{list}
</ul>
</div>
);
}
fetchBoards() {
Endpoints.Boards().getData()
.then(data => {
this.setState({data: data});
})
.catch(err => {
console.error("HeaderBoardList::fetchBoards", "Couldn't get Boards endpoint!", err);
})
}
}
const HeaderBoardListItem = ({abbr}) => (
<li className='HeaderBoardList__list__item'>
<Link className='HeaderBoardList__list__item__anchor' to={'/boards/' + abbr + '/'}>
{abbr}
</Link>
</li>
);
export default HeaderBoardList;
|
Prepare plugin for gui testing with remote-robot
GitOrigin-RevId: 708ebfb9f4d7f57bbeafc6ff64434039f2865bdd
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cloudConfig;
import com.intellij.openapi.wm.StatusBar;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
/**
* @author Alexander Lobas
*/
public abstract class CloudConfigTestProvider {
private static CloudConfigTestProvider myProvider;
public static @Nullable CloudConfigTestProvider getProvider() {
return myProvider;
}
public static void setProvider(@NotNull CloudConfigTestProvider provider) {
myProvider = provider;
}
public abstract void initLocalClient(@NotNull File location);
public abstract @NotNull String getStatusInfo();
public abstract @NotNull String getPluginsInfo();
public abstract @NotNull String getActions(@NotNull StatusBar statusBar);
public abstract void runAction(@NotNull StatusBar statusBar, @NotNull String name);
}
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cloudConfig;
import com.intellij.openapi.wm.StatusBar;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
/**
* @author Alexander Lobas
*/
public abstract class CloudConfigTestProvider {
private static CloudConfigTestProvider myProvider;
public static @Nullable CloudConfigTestProvider getProvider() {
return myProvider;
}
public static void setProvider(@NotNull CloudConfigTestProvider provider) {
myProvider = provider;
}
public abstract void initLocalClient(@NotNull File location);
public abstract @NotNull String getStatusInfo();
public abstract @NotNull String getActions(@NotNull StatusBar statusBar);
public abstract void runAction(@NotNull StatusBar statusBar, @NotNull String name);
}
|
Fix compatibility for SublimeLinter 4.12.0
Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint @ ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
syntax = ('html', 'html+tt2', 'html+tt3')
cmd = ('bemlint', '@', '--format', 'compact')
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
|
Fix an issue any page is redirected to the top page when opening the cache of the login page (for example with the back button)
|
import queryString from 'query-string'
export default class CrowiAuth {
constructor(crowi) {
this.crowi = crowi
this.location = crowi.location
this.localStorage = crowi.localStorage
this.onStorage = this.onStorage.bind(this)
this.subscribeStorage()
this.updateState()
}
isAuthenticated() {
const { id, name } = this.crowi.getUser()
return !!(id && name)
}
subscribeStorage() {
window.addEventListener('storage', this.onStorage)
}
shouldUpdate() {
return this.isAuthenticated() !== this.localStorage.getItem('authenticated')
}
updateState() {
if (this.shouldUpdate()) {
this.localStorage.setItem('authenticated', this.isAuthenticated())
}
}
onStorage(e) {
const { key, newValue } = e
const isAuthenticated = newValue === 'true'
if (key === 'authenticated') {
if (isAuthenticated) {
this.onLogin()
} else {
this.onLogout()
}
}
}
onLogin() {
const { continue: continueUrl } = queryString.parse(this.location.search)
if (continueUrl) {
top.location.href = continueUrl
} else {
this.location.reload()
}
}
onLogout() {
this.location.reload()
}
}
|
import queryString from 'query-string'
export default class CrowiAuth {
constructor(crowi) {
this.crowi = crowi
this.location = crowi.location
this.localStorage = crowi.localStorage
this.onStorage = this.onStorage.bind(this)
this.subscribeStorage()
this.updateState()
}
isAuthenticated() {
const { id, name } = this.crowi.getUser()
return !!(id && name)
}
subscribeStorage() {
window.addEventListener('storage', this.onStorage)
}
shouldUpdate() {
return this.isAuthenticated() !== this.localStorage.getItem('authenticated')
}
updateState() {
if (this.shouldUpdate()) {
this.localStorage.setItem('authenticated', this.isAuthenticated())
}
}
onStorage(e) {
const { key, newValue } = e
const isAuthenticated = newValue === 'true'
if (key === 'authenticated') {
if (isAuthenticated) {
this.onLogin()
} else {
this.onLogout()
}
}
}
onLogin() {
const { continue: continueUrl = '/' } = queryString.parse(this.location.search)
top.location.href = continueUrl
}
onLogout() {
this.location.reload()
}
}
|
Fix bug and delete unused library
|
# -*- coding: utf-8 -*-
import cv2
import sys
def resize(src, w_ratio, h_ratio):
height = src.shape[0]
width = src.shape[1]
dst = cv2.resize(src,((int)(width/100*w_ratio),(int)(height/100*h_ratio)))
return dst
if __name__ == '__main__':
param = sys.argv
if (len(param) != 4):
print ("Usage: $ python " + param[0] + " sample.jpg wide_ratio height_ratio")
quit()
# open image file
try:
input_img = cv2.imread(param[1])
except:
print ('faild to load %s' % param[1])
quit()
if input_img is None:
print ('faild to load %s' % param[1])
quit()
w_ratio = int(param[2])
h_ratio = int(param[3])
output_img = resize(input_img, w_ratio, h_ratio)
cv2.imwrite(param[1], output_img)
|
# -*- coding: utf-8 -*-
import cv2
import sys
import numpy as np
def resize(src, w_ratio, h_ratio):
height = src.shape[0]
width = src.shape[1]
dst = cv2.resize(src,(width/100*w_ratio,height/100*h_ratio))
return dst
if __name__ == '__main__':
param = sys.argv
if (len(param) != 4):
print ("Usage: $ python " + param[0] + " sample.jpg wide_ratio height_ratio")
quit()
# open image file
try:
input_img = cv2.imread(param[1])
except:
print ('faild to load %s' % param[1])
quit()
if input_img is None:
print ('faild to load %s' % param[1])
quit()
w_ratio = int(param[2])
h_ratio = int(param[3])
output_img = resize(input_img, w_ratio, h_ratio)
cv2.imwrite(param[1], output_img)
|
Add certifi to required packages
|
# coding: utf-8
from setuptools import setup
setup(
name='pysuru',
version='0.0.1',
description='Python library to interact with Tsuru API',
long_description=open('README.rst', 'r').read(),
keywords='tsuru',
author='Rodrigo Machado',
author_email='rcmachado@gmail.com',
url='https://github.com/rcmachado/pysuru',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers'
'Topic :: Software Development :: Libraries',
],
install_requires=[
'urllib3>=1.15',
'certifi'
]
packages=['pysuru'],
platforms=['linux', 'osx']
)
|
# coding: utf-8
from setuptools import setup
setup(
name='pysuru',
version='0.0.1',
description='Python library to interact with Tsuru API',
long_description=open('README.rst', 'r').read(),
keywords='tsuru',
author='Rodrigo Machado',
author_email='rcmachado@gmail.com',
url='https://github.com/rcmachado/pysuru',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers'
'Topic :: Software Development :: Libraries',
],
install_requires=[
'urllib3>=1.15'
]
packages=['pysuru'],
platforms=['linux', 'osx']
)
|
Handle Sentry error ID in front Ajax
|
/**
* Common stack, plugins and helpers
*/
import config from 'config';
import $ from 'jquery';
import Notify from 'notify';
import 'bootstrap';
import 'widgets/site-search';
import 'utils/ellipsis';
import 'vendor/jquery.microdata';
import 'i18n';
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
xhr.setRequestHeader('X-CSRFToken', config.csrftoken);
}
}
});
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
const sentry_id = jqxhr.getResponseHeader('X-Sentry-ID');
if (sentry_id) {
Notify.error([
i18n._('An error occured'),
i18n._('The error identifier is {id}', {id: sentry_id}),
].join('. '))
}
});
$(function() {
// Display tooltips and popovers with markup
$('[rel=tooltip]').tooltip();
$('[rel=popover]').popover().on('click', function(e) {
if ($(this).data('trigger').match(/(click|focus)/)) {
e.preventDefault();
return true;
}
});
});
|
/**
* Common stack, plugins and helpers
*/
import config from 'config';
import $ from 'jquery';
import 'bootstrap';
import 'widgets/site-search';
import 'utils/ellipsis';
import 'vendor/jquery.microdata';
import 'i18n';
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
xhr.setRequestHeader('X-CSRFToken', config.csrftoken);
}
}
});
$(function() {
// Display tooltips and popovers with markup
$('[rel=tooltip]').tooltip();
$('[rel=popover]').popover().on('click', function(e) {
if ($(this).data('trigger').match(/(click|focus)/)) {
e.preventDefault();
return true;
}
});
});
|
Test things first you big dummy
|
import math
from django.shortcuts import render
from django.template import RequestContext
from django.http import HttpResponseRedirect
from orders.models import Order
def index(request, x, y):
if request.META.get('HTTP_REFERER', None) not in ('http://www.urbandead.com/map.cgi', 'http://urbandead.com/map.cgi'):
return HttpResponseRedirect('http://www.youtube.com/watch?v=lWKQiZVBtu4')
x = int(x)
y = int(y)
# Fetch the orders
fresh_order = list(Order.objects.all().order_by('-date'))
fresh_order.sort(key=lambda o: user_coord_dist(x, y, o.x, o.y))
# Return orders sorted by distance
return render(request, 'orders/orders.html', dict(orders=fresh_order))
def user_coord_dist(x1, y1, x2, y2):
# Pythagoras
return math.sqrt(math.pow(x2-x1,2)+math.pow(y2-y1,2))
|
import math
from django.shortcuts import render
from django.template import RequestContext
from django.http import HttpResponseRedirect
from orders.models import Order
def index(request, x, y):
if request.META['HTTP_REFERER'] not in ('http://www.urbandead.com/map.cgi', 'http://urbandead.com/map.cgi'):
return HttpResponseRedirect('http://www.youtube.com/watch?v=lWKQiZVBtu4')
x = int(x)
y = int(y)
# Fetch the orders
fresh_order = list(Order.objects.all().order_by('-date'))
fresh_order.sort(key=lambda o: user_coord_dist(x, y, o.x, o.y))
# Return orders sorted by distance
return render(request, 'orders/orders.html', dict(orders=fresh_order))
def user_coord_dist(x1, y1, x2, y2):
# Pythagoras
return math.sqrt(math.pow(x2-x1,2)+math.pow(y2-y1,2))
|
Set server response type to json
|
var http = require('http'),
io = require('socket.io-client'),
url = require('url');
var server = http.createServer(function(request, response) {
response.writeHead(200, {
'Content-type': 'application/json'
});
var queryObject = url.parse(request.url,true).query;
var matchid = queryObject.matchid;
socket = io.connect('http://scorebot.hltv.org:10022');
socket.on('score', function(score) {
jsonobj = {
"scorea" : score['ctScore'],
"scoreb" : score['tScore']
};
response.end(JSON.stringify(jsonobj));
});
socket.emit('readyForMatch', matchid);
});
server.listen(8000, 'ikinz.se');
|
var http = require('http'),
io = require('socket.io-client'),
url = require('url');
var server = http.createServer(function(request, response) {
response.writeHead(200, {
'Content-type': 'text/plain'
});
var queryObject = url.parse(request.url,true).query;
var matchid = queryObject.matchid;
socket = io.connect('http://scorebot.hltv.org:10022');
socket.on('score', function(score) {
jsonobj = {
"scorea" : score['ctScore'],
"scoreb" : score['tScore']
};
response.end(JSON.stringify(jsonobj));
});
socket.emit('readyForMatch', matchid);
});
server.listen(8000, 'ikinz.se');
|
Remove warning for Django 1.7
|
#!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
settings.configure(
DEBUG = True,
TEMPLATE_DEBUG = True,
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader',
),
INSTALLED_APPS = (
'template_analyzer',
),
MIDDLEWARE_CLASSES = (),
)
def runtests():
argv = sys.argv[:1] + ['test', 'template_analyzer', '--traceback'] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == '__main__':
runtests()
|
#!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
settings.configure(
DEBUG = True,
TEMPLATE_DEBUG = True,
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader',
),
INSTALLED_APPS = (
'template_analyzer',
)
)
def runtests():
argv = sys.argv[:1] + ['test', 'template_analyzer', '--traceback'] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == '__main__':
runtests()
|
Make this work with Django 1.4
|
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from ...settings import User
from ...sync import sync_customer
class Command(BaseCommand):
help = "Sync customer data with stripe"
def handle(self, *args, **options):
qs = User.objects.exclude(customer__isnull=True)
count = 0
total = qs.count()
for user in qs:
count += 1
perc = int(round(100 * (float(count) / float(total))))
print("[{0}/{1} {2}%] Syncing {3} [{4}]").format(
count, total, perc, user.username, user.pk
)
sync_customer(user)
|
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from ...settings import get_user_model
from ...sync import sync_customer
User = get_user_model()
class Command(BaseCommand):
help = "Sync customer data with stripe"
def handle(self, *args, **options):
qs = User.objects.exclude(customer__isnull=True)
count = 0
total = qs.count()
for user in qs:
count += 1
perc = int(round(100 * (float(count) / float(total))))
print("[{0}/{1} {2}%] Syncing {3} [{4}]").format(
count, total, perc, user.username, user.pk
)
sync_customer(user)
|
Add blinky cursor upon page load
|
function recipeSearch(input) {
$.ajax({
url: "/recipes",
data: input,
}).done(function(recipeItemPartial) {
$(recipeItemPartial).appendTo(".main-searchbar");
});
}
var throttledSearch = _.throttle(recipeSearch, 300);
$(document).ready(function() {
$('input').focus();
$(".form-control").keyup(function(event){
$(".drop-down").remove();
event.preventDefault();
var input = $(this).serialize();
if ($(this).val().length > 1) {
throttledSearch(input);
}
});
$(document).on("mouseover", "mark", function(){
$("div").removeClass("hovered-term");
var container = ".scrollable";
text = $(this).text().toLowerCase();
termCard = $(container).find("#"+text);
$(container).prepend(termCard).scrollTop();
$(termCard).addClass("hovered-term");
$
});
});
|
function recipeSearch(input) {
$.ajax({
url: "/recipes",
data: input,
}).done(function(recipeItemPartial) {
$(recipeItemPartial).appendTo(".main-searchbar");
});
}
var throttledSearch = _.throttle(recipeSearch, 300);
$(document).ready(function() {
$(".form-control").keyup(function(event){
$(".drop-down").remove();
event.preventDefault();
var input = $(this).serialize();
if ($(this).val().length > 1) {
throttledSearch(input);
}
});
$(document).on("mouseover", "mark", function(){
$("div").removeClass("hovered-term");
var container = ".scrollable";
text = $(this).text().toLowerCase();
termCard = $(container).find("#"+text);
$(container).prepend(termCard).scrollTop();
$(termCard).addClass("hovered-term");
$
});
});
|
Update pyyaml requirement to >=3.12,<4.2
Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version.
- [Release notes](https://github.com/yaml/pyyaml/releases)
- [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES)
- [Commits](https://github.com/yaml/pyyaml/commits/4.1)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
|
from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.0.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<6.8',
'PyYAML>=3.12,<4.2',
'panoptes-client>=1.0,<2.0',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.0.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<6.8',
'PyYAML>=3.12,<3.13',
'panoptes-client>=1.0,<2.0',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
Make REPL context properties read-only
|
'use strict';
// MODULES //
var r = require( 'repl' );
var getKeys = require( 'object-keys' ).shim();
var namespace = require( '@stdlib/namespace' );
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var defaults = require( './defaults.js' );
// REPL //
/**
* Starts a REPL environment.
*
* @returns {Object} REPL server
*
* @example
* repl();
*/
function repl() {
var context;
var server;
var opts;
var keys;
var key;
var i;
opts = defaults();
server = r.start( opts );
// Create a REPL context:
context = namespace( {} );
// Bind all context values to the REPL server...
keys = getKeys( context );
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
setReadOnly( server.context, key, context[ key ] );
}
return server;
} // end FUNCTION repl()
// EXPORTS //
module.exports = repl;
|
'use strict';
// MODULES //
var r = require( 'repl' );
var getKeys = require( 'object-keys' ).shim();
var namespace = require( '@stdlib/namespace' );
var defaults = require( './defaults.js' );
// REPL //
/**
* Starts a REPL environment.
*
* @returns {Object} REPL server
*
* @example
* repl();
*/
function repl() {
var context;
var server;
var opts;
var keys;
var key;
var i;
opts = defaults();
server = r.start( opts );
// Create a REPL context:
context = namespace( {} );
// Bind all context values to the REPL server...
keys = getKeys( context );
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
server.context[ key ] = context[ key ];
}
return server;
} // end FUNCTION repl()
// EXPORTS //
module.exports = repl;
|
Disable SQLAlchemy change tracking signals
This is enabled by default, which currently emits a warning.
The default will be False in the future.
|
import os
class Config:
"""Base configuration."""
ENV = None
PATH = os.path.abspath(os.path.dirname(__file__))
ROOT = os.path.dirname(PATH)
DEBUG = False
THREADED = False
GOOGLE_ANALYTICS_TID = os.getenv('GOOGLE_ANALYTICS_TID')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = False
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
class TestConfig(Config):
"""Test configuration."""
ENV = 'test'
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = "postgresql://localhost/memegen_test"
class DevConfig(Config):
"""Development configuration."""
ENV = 'dev'
DEBUG = True
def get_config(name):
assert name, "no configuration specified"
for config in Config.__subclasses__(): # pylint: disable=no-member
if config.ENV == name:
return config
assert False, "no matching configuration"
|
import os
class Config:
"""Base configuration."""
ENV = None
PATH = os.path.abspath(os.path.dirname(__file__))
ROOT = os.path.dirname(PATH)
DEBUG = False
THREADED = False
GOOGLE_ANALYTICS_TID = os.getenv('GOOGLE_ANALYTICS_TID')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
class TestConfig(Config):
"""Test configuration."""
ENV = 'test'
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = "postgresql://localhost/memegen_test"
class DevConfig(Config):
"""Development configuration."""
ENV = 'dev'
DEBUG = True
def get_config(name):
assert name, "no configuration specified"
for config in Config.__subclasses__(): # pylint: disable=no-member
if config.ENV == name:
return config
assert False, "no matching configuration"
|
Add comments to clarify the relationship between feathers, Sequelize, and setting table relationships.
|
'use strict';
const Sequelize = require('sequelize');
// projects-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
module.exports = function(sequelize) {
const Projects = sequelize.define('Projects', {
name: {
type: Sequelize.STRING,
allowNull: false
},
description:{
type: Sequelize.STRING,
allowNull: false
},
bounty: {
type: Sequelize.INTEGER,
allowNull: false,
},
videoUrl: {
type: Sequelize.STRING,
allowNull: true
},
awarded:{
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
image: {
type: Sequelize.BLOB('long'),
allowNull: true
}
}, {
/* Feathers adds additional level of complexity when creating database tables.
the class Method associate is used to add the table relations before the database is synced. The actual creation of ll the tables happens in the services/index.js file */
classMethods: {
associate() {
Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'});
}
}
});
return Projects;
};
|
'use strict';
const Sequelize = require('sequelize');
// projects-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
module.exports = function(sequelize) {
const Projects = sequelize.define('Projects', {
name: {
type: Sequelize.STRING,
allowNull: false
},
description:{
type: Sequelize.STRING,
allowNull: false
},
bounty: {
type: Sequelize.INTEGER,
allowNull: false,
},
videoUrl: {
type: Sequelize.STRING,
allowNull: true
},
awarded:{
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
image: {
type: Sequelize.BLOB('long'),
allowNull: true
}
}, {
image: {
type: Sequelize.BLOB('long'),
allowNull: true
}
}, {
/* Feathers adds additional level of complexity when creating database tables.
the class Method associate is used to add the table relations before the database is synced. The actual creation of ll the tables happens in the services/index.js file */
classMethods: {
associate() {
Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'});
}
}
});
return Projects;
};
|
Remove print statements, not usefull anymore.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def fix_multiple_default_templates(apps, schema_editor):
# Some users have more than 1 default template.
# This shouldn't be possible, make sure is will be just 1.
User = apps.get_model('users', 'LilyUser')
DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate')
for user in User.objects.all():
templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id')
if templates.count() > 1:
# User has more than one default template.
# Best guess would be that the user prefers the last set template to be the default.
# So remove all except the last one.
template_to_keep = templates.last()
templates.exclude(id=template_to_keep.id).delete()
class Migration(migrations.Migration):
dependencies = [
('email', '0012_auto_20160715_1423'),
]
operations = [
migrations.RunPython(fix_multiple_default_templates),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def fix_multiple_default_templates(apps, schema_editor):
# Some users have more than 1 default template.
# This shouldn't be possible, make sure is will be just 1.
User = apps.get_model('users', 'LilyUser')
DefaultEmailTemplate = apps.get_model('email', 'DefaultEmailTemplate')
print('\nFixing default template for the following users:')
for user in User.objects.all():
templates = DefaultEmailTemplate.objects.filter(user=user.pk).order_by('id')
if templates.count() > 1:
# User has more than one default template.
# Best guess would be that the user prefers the last set template to be the default.
# So remove all except the last one.
template_to_keep = templates.last()
templates.exclude(id=template_to_keep.id).delete()
print('%d:\t%s' % (user.pk, user.email))
class Migration(migrations.Migration):
dependencies = [
('email', '0012_auto_20160715_1423'),
]
operations = [
migrations.RunPython(fix_multiple_default_templates),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.