text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix specification of Python 3.6 and 3.7 | from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.3.3',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
install_requires=[
'lxml >= 4.4.0',
'requests >= 2.22.0',
'six >= 1.12.0'
],
entry_points={
}
)
| from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.3.3',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 3.7.5'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=False,
install_requires=[
'lxml >= 4.4.0',
'requests >= 2.22.0',
'six >= 1.12.0'
],
entry_points={
}
)
|
Add @Before method so that all extending tests cleanup the Redis database before executing
This makes sure we work starting from an empty database | package com.github.gabrielruiu.spring.cloud.config.redis;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
import java.util.Set;
/**
* @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BaseRedisEnvironmentRepositoryTest {
@LocalServerPort
int port;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
TestRestTemplate testRestTemplate;
@Before
public void cleanUpRedis() {
Set<String> keys = stringRedisTemplate.keys("*");
stringRedisTemplate.delete(keys);
}
protected void injectPropertiesIntoRedis(Map<String, String> properties) {
for (Map.Entry<String, String> propertyEntry : properties.entrySet()) {
stringRedisTemplate.opsForValue().set(propertyEntry.getKey(), propertyEntry.getValue());
}
}
}
| package com.github.gabrielruiu.spring.cloud.config.redis;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
/**
* @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BaseRedisEnvironmentRepositoryTest {
@LocalServerPort
int port;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
TestRestTemplate testRestTemplate;
protected void injectPropertiesIntoRedis(Map<String, String> properties) {
for (Map.Entry<String, String> propertyEntry : properties.entrySet()) {
stringRedisTemplate.opsForValue().set(propertyEntry.getKey(), propertyEntry.getValue());
}
}
}
|
Correct typo in NEP2 test | import 'react-native'
import { encryptWIF, decryptWIF } from '../app/api/crypto'
// use official test vectors from https://github.com/neo-project/proposals/blob/master/nep-2.mediawiki#test-vectors
const unencryptedWIF = 'L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP'
const passphrase = 'TestingOneTwoThree'
const encryptedWIF = '6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL'
it('should encrypt a WIF correctly', () => {
expect(encryptWIF(unencryptedWIF, passphrase)).toEqual(encryptedWIF)
})
it('should decrypt a WIF correctly', () => {
expect(decryptWIF(encryptedWIF, passphrase)).toEqual(unencryptedWIF)
})
it('should notify about an incorrect passphrase when failing to decrypt a WIF', () => {
expect(function() {
decryptWIF(encryptedWIF, 'wrongPassphrase')
}).toThrowError('Wrong passphrase!')
})
| import 'react-native'
import { encryptWIF, decryptWIF } from '../app/api/crypto'
// use official test vectors from https://github.com/neo-project/proposals/blob/master/nep-2.mediawiki#test-vectors
const unencryptedWIF = 'L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP'
const passphrase = 'TestingOneTwoThree'
const encryptedWIF = '6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL'
it('should encrypt a WIF correctly', () => {
expect(encryptWIF(unencryptedWIF, passphrase)).toEqual(encryptedWIF)
})
it('should decrypt a WIF correctly', () => {
expect(decryptWIF(encryptedWIF, passphrase)).toEqual(unencryptedWIF)
})
it('should notify about an incorrect passphrase when failing to decrypt a WIF', () => {
expect(function() {
decryptWIF(encryptedWIF, 'wrongPassphrase')
}).toThrowError('Wrong Password!')
})
|
Send 10 events to Ruby at a time | const execFile = require('child_process').execFile;
exports.handler = function(event, context) {
const chunkSize = 10;
var records = event.Records;
var context = context;
console.log("Received " + records.length + " records.")
var chunkOffset = 0;
var chunks = []
while (chunkOffset < records.length) {
chunks.push(records.slice(chunkOffset, chunkOffset + chunkSize));
chunkOffset += chunkSize;
}
chunks.forEach(function(chunk, index) {
const child = execFile('./ruby_wrapper', [JSON.stringify(chunk), JSON.stringify(context)], {}, (error, stdout, stderr) => {
stdout.trim().split("\n").forEach(function(x) {
log = x.trim();
if (log !== "") {
console.log(log);
}
});
stderr.trim().split("\n").forEach(function(x) {
log = x.trim();
if (log !== "") {
console.log(log);
}
});
if (error) {
console.error(`exec error: ${error}`);
process.exit(1);
}
});
});
};
| const execFile = require('child_process').execFile;
exports.handler = function(event, context) {
const chunkSize = 5;
var records = event.Records;
var context = context;
console.log("Received " + records.length + " records.")
var chunkOffset = 0;
var chunks = []
while (chunkOffset < records.length) {
chunks.push(records.slice(chunkOffset, chunkOffset + chunkSize));
chunkOffset += chunkSize;
}
chunks.forEach(function(chunk, index) {
const child = execFile('./ruby_wrapper', [JSON.stringify(chunk), JSON.stringify(context)], {}, (error, stdout, stderr) => {
stdout.trim().split("\n").forEach(function(x) {
log = x.trim();
if (log !== "") {
console.log(log);
}
});
stderr.trim().split("\n").forEach(function(x) {
log = x.trim();
if (log !== "") {
console.log(log);
}
});
if (error) {
console.error(`exec error: ${error}`);
process.exit(1);
}
});
});
};
|
Add instance name logic for unique ids in binding handlers | define(['knockout', 'jquery', 'lodash', './model',
'knockout.punches',
'template!./template/index.html!<%= model.name %>-main',
],
function(ko, $, _, ViewModel) {
ko.punches.enableAll();
ko.bindingHandlers.<%= model.name %> = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor());
element.model = new ViewModel();
element.model.instanceName = allBindings.get('id') || _.uniqueId("<%= model.name %>--");
ko.renderTemplate("<%= model.name %>-main", element.model, null, element, "replaceChildren");
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
element.value = ko.utils.unwrapObservable(valueAccessor());
}
};
});
| define(['knockout', 'jquery', './model',
'knockout.punches',
'template!./template/index.html!<%= model.name %>-main',
],
function(ko, $, ViewModel) {
ko.punches.enableAll();
ko.bindingHandlers.<%= model.name %> = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor());
element.model = new ViewModel();
ko.renderTemplate("<%= model.name %>-main", element.model, null, element, "replaceChildren");
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
element.value = ko.utils.unwrapObservable(valueAccessor());
}
};
});
|
Change default README to rst file | # coding: utf8
from setuptools import setup
setup(
name='pyshorteners',
version='0.1',
license='MIT',
description='A simple URL shortening Python Lib, implementing the most famous shorteners.',
long_description=open('README.rst').read(),
author=u'Ellison Leão',
author_email='ellisonleao@gmail.com',
url='https://github.com/ellisonleao/pyshorteners/',
platforms='any',
zip_save=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
install_requires=['requests',],
test_suite="test_shorteners",
packages=['pyshorteners'],
namespace_packages=['pyshorteners'],
)
| # coding: utf8
from setuptools import setup
setup(
name='pyshorteners',
version='0.1',
license='MIT',
description='A simple URL shortening Python Lib, implementing the most famous shorteners.',
long_description=open('README.md').read(),
author=u'Ellison Leão',
author_email='ellisonleao@gmail.com',
url='https://github.com/ellisonleao/pyshorteners/',
platforms='any',
zip_save=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
install_requires=['requests',],
test_suite="test_shorteners",
packages=['pyshorteners'],
namespace_packages=['pyshorteners'],
)
|
Test runner uses current python |
import os, sys
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
continue
if not f.startswith("test_"):
continue
test_file = os.path.join(subdir, f)
print "FILE:", test_file
exit_code = os.system(sys.executable + " " + test_file)
total += 1
if exit_code != 0:
errs += 1
print "SUMMARY: %s -> %s total / %s error (%s)" \
% (subdir, total, errs, sys.executable)
if __name__ == "__main__":
os.chdir(TEST_DIR)
os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR])
runtestdir("bindertest")
|
import os
PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ ))
SRC_DIR = os.path.join(PROJECT_DIR, "src")
TEST_DIR = os.path.join(PROJECT_DIR, "test")
def runtestdir(subdir):
#cwd = os.getcwd()
#subdir = os.path.join(cwd, subdir)
entries = os.listdir(subdir)
total = 0
errs = 0
for f in entries:
if not f.endswith(".py"):
continue
if not f.startswith("test_"):
continue
cmd = "python %s/%s" % (subdir, f)
print "FILE: %s/%s" % (subdir, f)
exit_code = os.system(cmd)
total += 1
if exit_code != 0:
errs += 1
print "SUMMARY: %s -> %s total / %s error" % (subdir, total, errs)
if __name__ == "__main__":
#
os.chdir(TEST_DIR)
#
os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR])
#
runtestdir("bindertest")
|
Return an "empty sequence" character instead of an empty list for empty select fields | # -*- coding: utf-8 -*-
"""Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import (
QuerySelectField, QuerySelectMultipleField, BooleanField)
def data(field):
"""Field data beautifier.
QuerySelectMultipleField
Renders comma-separated data.
QuerySelectField
Renders the selected value.
BooleanField
Renders '✓' or '✕'
Example:
.. sourcecode:: html+jinja
<dd>{{ field | data }}</dd>
"""
if isinstance(field, QuerySelectMultipleField):
if field.data:
return escape(
u', '.join(field.get_label(data) for data in field.data))
else:
return u'∅'
elif isinstance(field, QuerySelectField):
if field.data:
return escape(field.get_label(field.data))
elif isinstance(field, BooleanField):
return u'✓' if field.data else u'✕'
return escape(field.data)
| # -*- coding: utf-8 -*-
"""Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import (
QuerySelectField, QuerySelectMultipleField, BooleanField)
def data(field):
"""Field data beautifier.
QuerySelectMultipleField
Renders comma-separated data.
QuerySelectField
Renders the selected value.
BooleanField
Renders '✓' or '✕'
Example:
.. sourcecode:: html+jinja
<dd>{{ field | data }}</dd>
"""
if isinstance(field, QuerySelectMultipleField):
if field.data:
return escape(
u', '.join(field.get_label(data) for data in field.data))
elif isinstance(field, QuerySelectField):
if field.data:
return escape(field.get_label(field.data))
elif isinstance(field, BooleanField):
return u'✓' if field.data else u'✕'
return escape(field.data)
|
Change args change to be optimizable | 'use strict';
var assert = require('assert');
exports = module.exports = promissory;
function promissory(fn) {
assert(typeof fn == 'function', 'function required');
return function() {
var args = new Array(arguments.length);
var ctx = this;
var i;
for (i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new Promise(function(resolve, reject) {
args.push(function promisedWork() {
var args = new Array(arguments.length);
var i;
for (i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
if (args[0]) {
reject(args[0]);
} else if (args.length == 2) {
resolve(args[1]);
} else {
resolve(args.slice(1));
}
});
fn.apply(ctx, args);
});
};
}
| 'use strict';
var assert = require('assert');
exports = module.exports = promissory;
function promissory(fn) {
assert(typeof fn == 'function', 'function required');
return function() {
var args = arrayFrom(arguments);
var ctx = this;
return new Promise(function(resolve, reject) {
args.push(function promisedWork() {
var args = arrayFrom(arguments);
if (args[0]) {
reject(args[0]);
} else if (args.length == 2) {
resolve(args[1]);
} else {
resolve(args.slice(1));
}
});
fn.apply(ctx, args);
});
};
}
function arrayFrom(oldArgs) {
var args = new Array(oldArgs.length);
var i;
for (i = 0; i < args.length; i++) {
args[i] = oldArgs[i];
}
return args;
}
|
Move returning promise up to test if it resolves messaging issue | const { exec } = require('child_process');
const EventEmitter = require('events');
class Execute extends EventEmitter {
constructor(options) {
super();
let { fullCmd, params } = options;
this.fullCmd = fullCmd;
this.params = params;
}
run() {
RunCmd(BuildCmd(this.fullCmd, this.params))
.then((msg) => {
this.emit('end', msg);
})
.catch((error) => {
this.emit('error', error)
});
}
static run(fullCmd) {
return new Promise((resolve, reject) => {
exec(fullCmd, (error, stdout, stderr) => {
if (stderr || error) {
reject(stderr || error);
}
resolve(stdout);
});
});
}
static cmd(base, params) {
return BuildCmd(base, params);
}
}
module.exports = Execute;
function RunCmd(fullCmd) {
return new Promise((resolve, reject) => {
exec(fullCmd, (error, stdout, stderr) => {
if (stderr || error) {
reject(stderr || error);
}
resolve(stdout);
});
});
}
function BuildCmd(base, params) {
if (!params && base) {
return base;
}
if (params.constructor !== Array) {
throw new Error('params must be an Array');
}
return base + ' ' + params.join(' ');
}
| const { exec } = require('child_process');
const EventEmitter = require('events');
class Execute extends EventEmitter {
constructor(options) {
super();
let { fullCmd, params } = options;
this.fullCmd = fullCmd;
this.params = params;
}
run() {
RunCmd(BuildCmd(this.fullCmd, this.params))
.then((msg) => {
this.emit('end', msg);
})
.catch((error) => {
this.emit('error', error)
});
}
static run(fullCmd) {
return RunCmd(fullCmd);
}
static cmd(base, params) {
return BuildCmd(base, params);
}
}
module.exports = Execute;
function RunCmd(fullCmd) {
return new Promise((resolve, reject) => {
exec(fullCmd, (error, stdout, stderr) => {
if (stderr || error) {
reject(stderr || error);
}
resolve(stdout);
});
});
}
function BuildCmd(base, params) {
if (!params && base) {
return base;
}
if (params.constructor !== Array) {
throw new Error('params must be an Array');
}
return base + ' ' + params.join(' ');
}
|
Add support for ... (`Ellipsis`).
Note that it is still considered an operator, so stuff like `a ... b` means "call ... with a and b". | import builtins
import operator
import functools
import importlib
# Choose a function based on the number of arguments.
varary = lambda *fs: lambda *xs: fs[len(xs) - 1](*xs)
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, *xs: f(*xs)
, ',': lambda a, *xs: (a,) + xs
, '<': operator.lt
, '<=': operator.le
, '==': operator.eq
, '!=': operator.ne
, '>': operator.gt
, '>=': operator.ge
, 'is': operator.is_
, 'in': lambda a, b: a in b
, 'not': operator.not_
, '~': operator.invert
, '+': varary(operator.pos, operator.add)
, '-': varary(operator.neg, operator.sub)
, '*': operator.mul
, '**': operator.pow
, '/': operator.truediv
, '//': operator.floordiv
, '%': operator.mod
, '!!': operator.getitem
, '&': operator.and_
, '^': operator.xor
, '|': operator.or_
, '<<': operator.lshift
, '>>': operator.rshift
# Useful stuff.
, 'import': importlib.import_module
, 'foldl': functools.reduce
, '~:': functools.partial
, '...': Ellipsis
})
| import builtins
import operator
import functools
import importlib
# Choose a function based on the number of arguments.
varary = lambda *fs: lambda *xs: fs[len(xs) - 1](*xs)
builtins.__dict__.update({
# Runtime counterparts of some stuff in `Compiler.builtins`.
'$': lambda f, *xs: f(*xs)
, ':': lambda f, *xs: f(*xs)
, ',': lambda a, *xs: (a,) + xs
, '<': operator.lt
, '<=': operator.le
, '==': operator.eq
, '!=': operator.ne
, '>': operator.gt
, '>=': operator.ge
, 'is': operator.is_
, 'in': lambda a, b: a in b
, 'not': operator.not_
, '~': operator.invert
, '+': varary(operator.pos, operator.add)
, '-': varary(operator.neg, operator.sub)
, '*': operator.mul
, '**': operator.pow
, '/': operator.truediv
, '//': operator.floordiv
, '%': operator.mod
, '!!': operator.getitem
, '&': operator.and_
, '^': operator.xor
, '|': operator.or_
, '<<': operator.lshift
, '>>': operator.rshift
# Useful stuff.
, 'import': importlib.import_module
, 'foldl': functools.reduce
, '~:': functools.partial
})
|
Fix issue with CJ query | package fr.insee.rmes.api.codes.cj;
import fr.insee.rmes.api.Configuration;
public class CJQueries {
public static String getCategorieJuridiqueNiveauIII(String code) {
return "SELECT ?uri ?intitule WHERE { \n"
+ "?uri skos:notation '" + code + "' . \n"
+ "?lastCJThirdLevel skos:member ?uri . \n"
+ "?uri skos:prefLabel ?intitule \n"
+ "FILTER (lang(?intitule) = 'fr') \n"
+ "{ \n"
+ "SELECT ?lastCJThirdLevel WHERE { \n"
+ "?lastCJThirdLevel xkos:organizedBy <" + Configuration.BASE_HOST + "/concepts/cj/cjNiveauIII> . \n"
+ "BIND(STRBEFORE(STRAFTER(STR(?lastCJThirdLevel), '" + Configuration.BASE_HOST + "/codes/cj/cj'), '/niveauIII') AS ?lastCJVersion) \n"
+ "BIND(xsd:float(?lastCJVersion) AS ?lastCJVersionFloat)"
+ "} \n"
+ "ORDER BY DESC (?lastCJVersionFloat) \n"
+ "LIMIT 1 \n"
+ "} \n"
+ "}";
}
}
| package fr.insee.rmes.api.codes.cj;
import fr.insee.rmes.api.Configuration;
public class CJQueries {
public static String getCategorieJuridiqueNiveauIII(String code) {
return "SELECT ?uri ?intitule WHERE { \n"
+ "?uri skos:notation '" + code + "' . \n"
+ "?lastCJThirdLevel skos:member ?uri . \n"
+ "?uri skos:prefLabel ?intitule \n"
+ "FILTER (lang(?intitule) = 'fr') \n"
+ "{ \n"
+ "SELECT ?lastCJThirdLevel WHERE { \n"
+ "?lastCJThirdLevel xkos:organizedBy <" + Configuration.BASE_HOST + "/concepts/cj/cjNiveauIII> . \n"
+ "BIND(STRBEFORE(STRAFTER(STR(?lastThirdLevel ), '" + Configuration.BASE_HOST + "/codes/cj/cj'), '/niveauIII') AS ?lastCJVersion) \n"
+ "BIND(xsd:float(?lastCJVersion) AS ?lastCJVersionFloat)"
+ "} \n"
+ "ORDER BY DESC (?lastCJVersionFloat) \n"
+ "LIMIT 1 \n"
+ "} \n"
+ "}";
}
}
|
Use helper not facade because facade calls the wrong factory | <?php
/**
* Class VpageController
*/
namespace Delatbabel\ViewPages\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;
/**
* Class VpageController
*
* Handles requests for application pages.
*/
class VpageController extends BaseController
{
/**
* Make and return a view relating to the current URL.
*
* This is an example controller that can be used or copied or extended in your applications
* to provide CMS-like functionality. It returns the view based on the URL in the
* current request.
*
* ### Example
*
* <code>
* // If request contains the URL 1/2/3 then this will return the view with the URL 1/2/3
* return $this->make($request);
* </code>
*
* @return \Illuminate\Contracts\View\View
*/
public function make(Request $request)
{
$url = $request->path();
if ($url == '/') {
$url = 'index';
}
# Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' .
# 'Make page for URL ' . $url);
return view($url);
// return View::make($url);
}
}
| <?php
/**
* Class VpageController
*/
namespace Delatbabel\ViewPages\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;
/**
* Class VpageController
*
* Handles requests for application pages.
*/
class VpageController extends BaseController
{
/**
* Make and return a view relating to the current URL.
*
* This is an example controller that can be used or copied or extended in your applications
* to provide CMS-like functionality. It returns the view based on the URL in the
* current request.
*
* ### Example
*
* <code>
* // If request contains the URL 1/2/3 then this will return the view with the URL 1/2/3
* return $this->make($request);
* </code>
*
* @return \Illuminate\Contracts\View\View
*/
public function make(Request $request)
{
$url = $request->path();
if ($url == '/') {
$url = 'index';
}
# Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' .
# 'Make page for URL ' . $url);
return View::make($url);
}
}
|
Refactor mocked DOB to constants | package com.springapp.batch;
import com.springapp.batch.bo.BookEntry;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CompareEntryTest {
public static final String BILL_DOB = "1970-01-08T12:30:49+05:30";
public static final String PAUL_DOB = "1970-01-09T15:30:49+05:30";
@Test
public void testJob() throws Exception {
BookEntry bill = mock(BookEntry.class);
BookEntry paul = mock(BookEntry.class);
when(bill.getDateOfBirth()).thenReturn(DateTime.parse(BILL_DOB));
when(paul.getDateOfBirth()).thenReturn(DateTime.parse(PAUL_DOB));
Assert.assertEquals(1, bill.compareTo(paul));
}
}
| package com.springapp.batch;
import com.springapp.batch.bo.BookEntry;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CompareEntryTest {
@Test
public void testJob() throws Exception {
BookEntry bill = mock(BookEntry.class);
BookEntry paul = mock(BookEntry.class);
when(bill.getDateOfBirth()).thenReturn(DateTime.parse("1970-01-08T12:30:49+05:30"));
when(paul.getDateOfBirth()).thenReturn(DateTime.parse("1970-01-09T15:30:49+05:30"));
Assert.assertEquals(1, bill.compareTo(paul));
}
}
|
Add proper banner to dev launch script | #!/usr/bin/env python
"""
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Magical Everything System
Glasnost Image Board and Boredom Inhibitor
"""
from kremlin import app
def main():
print "Kremlin Magical Everything System v 0.0.0-None"
print "Copyright (c) Glasnost 2010-2011"
print "-----------------------------------------------"
print "RUNNING IN DEVELOPMENT MODE! ** NOT FOR PRODUCTION **"
print "Connect to http://127.0.0.1:5000 to access."
app.run(debug=True)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Magical Everything System
Glasnost Image Board and Boredom Inhibitor
"""
from kremlin import app
def main():
print "Launching kremlin in development mode."
print "--------------------------------------"
app.run(debug=True)
if __name__ == '__main__':
main()
|
Change test name for the _reinit() method. | from nose.tools import assert_true, assert_false, assert_equal
from ..base import BaseEstimator
class MyEstimator(BaseEstimator):
def __init__(self, l1=0):
self.l1 = l1
def test_reinit():
"""Tests that BaseEstimator._new() creates a correct deep copy.
We create an estimator, make a copy of its original state
(which, in this case, is the current state of the setimator),
and check that the obtained copy is a correct deep copy.
"""
from scikits.learn.feature_selection import SelectFpr, f_classif
selector = SelectFpr(f_classif, alpha=0.1)
new_selector = selector._reinit()
assert_true(selector is not new_selector)
assert_equal(selector._get_params(), new_selector._get_params())
def test_reinit_2():
"""Tests that BaseEstimator._new() doesn't copy everything.
We first create an estimator, give it an own attribute, and
make a copy of its original state. Then we check that the copy doesn't have
the specific attribute we manually added to the initial estimator.
"""
from scikits.learn.feature_selection import SelectFpr, f_classif
selector = SelectFpr(f_classif, alpha=0.1)
selector.own_attribute = "test"
new_selector = selector._reinit()
assert_false(hasattr(new_selector, "own_attribute"))
def test_repr():
""" Smoke test the repr of the
"""
my_estimator = MyEstimator()
repr(my_estimator)
| from nose.tools import assert_true, assert_false, assert_equal
from ..base import BaseEstimator
class MyEstimator(BaseEstimator):
def __init__(self, l1=0):
self.l1 = l1
def test_renew():
"""Tests that BaseEstimator._new() creates a correct deep copy.
We create an estimator, make a copy of its original state
(which, in this case, is the current state of the setimator),
and check that the obtained copy is a correct deep copy.
"""
from scikits.learn.feature_selection import SelectFpr, f_classif
selector = SelectFpr(f_classif, alpha=0.1)
new_selector = selector._reinit()
assert_true(selector is not new_selector)
assert_equal(selector._get_params(), new_selector._get_params())
def test_renew_2():
"""Tests that BaseEstimator._new() doesn't copy everything.
We first create an estimator, give it an own attribute, and
make a copy of its original state. Then we check that the copy doesn't have
the specific attribute we manually added to the initial estimator.
"""
from scikits.learn.feature_selection import SelectFpr, f_classif
selector = SelectFpr(f_classif, alpha=0.1)
selector.own_attribute = "test"
new_selector = selector._reinit()
assert_false(hasattr(new_selector, "own_attribute"))
def test_repr():
""" Smoke test the repr of the
"""
my_estimator = MyEstimator()
repr(my_estimator)
|
Fix mark home page active | <?php
namespace Rudolf\Modules\index;
class IndexController extends \Rudolf\Modules\_front\Controller {
public function index($page) {
$page = $this->firstPageRedirect($page);
$model = new IndexModel();
$view = new IndexView();
$module = new \Rudolf\Modules\Module('index');
$config = $module->getConfig();
$onPage = $config['on_page'];
$navNumber = $config['nav_number'];
$pagination = new \Rudolf\Libs\Pagination($model->getTotalNumber(), $page, $onPage, $navNumber);
$articles = $model->getList($pagination, [$config['sort'], $config['order']]);
if(false === $articles and $page > 1) {
throw new \Rudolf\Http\HttpErrorException('No articles page found (error 404)', 404);
}
$view->setData($articles, $pagination);
$view->setFrontData($this->frontData, '');
$view->render();
}
}
| <?php
namespace Rudolf\Modules\index;
class IndexController extends \Rudolf\Modules\_front\Controller {
public function index($page) {
$page = $this->firstPageRedirect($page);
$model = new IndexModel();
$view = new IndexView();
$module = new \Rudolf\Modules\Module('index');
$config = $module->getConfig();
$onPage = $config['on_page'];
$navNumber = $config['nav_number'];
$pagination = new \Rudolf\Libs\Pagination($model->getTotalNumber(), $page, $onPage, $navNumber);
$articles = $model->getList($pagination, [$config['sort'], $config['order']]);
if(false === $articles and $page > 1) {
throw new \Rudolf\Http\HttpErrorException('No articles page found (error 404)', 404);
}
$view->setData($articles, $pagination);
$view->setFrontData($this->frontData);
$view->render();
}
}
|
Remove fields from method definition. | # -*- coding: utf-8 -*-
# © 2015 iDT LABS (http://www.@idtlabs.sl)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models, api
class HumanResourcesConfiguration(models.TransientModel):
_inherit = 'hr.config.settings'
legal_holidays_status_id = fields.Many2one(
'hr.holidays.status',
'Legal Leave Status',
)
@api.model
def get_legal_holidays_status_id(self):
company = self.env.user.company_id
return {
'legal_holidays_status_id': company.legal_holidays_status_id.id,
}
@api.multi
def set_legal_holidays_status_id(self):
self.ensure_one()
company = self.env.user.company_id
company.legal_holidays_status_id = self.legal_holidays_status_id
| # -*- coding: utf-8 -*-
# © 2015 iDT LABS (http://www.@idtlabs.sl)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models, api
class HumanResourcesConfiguration(models.TransientModel):
_inherit = 'hr.config.settings'
legal_holidays_status_id = fields.Many2one(
'hr.holidays.status',
'Legal Leave Status',
)
@api.model
def get_legal_holidays_status_id(self, fields):
company = self.env.user.company_id
return {
'legal_holidays_status_id': company.legal_holidays_status_id.id,
}
@api.multi
def set_legal_holidays_status_id(self):
self.ensure_one()
company = self.env.user.company_id
company.legal_holidays_status_id = self.legal_holidays_status_id
|
Change structure of facets and defaultFacet within the useCase-groupChat draft | import won from "../../app/service/won.js";
import { complain } from "./uc-complain.js";
import { handleComplaint } from "./uc-handle-complaint.js";
import { customUseCase } from "./uc-custom.js";
import { details, mergeInEmptyDraft } from "../detail-definitions.js";
export const otherGroup = {
identifier: "othergroup",
label: "More...",
icon: undefined,
useCases: {
complain: complain,
handleComplaint: handleComplaint,
customUseCase: customUseCase,
groupChat: {
identifier: "groupChat",
label: "New Groupchat Post",
draft: {
...mergeInEmptyDraft({
content: {
facets: {
"#groupFacet": won.WON.GroupFacet,
"#holdableFacet": won.WON.HoldableFacet,
},
defaultFacet: { "#groupFacet": won.WON.GroupFacet },
},
}),
},
details: details,
seeksDetails: details,
},
},
};
| import won from "../../app/service/won.js";
import { complain } from "./uc-complain.js";
import { handleComplaint } from "./uc-handle-complaint.js";
import { customUseCase } from "./uc-custom.js";
import { details, mergeInEmptyDraft } from "../detail-definitions.js";
export const otherGroup = {
identifier: "othergroup",
label: "More...",
icon: undefined,
useCases: {
complain: complain,
handleComplaint: handleComplaint,
customUseCase: customUseCase,
groupChat: {
identifier: "groupChat",
label: "New Groupchat Post",
draft: {
...mergeInEmptyDraft({
content: {
facets: [
{ "@id": "#groupFacet", "@type": won.WON.GroupFacet },
{ "@id": "#holdableFacet", "@type": won.WON.HoldableFacet },
],
defaultFacet: { "@id": "#groupFacet", "@type": won.WON.GroupFacet },
},
}),
},
details: details,
seeksDetails: details,
},
},
};
|
Fix test file after an update to the test cases. | 'use strict';
var lint = require('./_lint');
//////////////////////////////
// SCSS syntax tests
//////////////////////////////
describe('no trailing zero - scss', function () {
var file = lint.file('no-trailing-zero.scss');
it('enforce', function (done) {
lint.test(file, {
'trailing-zero': 1
}, function (data) {
lint.assert.equal(8, data.warningCount);
done();
});
});
});
//////////////////////////////
// Sass syntax tests
//////////////////////////////
describe('no trailing zero - sass', function () {
var file = lint.file('no-trailing-zero.sass');
it('enforce', function (done) {
lint.test(file, {
'trailing-zero': 1
}, function (data) {
lint.assert.equal(8, data.warningCount);
done();
});
});
});
| 'use strict';
var lint = require('./_lint');
//////////////////////////////
// SCSS syntax tests
//////////////////////////////
describe('no trailing zero - scss', function () {
var file = lint.file('no-trailing-zero.scss');
it('enforce', function (done) {
lint.test(file, {
'trailing-zero': 1
}, function (data) {
lint.assert.equal(6, data.warningCount);
done();
});
});
});
//////////////////////////////
// Sass syntax tests
//////////////////////////////
describe('no trailing zero - sass', function () {
var file = lint.file('no-trailing-zero.sass');
it('enforce', function (done) {
lint.test(file, {
'trailing-zero': 1
}, function (data) {
lint.assert.equal(6, data.warningCount);
done();
});
});
});
|
Make TestPPrintSimple easier to extend | // Copyright 2015 Jean Niklas L'orange. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package edn
import (
"bytes"
"testing"
)
func TestPPrint(t *testing.T) {
inputs := map[string]string{
"{}": "{}",
"[]": "[]",
"{:a 42}": "{:a 42}",
"{:a 1 :b 2}": "{:a 1,\n :b 2}",
}
for input, expected := range inputs {
buff := bytes.NewBuffer(nil)
if err := PPrint(buff, []byte(input), &PPrintOpts{}); err != nil {
t.Errorf(`PPrint(%q) failed, but expected success: %v`, input, err)
}
output := string(buff.Bytes())
if output != expected {
t.Errorf(`Expected PPrint(%q) to be %q; was %q`, input, expected, output)
}
}
}
| // Copyright 2015 Jean Niklas L'orange. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package edn
import (
"bytes"
"testing"
)
func TestPPrintSimple(t *testing.T) {
inputs := []string{
"{}",
"[]",
"{:a 42}",
}
for _, input := range inputs {
buff := bytes.NewBuffer(nil)
if err := PPrint(buff, []byte(input), &PPrintOpts{}); err != nil {
t.Errorf(`PPrint("%s") failed, but expected success: %v`, input, err)
}
output := string(buff.Bytes())
if output != input {
t.Errorf(`Expected PPrint("%s") to be "%s"; was "%s"`, input, input, output)
}
}
}
|
ScreengroupClients: Set SG to 0 on detach | <?php
namespace App\Api\V1\Controllers;
use Gate;
use Activity;
use App\Models\ScreenGroup;
use App\Models\Client;
class ScreenGroupClientController extends BaseController
{
public function destroy(ScreenGroup $screengroup, Client $client) {
if (Gate::denies('edit_screengroup'))
$this->response->error('permission_denied: edit_screengroup', 401);
$client->update(['screen_group_id' => 0]);
$client->save();
Activity::log([
'contentId' => $screengroup->id,
'contentType' => 'ScreenGroupClient',
'action' => 'Detach',
'description' => 'Detached Client from ScreenGroup',
'details' => $screengroup->clients->toJson(),
]);
return $this->response->noContent();
}
}
| <?php
namespace App\Api\V1\Controllers;
use Gate;
use Activity;
use App\Models\ScreenGroup;
use App\Models\Client;
class ScreenGroupClientController extends BaseController
{
public function destroy(ScreenGroup $screengroup, Client $client) {
if (Gate::denies('edit_screengroup'))
$this->response->error('permission_denied: edit_screengroup', 401);
$client->update(['screen_group_id' => 1]);
$client->save();
Activity::log([
'contentId' => $screengroup->id,
'contentType' => 'ScreenGroupClient',
'action' => 'Detach',
'description' => 'Detached Client from ScreenGroup',
'details' => $screengroup->clients->toJson(),
]);
return $this->response->noContent();
}
}
|
Use curly brackets (PSR-2) + phpdoc short type name | <?php
/**
* @title Useful class for managing the system modules.
*
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2016-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Module
*/
namespace PH7\Framework\Module;
defined('PH7') or exit('Restricted access');
use PH7\Framework\Mvc\Model\Module;
class Various
{
/**
* @param string $sModFolderName Name of the module folder.
*
* @return bool
*/
public static function isEnabled($sModFolderName)
{
$oMods = (new Module)->get($sModFolderName);
// If the module is not in the SysModsEnabled table, return always TRUE
if (!isset($oMods->enabled)) {
return true;
}
return (((int)$oMods->enabled) === 1);
}
}
| <?php
/**
* @title Useful class for managing the system modules.
*
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2016-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Module
*/
namespace PH7\Framework\Module;
defined('PH7') or exit('Restricted access');
use PH7\Framework\Mvc\Model\Module;
class Various
{
/**
* @param string $sModFolderName Name of the module folder.
* @return boolean
*/
public static function isEnabled($sModFolderName)
{
$oMods = (new Module)->get($sModFolderName);
// If the module is not in the SysModsEnabled table, return always TRUE
if (!isset($oMods->enabled)) return true;
return (((int)$oMods->enabled) === 1);
}
}
|
Add newline and request to play again to confirm box | function Game(){
this.$track = $('#racetrack');
this.finishLine = this.$track.width() - 54;
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 20;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
function checkWinner(player, game){
if( player.position > game.finishLine ){
window.confirm("Player " + player.player.id + " has won!" + "\n Play Again?");
}
}
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); | function Game(){
this.$track = $('#racetrack');
this.finishLine = this.$track.width() - 54;
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 20;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
function checkWinner(player, game){
if( player.position > game.finishLine ){
alert("Player " + player.player.id + " has won!");
}
}
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); |
Include URL and response body on HTTP failure
It's quite awkward to diagnose exceptions caused by HTTP errors when you
don't have the URL and response body, so this should help. | import datetime
import logging
import pytz
import requests
import json
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
if obj.tzinfo is None:
obj = obj.replace(tzinfo=pytz.UTC)
return obj.isoformat()
return json.JSONEncoder.default(self, obj)
class Bucket(object):
"""Client for writing to a backdrop bucket"""
def __init__(self, url, token):
self.url = url
self.token = token
def post(self, records):
headers = {
"Authorization": "Bearer %s" % self.token,
"Content-type": "application/json"
}
response = requests.post(
url=self.url,
headers=headers,
data=json.dumps(records, cls=JsonEncoder)
)
try:
response.raise_for_status()
except:
logging.error('[Backdrop: {}]\n{}'.format(self.url, response.text))
raise
logging.debug("[Backdrop] " + response.text)
| import datetime
import logging
import pytz
import requests
import json
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
if obj.tzinfo is None:
obj = obj.replace(tzinfo=pytz.UTC)
return obj.isoformat()
return json.JSONEncoder.default(self, obj)
class Bucket(object):
"""Client for writing to a backdrop bucket"""
def __init__(self, url, token):
self.url = url
self.token = token
def post(self, records):
headers = {
"Authorization": "Bearer %s" % self.token,
"Content-type": "application/json"
}
response = requests.post(
url=self.url,
headers=headers,
data=json.dumps(records, cls=JsonEncoder)
)
logging.debug("[Backdrop] " + response.text)
response.raise_for_status()
|
Add JavaScript minification to the build task. | module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
build: {
src: "build"
}
},
copy: {
build: {
files: [
{
expand: true,
cwd: 'source/',
src: ['pixadee.js'],
dest: 'build/'
}
]
}
},
uglify: {
build: {
files: {
'build/pixadee.min.js': ['source/pixadee.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('build', ['clean', 'copy', 'uglify']);
grunt.registerTask('default', ['build']);
}; | module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
build: {
src: "build"
}
},
copy: {
build: {
files: [
{
expand: true,
cwd: 'source/',
src: ['pixadee.js'],
dest: 'build/'
}
]
}
},
uglify: {
build: {
files: {
'build/pixadee.min.js': ['source/pixadee.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('build', ['clean', 'copy']);
grunt.registerTask('default', ['build']);
}; |
Add underscore.js to test require | // Karma configuration
//
// For all available config options and default values, see:
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function (config) {
'use strict';
config.set({
autoWatch: true,
basePath: '',
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
captureTimeout: 5000,
exclude: [
'app/js/main.js'
],
files: [
// loaded without require
'app/bower_components/jquery/dist/jquery.js',
'app/bower_components/underscore/underscore.js',
'app/bower_components/jasmine-jquery/lib/jasmine-jquery.js',
'app/bower_components/jasmine-flight/lib/jasmine-flight.js',
// loaded with require
{pattern: 'app/bower_components/flight/**/*.js', included: false},
{pattern: 'app/js/**/*.js', included: false},
{pattern: 'test/spec/**/*.spec.js', included: false},
// test config
'test/test-main.js'
],
frameworks: [
'jasmine',
'requirejs'
],
reporters: [process.env.TRAVIS ? 'dots' : 'progress'],
reportSlowerThan: 500,
singleRun: false
});
};
| // Karma configuration
//
// For all available config options and default values, see:
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function (config) {
'use strict';
config.set({
autoWatch: true,
basePath: '',
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
captureTimeout: 5000,
exclude: [
'app/js/main.js'
],
files: [
// loaded without require
'app/bower_components/jquery/dist/jquery.js',
'app/bower_components/jasmine-jquery/lib/jasmine-jquery.js',
'app/bower_components/jasmine-flight/lib/jasmine-flight.js',
// loaded with require
{pattern: 'app/bower_components/flight/**/*.js', included: false},
{pattern: 'app/js/**/*.js', included: false},
{pattern: 'test/spec/**/*.spec.js', included: false},
// test config
'test/test-main.js'
],
frameworks: [
'jasmine',
'requirejs'
],
reporters: [process.env.TRAVIS ? 'dots' : 'progress'],
reportSlowerThan: 500,
singleRun: false
});
};
|
Add an aria-label attr to our input control for better accessibility. | import React from 'react';
import PropTypes from 'prop-types';
import Input from 'react-toolbox/lib/input/Input';
const sectionStyle = {
marginLeft: "2.5rem",
marginRight: "2.5rem",
}
const SearchForm = (props) => (
<section style={sectionStyle}>
<form onSubmit={props.handleSubmit}>
<Input
type='text'
aria-label='Search'
label='Search by City'
value={props.city}
onChange={props.handleInputChange}
maxLength={200} />
</form>
</section>
);
export default SearchForm;
SearchForm.propTypes = {
city: PropTypes.string.isRequired,
handleSubmit: PropTypes.func.isRequired,
handleInputChange: PropTypes.func.isRequired
}
| import React from 'react';
import PropTypes from 'prop-types';
import Input from 'react-toolbox/lib/input/Input';
const sectionStyle = {
marginLeft: "2.5rem",
marginRight: "2.5rem",
}
const SearchForm = (props) => (
<section style={sectionStyle}>
<form onSubmit={props.handleSubmit}>
<Input
type='text'
label='Search by City'
value={props.city}
onChange={props.handleInputChange}
maxLength={200} />
</form>
</section>
);
export default SearchForm;
SearchForm.propTypes = {
city: PropTypes.string.isRequired,
handleSubmit: PropTypes.func.isRequired,
handleInputChange: PropTypes.func.isRequired
}
|
pyroTorrent: Fix encoding on error page. | import traceback
import sys
class SessionHackException(Exception):
"""
Raised when something goes wrong.
"""
class SessionHack(object):
"""
The SessionHack middleware is used to catch any exceptions that occur;
this makes debugging easier. Typically debugging can be painful because
the trace and error is only shown in the web page.
"""
def __init__(self, app, render_call):
self.app = app
self.render_call = render_call
def __call__(self, env, start_response):
error = False
try:
ret = self.app(env, start_response)
except Exception, e:
print 'Exception in SessionHack:', e.message
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
ret = self.render_call(env, str(e))
#raise SessionHackException(e.message)
error = True
finally:
pass
if error:
start_response('200 OK', [('Content-Type', 'text/html;charset=utf8')])
return ret
| import traceback
import sys
class SessionHackException(Exception):
"""
Raised when something goes wrong.
"""
class SessionHack(object):
"""
The SessionHack middleware is used to catch any exceptions that occur;
this makes debugging easier. Typically debugging can be painful because
the trace and error is only shown in the web page.
"""
def __init__(self, app, render_call):
self.app = app
self.render_call = render_call
def __call__(self, env, start_response):
error = False
try:
ret = self.app(env, start_response)
except Exception, e:
print 'Exception in SessionHack:', e.message
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
ret = self.render_call(env, str(e))
#raise SessionHackException(e.message)
error = True
finally:
pass
if error:
start_response('200 OK', [('Content-Type', 'text/html')])
return ret
|
Add a custom hashCode and equals for performance. | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.wire;
/**
* Created by peter on 16/03/16.
*/
public abstract class AbstractMarshallable implements Marshallable {
@Override
public boolean equals(Object o) {
return Marshallable.$equals(this, o);
}
@Override
public int hashCode() {
return Marshallable.$hashCode(this);
}
@Override
public String toString() {
return Marshallable.$toString(this);
}
}
| /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.wire;
/**
* Created by peter on 16/03/16.
*/
public abstract class AbstractMarshallable implements Marshallable {
@Override
public boolean equals(Object o) {
return Marshallable.$equals(this, o);
}
@Override
public int hashCode() {
assert false;
return Marshallable.$hashCode(this);
}
@Override
public String toString() {
return Marshallable.$toString(this);
}
}
|
Make some vars lets for strictness purposes. | "use strict";
var expect = require('chai').expect;
var parse = require('../src/commands/parse');
describe('YAML-to-commands parser', () => {
let filename = 'test/test.usher.yml';
let result = parse(filename);
let tests = [
{
key: 'basic',
expected: 'docker build -t usher .'
},
{
key: 'custom',
expected: 'do thing'
},
{
key: 'sequence',
expected: [
'docker build -t usher .',
'do thing'
]
},
{
key: 'bogus',
expected: false
},
{
key: 'null',
expected: false
}
];
tests.forEach( test =>
it(`should make command ${test.key} ==> ${test.expected}`, () =>
expect(result[test.key]).to.deep.equal(test.expected)));
});
| var expect = require('chai').expect;
var parse = require('../src/commands/parse');
describe('YAML-to-commands parser', () => {
var filename = 'test/test.usher.yml';
var result = parse(filename);
var tests = [
{
key: 'basic',
expected: 'docker build -t usher .'
},
{
key: 'custom',
expected: 'do thing'
},
{
key: 'sequence',
expected: [
'docker build -t usher .',
'do thing'
]
},
{
key: 'bogus',
expected: false
},
{
key: 'null',
expected: false
}
];
tests.forEach( test =>
it(`should make command ${test.key} ==> ${test.expected}`, () =>
expect(result[test.key]).to.deep.equal(test.expected)));
});
|
Adjust history capability for "Dark Legacy" | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Dark Legacy"
language = "en"
url = "http://www.darklegacycomics.com/"
start_date = "2006-01-01"
rights = "Arad Kedar"
class Crawler(CrawlerBase):
history_capable_days = 33 * 7 # 33 weekly releases
schedule = "Su"
time_zone = "US/Pacific"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.darklegacycomics.com/feed.xml")
for entry in feed.for_date(pub_date):
title = entry.title
page = self.parse_page(entry.link)
url = page.src("img.comic-image")
return CrawlerImage(url, title)
| from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Dark Legacy"
language = "en"
url = "http://www.darklegacycomics.com/"
start_date = "2006-01-01"
rights = "Arad Kedar"
class Crawler(CrawlerBase):
history_capable_days = 29 * 7 # 7 weekly releases
schedule = "Su"
time_zone = "US/Pacific"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.darklegacycomics.com/feed.xml")
for entry in feed.for_date(pub_date):
title = entry.title
page = self.parse_page(entry.link)
url = page.src("img.comic-image")
return CrawlerImage(url, title)
|
Move check for week number out into function. | from datetime import date as vanilla_date, timedelta
from overflow import OverflowDate
def _check_week(week):
if week < 1 or week > 54:
raise ValueError(
"Week number %d is invalid for an ISO calendar."
% (week, )
)
def iso_to_gregorian(year, week, weekday):
_check_week(week)
jan_8 = vanilla_date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
try:
d = vanilla_date(year, 1, 8) + timedelta(days=offset)
except:
d = OverflowDate(isocalendar=(year, week, weekday))
if d.isocalendar()[0] != year:
raise ValueError(
"Week number %d is invalid for ISO year %d."
% (week, year)
)
return d
| from datetime import date as vanilla_date, timedelta
from overflow import OverflowDate
def iso_to_gregorian(year, week, weekday):
if week < 1 or week > 54:
raise ValueError(
"Week number %d is invalid for an ISO calendar."
% (week, )
)
jan_8 = vanilla_date(year, 1, 8).isocalendar()
offset = (week - jan_8[1]) * 7 + (weekday - jan_8[2])
try:
d = vanilla_date(year, 1, 8) + timedelta(days=offset)
except:
d = OverflowDate(isocalendar=(year, week, weekday))
if d.isocalendar()[0] != year:
raise ValueError(
"Week number %d is invalid for ISO year %d."
% (week, year)
)
return d
|
Fix indentation according to coding standards | <?php
/**
* This file is part of the hyyan/woo-poly-integration plugin.
* (c) Hyyan Abo Fakher <hyyanaf@gmail.com>.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Hyyan\WPI;
/**
* Ajax.
*
* Handle Ajax
*
* @author Marian Kadanka <marian.kadanka@gmail.com>
*/
class Ajax {
/**
* Construct object.
*/
public function __construct() {
add_filter( 'pll_home_url_white_list', array( $this, 'pll_home_url_white_list' ) );
}
/**
* Add WooCommerce class-wc-ajax.php to the Polylang home_url white list
*
* @param array $white_list Polylang home_url white list
*
* @return array filtered white list
*/
public function pll_home_url_white_list( $white_list ) {
$white_list[] = array( 'file' => 'class-wc-ajax.php' );
return $white_list;
}
}
| <?php
/**
* This file is part of the hyyan/woo-poly-integration plugin.
* (c) Hyyan Abo Fakher <hyyanaf@gmail.com>.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Hyyan\WPI;
/**
* Ajax.
*
* Handle Ajax
*
* @author Marian Kadanka <marian.kadanka@gmail.com>
*/
class Ajax {
/**
* Construct object.
*/
public function __construct() {
add_filter( 'pll_home_url_white_list', array( $this, 'pll_home_url_white_list' ) );
}
/**
* Add WooCommerce class-wc-ajax.php to the Polylang home_url white list
*
* @param array $white_list Polylang home_url white list
*
* @return array filtered white list
*/
public function pll_home_url_white_list( $white_list ) {
$white_list[] = array( 'file' => 'class-wc-ajax.php' );
return $white_list;
}
}
|
Cover unknown time format case | import pytest
from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
def test_unknown(self):
with pytest.raises(RuntimeError):
time_convert("5u")
class TestGrouper(object):
def test_simple_seq(self):
seq = range(0, 10)
result = list(grouper(2, seq))
assert len(result) == 5
def test_odd_seq(self):
seq = range(0, 10)
result = list(grouper(3, seq))
assert len(result) == 4
assert result[-1] == (9, None, None)
| from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(object):
def test_simple_seq(self):
seq = range(0, 10)
result = list(grouper(2, seq))
assert len(result) == 5
def test_odd_seq(self):
seq = range(0, 10)
result = list(grouper(3, seq))
assert len(result) == 4
assert result[-1] == (9, None, None)
|
Make ReusableMessageGroup broadcast the notify_about_to_send_message to all limiters | from bot.logger.message_sender.message_builder import MessageBuilder
from bot.logger.message_sender.reusable.limiter import ReusableMessageLimiter
class ReusableMessageLimiterGroup(ReusableMessageLimiter):
def __init__(self, *limiters: ReusableMessageLimiter):
self.limiters = limiters
def should_issue_new_message_pre_add(self, new_text):
return self.__any_limiter(lambda limiter: limiter.should_issue_new_message_pre_add(new_text))
def should_issue_new_message_post_add(self, builder: MessageBuilder):
return self.__any_limiter(lambda limiter: limiter.should_issue_new_message_post_add(builder))
def __any_limiter(self, func: callable):
return any((func(limiter) for limiter in self.limiters))
def notify_new_message_issued(self):
for limiter in self.limiters:
limiter.notify_new_message_issued()
def notify_about_to_send_message(self):
for limiter in self.limiters:
limiter.notify_about_to_send_message()
| from bot.logger.message_sender.message_builder import MessageBuilder
from bot.logger.message_sender.reusable.limiter import ReusableMessageLimiter
class ReusableMessageLimiterGroup(ReusableMessageLimiter):
def __init__(self, *limiters: ReusableMessageLimiter):
self.limiters = limiters
def should_issue_new_message_pre_add(self, new_text):
return self.__any_limiter(lambda limiter: limiter.should_issue_new_message_pre_add(new_text))
def should_issue_new_message_post_add(self, builder: MessageBuilder):
return self.__any_limiter(lambda limiter: limiter.should_issue_new_message_post_add(builder))
def __any_limiter(self, func: callable):
return any((func(limiter) for limiter in self.limiters))
def notify_new_message_issued(self):
for limiter in self.limiters:
limiter.notify_new_message_issued()
|
Fix 691 - HTML not getting decoded properly by Middleware in Django 2.2 | from __future__ import unicode_literals
from django.core.exceptions import MiddlewareNotUsed
from django.utils.encoding import DjangoUnicodeDecodeError
from django.utils.html import strip_spaces_between_tags as minify_html
from pipeline.conf import settings
from django.utils.deprecation import MiddlewareMixin
class MinifyHTMLMiddleware(MiddlewareMixin):
def __init__(self, *args, **kwargs):
super(MinifyHTMLMiddleware, self).__init__(*args, **kwargs)
if not settings.PIPELINE_ENABLED:
raise MiddlewareNotUsed
def process_response(self, request, response):
if response.has_header('Content-Type') and 'text/html' in response['Content-Type']:
try:
response.content = minify_html(response.content.decode().strip())
response['Content-Length'] = str(len(response.content))
except DjangoUnicodeDecodeError:
pass
return response
| from __future__ import unicode_literals
from django.core.exceptions import MiddlewareNotUsed
from django.utils.encoding import DjangoUnicodeDecodeError
from django.utils.html import strip_spaces_between_tags as minify_html
from pipeline.conf import settings
from django.utils.deprecation import MiddlewareMixin
class MinifyHTMLMiddleware(MiddlewareMixin):
def __init__(self, *args, **kwargs):
super(MinifyHTMLMiddleware, self).__init__(*args, **kwargs)
if not settings.PIPELINE_ENABLED:
raise MiddlewareNotUsed
def process_response(self, request, response):
if response.has_header('Content-Type') and 'text/html' in response['Content-Type']:
try:
response.content = minify_html(response.content.strip())
response['Content-Length'] = str(len(response.content))
except DjangoUnicodeDecodeError:
pass
return response
|
Move test.run() into before() phase. | /*global describe, before, it */
'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
describe('yui generator', function () {
var TMP_DIR = path.join(__dirname, 'temp');
var APP_DIR = path.join(__dirname, '../app');
before(function (done) {
yeoman.test
.run(APP_DIR)
.inDir(TMP_DIR)
.onEnd(done);
});
it('creates expected files', function () {
yeoman.assert.file([
'BUILD.md',
'README.md',
'Gruntfile.js',
'bower.json',
'package.json',
'.editorconfig',
'.gitignore',
'.jshintrc',
'.yeti.json'
]);
});
});
| /*global describe, it */
'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
describe('yui generator', function () {
var TMP_DIR = path.join(__dirname, 'temp');
var APP_DIR = path.join(__dirname, '../app');
it('creates expected files', function (done) {
var expected = [
'BUILD.md',
'README.md',
'Gruntfile.js',
'.editorconfig',
'.gitignore',
'.jshintrc',
'.yeti.json'
];
yeoman.test.run(APP_DIR)
.inDir(TMP_DIR)
.onEnd(function () {
yeoman.assert.file(expected);
done();
});
});
});
|
Add CDATASection to eslint globals |
module.exports = {
'extends': 'eslint:recommended',
'rules': {
'indent': ['error', 4, { 'SwitchCase': 1 }],
'space-before-function-paren': ['error', 'never'],
'no-console': ['error', { 'allow': ['warn'] }],
'object-curly-spacing': ['error', 'always', { 'objectsInObjects': false }],
'no-constant-condition': ['off'],
'no-undef': ['error'],
'no-unused-vars': ['error', { 'vars': 'local', 'args': 'none' }],
'quotes': ['error', 'single'],
'semi': ['error', 'always']
},
'env': {
'browser': true,
'node': true
},
'globals': {
'Uint8Array': true,
'CDATASection': true
},
'parserOptions': {
'ecmaVersion': 6,
sourceType: 'module'
}
};
|
module.exports = {
'extends': 'eslint:recommended',
'rules': {
'indent': ['error', 4, { 'SwitchCase': 1 }],
'space-before-function-paren': ['error', 'never'],
'no-console': ['error', { 'allow': ['warn'] }],
'object-curly-spacing': ['error', 'always', { 'objectsInObjects': false }],
'no-constant-condition': ['off'],
'no-undef': ['error'],
'no-unused-vars': ['error', { 'vars': 'local', 'args': 'none' }],
'quotes': ['error', 'single'],
'semi': ['error', 'always']
},
'env': {
'browser': true,
'node': true
},
'globals': {
'Uint8Array': true
},
'parserOptions': {
'ecmaVersion': 6,
sourceType: 'module'
}
};
|
Reorder the loading to make it work | /**
* Server root
*
* Collects all routes and starts the server
*/
require('./evilGlobalVariables');
const glob = require('glob-promise');
const express = require('express');
const { partial } = require('lodash');
const bodyParser = require('body-parser');
const server = express();
/* Setup the application server */
server.use(bodyParser.json());
/* Building blocks */
const findRoutes = partial(glob, './src/routes/**/*.js');
const findMiddlewares = partial(glob, './src/middlewares/**/*.js');
const requireAndIntegrate = function(files, app) {
files.forEach(file => {
const fn = require(file);
if ('function' === typeof fn) fn(app);
});
};
/* Start ✨ */
findMiddlewares()
.then(middlewares => {
requireAndIntegrate(middlewares, server);
return findRoutes();
})
.then(routes => {
requireAndIntegrate(routes, server);
})
.then(function() {
server.listen(3000);
})
.catch(reason => {
console.error('Failed to start the server', reason);
});
| /**
* Server root
*
* Collects all routes and starts the server
*/
require('./evilGlobalVariables');
const glob = require('glob-promise');
const express = require('express');
const { partial } = require('lodash');
const bodyParser = require('body-parser');
const server = express();
/* Setup the application server */
server.use(bodyParser.json());
/* Building blocks */
const findRoutes = partial(glob, './src/routes/**/*.js');
const findMiddlewares = partial(glob, './src/middlewares/**/*.js');
const requireAndIntegrate = function(files, app) {
files.forEach(file => {
const fn = require(file);
if ('function' === typeof fn) fn(app);
});
};
/* Start ✨ */
findRoutes()
.then(routes => {
requireAndIntegrate(routes, server);
return findMiddlewares();
})
.then(middlewares => {
requireAndIntegrate(middlewares, server);
})
.then(function() {
server.listen(3000);
})
.catch(reason => {
console.error('Failed to start the server', reason);
});
|
Save all simulation plots to one PDF instead of multiple | import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("test-results-plots.pdf")
for file in glob.glob("*.csv"):
data = np.genfromtxt(file, delimiter = ',', names = True)
plt.figure(figsize=(10,20))
plt.suptitle(file)
num_plots = len(data.dtype.names)
count = 1
for col_name in data.dtype.names:
plt.subplot(num_plots, 1, count)
plt.plot(data[col_name], label=col_name)
plt.legend()
count += 1
ymin, ymax = plt.ylim()
if ymin < 0 < ymax:
plt.axhline(0, hold=True, color = 'grey') # plot line through zero
pdf.savefig()
mng = plt.get_current_fig_manager()
if plt.get_backend() == 'TkAgg':
mng.window.state('zoomed')
elif plt.get_backend() == 'wxAgg':
mng.frame.Maximize(True)
elif plt.get_backend() == 'QT4Agg':
mng.window.showMaximized()
plt.show()
plt.close()
pdf.close()
| import glob
import csv
import numpy as np
import matplotlib.pyplot as plt
for file in glob.glob("*.csv"):
data = np.genfromtxt(file, delimiter = ',', names = True)
plt.figure(figsize=(10,20))
plt.suptitle(file)
num_plots = len(data.dtype.names)
count = 1
for col_name in data.dtype.names:
plt.subplot(num_plots, 1, count)
plt.plot(data[col_name], label=col_name)
plt.legend()
count += 1
ymin, ymax = plt.ylim()
if ymin < 0 < ymax:
plt.axhline(0, hold=True, color = 'grey') # plot line through zero
mng = plt.get_current_fig_manager()
if plt.get_backend() == 'TkAgg':
mng.window.state('zoomed')
elif plt.get_backend() == 'wxAgg':
mng.frame.Maximize(True)
elif plt.get_backend() == 'QT4Agg':
mng.window.showMaximized()
plt.savefig(file.rstrip('.csv') + '.pdf')
plt.show()
|
:art: Make the app always transparent | const {
app,
BrowserWindow,
ipcMain
} = require('electron')
const { join } = require('path')
let win
app.on('ready', () => {
win = new BrowserWindow({
width:800,
height: 600,
show: false,
frame: false,
transparent: true,
titleBarStyle : 'hidden-inset',
icon: join(__dirname, 'parts', 'icon.png')
})
win.setMenu(null)
win.loadURL(`file://${__dirname}/dist/index.html`)
// Show devtools only if you're in development mode
if(process.env.NODE_ENV == 'development') win.webContents.openDevTools()
})
ipcMain.on('ready', () => {
win.show()
win.focus()
})
ipcMain.on('bootstrap_error', () => {
win.show()
win.webContents.openDevTools()
})
| const {
app,
BrowserWindow,
ipcMain
} = require('electron')
const { platform } = require('os')
const { join } = require('path')
let win
app.on('ready', () => {
win = new BrowserWindow({
width:800,
height: 600,
show: false,
frame: false,
transparent: platform() == 'darwin' ? true : false,
titleBarStyle : 'hidden-inset',
icon: join(__dirname, 'parts', 'icon.png')
})
win.setMenu(null)
win.loadURL(`file://${__dirname}/dist/index.html`)
// Show devtools only if you're in development mode
if(process.env.NODE_ENV == 'development') win.webContents.openDevTools()
})
ipcMain.on('ready', () => {
win.show()
win.focus()
})
ipcMain.on('bootstrap_error', () => {
win.show()
win.webContents.openDevTools()
})
|
Refactor lightweight tags to remove duplication 🐞 | var buildFile = require('./build-file')
var runGitCommand = require('./helpers/run-git-command')
var COMMITHASH_COMMAND = 'rev-parse HEAD'
var VERSION_COMMAND = 'describe --always'
function GitRevisionPlugin (options) {
options = options || {}
this.gitWorkTree = options.gitWorkTree
this.commithashCommand = options.commithashCommand ||
COMMITHASH_COMMAND
this.versionCommand = options.versionCommand ||
VERSION_COMMAND + (options.lightweightTags ? ' --tags' : '')
}
GitRevisionPlugin.prototype.apply = function (compiler) {
buildFile(compiler,
this.gitWorkTree,
this.commithashCommand,
/\[git-revision-hash\]/gi,
'COMMITHASH'
)
buildFile(compiler,
this.gitWorkTree,
this.versionCommand,
/\[git-revision-version\]/gi,
'VERSION'
)
}
GitRevisionPlugin.prototype.commithash = function () {
return runGitCommand(
this.gitWorkTree,
this.commithashCommand
)
}
GitRevisionPlugin.prototype.version = function () {
return runGitCommand(
this.gitWorkTree,
this.versionCommand
)
}
module.exports = GitRevisionPlugin
| var buildFile = require('./build-file')
var runGitCommand = require('./helpers/run-git-command')
var COMMITHASH_COMMAND = 'rev-parse HEAD'
var VERSION_COMMAND = 'describe --always'
function GitRevisionPlugin (options) {
this.gitWorkTree = options && options.gitWorkTree
this.lightweightTags = options && options.lightweightTags || false
this.commithashCommand = options && options.commithashCommand || COMMITHASH_COMMAND
this.versionCommand = options && options.versionCommand || VERSION_COMMAND
}
GitRevisionPlugin.prototype.apply = function (compiler) {
buildFile(compiler,
this.gitWorkTree,
this.commithashCommand,
/\[git-revision-hash\]/gi,
'COMMITHASH'
)
buildFile(compiler,
this.gitWorkTree,
this.versionCommand + (this.lightweightTags ? ' --tags' : ''),
/\[git-revision-version\]/gi,
'VERSION'
)
}
GitRevisionPlugin.prototype.commithash = function () {
return runGitCommand(
this.gitWorkTree,
this.commithashCommand
)
}
GitRevisionPlugin.prototype.version = function () {
return runGitCommand(
this.gitWorkTree,
this.versionCommand + (this.lightweightTags ? ' --tags' : '')
)
}
module.exports = GitRevisionPlugin
|
Refactor static variables out of slave node runner | package primes.bramble;
import java.io.Serializable;
import java.util.ArrayList;
import primes.PrimeGenerator;
import bramble.node.slave.ISlaveNodeRunner;
import bramble.node.slave.SlaveNode;
/**
* This is an example of how a SlaveNode can be run.
*
* This class is responsible for passing a job from the
* API to a class that will accept a job.
*
* @author Tom
*
*/
public class SlaveNodeRunner implements ISlaveNodeRunner{
private final String ipAddress;
public static void main(String[] args){
if(args.length != 1){
System.out.println("Didn't find an IP on the command line, exiting");
return;
}
String ipAddress = args[0];
System.out.println("Slave node initiated, my IP is " + ipAddress);
(new SlaveNodeRunner(ipAddress)).initialize();
}
public SlaveNodeRunner(String ipAddress){
this.ipAddress = ipAddress;
}
public void initialize(){
(new SlaveNode<>(this.ipAddress, this)).listenForever();
}
@Override
public void runJob(int jobID, ArrayList<Serializable> initializationData) {
//System.out.print("[" + jobID + "] ");
PrimeGenerator primeGenerator = new PrimeGenerator(this.ipAddress, jobID, initializationData);
primeGenerator.run();
}
}
| package primes.bramble;
import java.io.Serializable;
import java.util.ArrayList;
import primes.PrimeGenerator;
import bramble.node.slave.ISlaveNodeRunner;
import bramble.node.slave.SlaveNode;
/**
* This is an example of how a SlaveNode can be run.
*
* This class is responsible for passing a job from the
* API to a class that will accept a job.
*
* @author Tom
*
*/
public class SlaveNodeRunner implements ISlaveNodeRunner{
private static String IPADDR;
@SuppressWarnings("unused")
public static void main(String[] args){
if(args.length != 1){
System.out.println("Didn't find an IP on the command line, exiting");
System.exit(1);
} else {
IPADDR = args[0];
System.out.println("Slave node initiated, my IP is " + IPADDR);
}
new SlaveNodeRunner();
}
public SlaveNodeRunner(){
(new SlaveNode<>(IPADDR, this)).listenForever();
}
@Override
public void runJob(int jobID, ArrayList<Serializable> initializationData) {
//System.out.print("[" + jobID + "] ");
PrimeGenerator primeGenerator = new PrimeGenerator(IPADDR, jobID, initializationData);
primeGenerator.run();
}
}
|
Upgrade testsuite to JUnit 4's @RunWith(Suite.class)
This is in preparation for j2cl where this will be the norm. | /*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gwtproject.http;
import org.gwtproject.http.client.RequestBuilderTest;
import org.gwtproject.http.client.RequestTest;
import org.gwtproject.http.client.ResponseTest;
import org.gwtproject.http.client.URLTest;
import org.gwtproject.http.client.UrlBuilderTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/** Test for suite for the org.gwtproject.http module */
@RunWith(Suite.class)
@Suite.SuiteClasses({
URLTest.class,
RequestBuilderTest.class,
RequestTest.class,
ResponseTest.class,
UrlBuilderTest.class
})
public class HTTPSuite {}
| /*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.gwtproject.http;
import org.gwtproject.http.client.RequestBuilderTest;
import org.gwtproject.http.client.RequestTest;
import org.gwtproject.http.client.ResponseTest;
import org.gwtproject.http.client.URLTest;
import org.gwtproject.http.client.UrlBuilderTest;
import com.google.gwt.junit.tools.GWTTestSuite;
import junit.framework.Test;
/**
* TODO: document me.
*/
public class HTTPSuite {
public static Test suite() {
GWTTestSuite suite = new GWTTestSuite(
"Test for suite for the org.gwtproject.http module");
suite.addTestSuite(URLTest.class);
suite.addTestSuite(RequestBuilderTest.class);
suite.addTestSuite(RequestTest.class);
suite.addTestSuite(ResponseTest.class);
suite.addTestSuite(UrlBuilderTest.class);
return suite;
}
}
|
Add pycrypto to optional module
It's not used by core code at the moment | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.1',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
setup_requires=[
'nose>=1.1.2',
'mock>=0.8',
'blinker==1.2',
],
install_requires=[
'Flask>=0.8',
],
extras_require={
'paging': 'pycrypto>=2.6',
}
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.1',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
setup_requires=[
'nose>=1.1.2',
'mock>=0.8',
'blinker==1.2',
],
install_requires=[
'Flask>=0.8',
'pycrypto>=2.6',
]
)
|
Make title field appear before comment in the form
Fixes #7 | from django import forms
from django.contrib.comments.forms import CommentForm
from django.conf import settings
from django.utils.hashcompat import sha_constructor
from threadedcomments.models import ThreadedComment
class ThreadedCommentForm(CommentForm):
parent = forms.IntegerField(required=False, widget=forms.HiddenInput)
def __init__(self, target_object, parent=None, data=None, initial=None):
self.base_fields.insert(
self.base_fields.keyOrder.index('comment'),
'title', forms.CharField(required=False)
)
self.parent = parent
if initial is None:
initial = {}
initial.update({'parent': self.parent})
super(ThreadedCommentForm, self).__init__(target_object, data=data,
initial=initial)
def get_comment_model(self):
return ThreadedComment
def get_comment_create_data(self):
d = super(ThreadedCommentForm, self).get_comment_create_data()
d['parent_id'] = self.cleaned_data['parent']
d['title'] = self.cleaned_data['title']
return d
| from django import forms
from django.contrib.comments.forms import CommentForm
from django.conf import settings
from django.utils.hashcompat import sha_constructor
from threadedcomments.models import ThreadedComment
class ThreadedCommentForm(CommentForm):
parent = forms.IntegerField(required=False, widget=forms.HiddenInput)
title = forms.CharField(required=False)
def __init__(self, target_object, parent=None, data=None, initial=None):
self.parent = parent
if initial is None:
initial = {}
initial.update({'parent': self.parent})
super(ThreadedCommentForm, self).__init__(target_object, data=data,
initial=initial)
def get_comment_model(self):
return ThreadedComment
def get_comment_create_data(self):
d = super(ThreadedCommentForm, self).get_comment_create_data()
d['parent_id'] = self.cleaned_data['parent']
d['title'] = self.cleaned_data['title']
return d
|
Add support to the float slider | // Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.
define([
"widgets/js/widget",
"widgets/js/widget_int",
], function(widget, int_widgets){
var IntSliderView = int_widgets.IntSliderView;
var IntTextView = int_widgets.IntTextView;
var FloatSliderView = IntSliderView.extend({
_validate_text_input: function(x) {
return parseFloat(x);
},
_validate_slide_value: function(x) {
// Validate the value of the slider before sending it to the back-end
// and applying it to the other views on the page.
return x;
},
});
var FloatTextView = IntTextView.extend({
_parse_value: function(value) {
// Parse the value stored in a string.
return parseFloat(value);
},
});
return {
'FloatSliderView': FloatSliderView,
'FloatTextView': FloatTextView,
};
});
| // Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.
define([
"widgets/js/widget",
"widgets/js/widget_int",
], function(widget, int_widgets){
var IntSliderView = int_widgets.IntSliderView;
var IntTextView = int_widgets.IntTextView;
var FloatSliderView = IntSliderView.extend({
_validate_slide_value: function(x) {
// Validate the value of the slider before sending it to the back-end
// and applying it to the other views on the page.
return x;
},
});
var FloatTextView = IntTextView.extend({
_parse_value: function(value) {
// Parse the value stored in a string.
return parseFloat(value);
},
});
return {
'FloatSliderView': FloatSliderView,
'FloatTextView': FloatTextView,
};
});
|
Set retrofit log level according to build config | package fr.utc.assos.uvweb.api;
import java.util.List;
import fr.utc.assos.uvweb.BuildConfig;
import fr.utc.assos.uvweb.model.Newsfeed;
import fr.utc.assos.uvweb.model.UvDetail;
import fr.utc.assos.uvweb.model.UvListItem;
import retrofit.Callback;
import retrofit.RestAdapter;
public class UvwebProvider {
private static RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://assos.utc.fr/uvweb")
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
.build();
private static UvwebApi uvwebApi = restAdapter.create(UvwebApi.class);
public static void getUvs(Callback<List<UvListItem>> callback) {
uvwebApi.getUvs(callback);
}
public static void getNewsfeed(Callback<Newsfeed> callback) {
uvwebApi.getNewsfeed(callback);
}
public static void getUvDetail(String name, Callback<UvDetail> callback) {
uvwebApi.getUvDetail(name, callback);
}
}
| package fr.utc.assos.uvweb.api;
import java.util.List;
import fr.utc.assos.uvweb.model.Newsfeed;
import fr.utc.assos.uvweb.model.UvDetail;
import fr.utc.assos.uvweb.model.UvListItem;
import retrofit.Callback;
import retrofit.RestAdapter;
public class UvwebProvider {
private static RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://assos.utc.fr/uvweb")
.build();
private static UvwebApi uvwebApi = restAdapter.create(UvwebApi.class);
public static void getUvs(Callback<List<UvListItem>> callback) {
uvwebApi.getUvs(callback);
}
public static void getNewsfeed(Callback<Newsfeed> callback) {
uvwebApi.getNewsfeed(callback);
}
public static void getUvDetail(String name, Callback<UvDetail> callback) {
uvwebApi.getUvDetail(name, callback);
}
}
|
Return an actual bool from any() | import __builtin__
def any(it):
for obj in it:
if obj:
return True
return False
def all(it):
for obj in it:
if not obj:
return False
return True
def max(it, key=None):
if key is not None:
k, value = max((key(value), value) for value in it)
return value
return max(it)
def min(it, key=None):
if key is not None:
k, value = min((key(value), value) for value in it)
return value
return min(it)
class Condition(object):
"""
This wraps a condition so that it can be shared by everyone and modified
by whomever wants to.
"""
def __init__(self, value):
self.value = value
def __nonzero__(self):
return self.value
class ComparableObjectMixin(object):
def __hash__(self):
"Implement in subclasses"
raise NotImplementedError
def __eq__(self, other):
"Implement in subclasses"
return NotImplemented | import __builtin__
def any(it):
for obj in it:
if obj:
return True
def all(it):
for obj in it:
if not obj:
return False
return True
def max(it, key=None):
if key is not None:
k, value = max((key(value), value) for value in it)
return value
return max(it)
def min(it, key=None):
if key is not None:
k, value = min((key(value), value) for value in it)
return value
return min(it)
class Condition(object):
"""
This wraps a condition so that it can be shared by everyone and modified
by whomever wants to.
"""
def __init__(self, value):
self.value = value
def __nonzero__(self):
return self.value
class ComparableObjectMixin(object):
def __hash__(self):
"Implement in subclasses"
raise NotImplementedError
def __eq__(self, other):
"Implement in subclasses"
return NotImplemented |
[core] Update class in com.b2international.snowowl.core bundle | /*
* Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.core.api;
import com.b2international.commons.collections.primitive.LongCollection;
/**
* @since 4.6
*/
public interface ITreeComponent {
/**
* @return the ancestor IDs of this component
*/
LongCollection getAncestors();
/**
* @return the direct parent IDs of this component
*/
LongCollection getParents();
}
| /*
* Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.core.api;
import bak.pcj.LongCollection;
/**
* @since 4.6
*/
public interface ITreeComponent {
/**
* @return the ancestor IDs of this component
*/
LongCollection getAncestors();
/**
* @return the direct parent IDs of this component
*/
LongCollection getParents();
}
|
Terminate exec on shell errors | // CLI setup
import program from 'commander';
import jsonfile from 'jsonfile';
import shell from 'shelljs';
import updateNotifier from 'update-notifier';
import winston from 'winston';
import pkg from '../../package.json';
import compileBundle from './bundle';
import AzureMethods from './azure-methods';
updateNotifier({ pkg }).notify();
program
.description(pkg.description)
.version(`v${pkg.version}`, '-v, --version')
.option('-s, --settings <path>', 'path to settings file [settings.json]', 'settings.json')
.option('-w, --web-config <path>', 'path to custom web.config file')
.option('-d, --debug', 'enable debug mode')
.option('-q, --quiet', 'enable quite mode')
.parse(process.argv);
// Pretty print logs
winston.cli();
// Terminate on shell error
shell.config.fatal = true;
// Quiet mode
if (program.quiet === true) {
winston.level = 'error';
shell.config.silent = true;
}
// Debug mode
if (program.debug === true) {
winston.level = 'debug';
}
export default async function startup() {
try {
const azureMethods = new AzureMethods(jsonfile.readFileSync(program.settings));
await azureMethods.authenticate();
await azureMethods.updateApplicationSettings();
const bundleFile = compileBundle({ customWebConfig: program.webConfig });
await azureMethods.deployBundle({ bundleFile });
} catch (error) {
winston.error(error.message);
process.exit(1);
}
}
| // CLI setup
import program from 'commander';
import jsonfile from 'jsonfile';
import shell from 'shelljs';
import updateNotifier from 'update-notifier';
import winston from 'winston';
import pkg from '../../package.json';
import compileBundle from './bundle';
import AzureMethods from './azure-methods';
updateNotifier({ pkg }).notify();
program
.description(pkg.description)
.version(`v${pkg.version}`, '-v, --version')
.option('-s, --settings <path>', 'path to settings file [settings.json]', 'settings.json')
.option('-w, --web-config <path>', 'path to custom web.config file')
.option('-d, --debug', 'enable debug mode')
.option('-q, --quiet', 'enable quite mode')
.parse(process.argv);
// Pretty print logs
winston.cli();
// Quiet mode
if (program.quiet === true) {
winston.level = 'error';
shell.config.silent = true;
}
// Debug mode
if (program.debug === true) {
winston.level = 'debug';
}
export default async function startup() {
try {
const azureMethods = new AzureMethods(jsonfile.readFileSync(program.settings));
await azureMethods.authenticate();
await azureMethods.updateApplicationSettings();
const bundleFile = compileBundle({ customWebConfig: program.webConfig });
await azureMethods.deployBundle({ bundleFile });
} catch (error) {
winston.error(error.message);
process.exit(1);
}
}
|
Fix crash when invalid json is returned | import urllib
import json
import logging
def quote(text):
try:
return urllib.quote(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote(unicode(text, 'utf-8').encode('utf-8'))
def quote_plus(text):
try:
return urllib.quote_plus(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote_plus(unicode(text, 'utf-8').encode('utf-8'))
def get(url):
try:
return urllib.urlopen(url).read()
except urllib.error.HTTPError as err:
logging.error(err)
def ajax(url):
data = get(url)
if data:
logging.info('got data from ' + url)
logging.info(data)
try:
return json.loads(data)
except ValueError as err:
logging.error(err)
| import urllib
import json
import logging
def quote(text):
try:
return urllib.quote(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote(unicode(text, 'utf-8').encode('utf-8'))
def quote_plus(text):
try:
return urllib.quote_plus(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote_plus(unicode(text, 'utf-8').encode('utf-8'))
def get(url):
try:
return urllib.urlopen(url).read()
except urllib.error.HTTPError as err:
logging.error(err)
def ajax(url):
data = get(url)
if data:
logging.info('got data from ' + url)
logging.info(data)
return json.loads(data)
|
Fix app crash due to Realm database migration | package com.github.ayltai.newspaper.data;
import android.content.Context;
import android.support.annotation.NonNull;
import dagger.Module;
import dagger.Provides;
import io.realm.Realm;
import io.realm.RealmConfiguration;
@Module
public final class DataModule {
private static final int SCHEMA_VERSION = 1;
private static boolean isInitialized;
private final Context context;
public DataModule(@NonNull final Context context) {
this.context = context.getApplicationContext();
}
@NonNull
@Provides
Context provideContext() {
return this.context;
}
@NonNull
@Provides
Realm provideRealm() {
if (!DataModule.isInitialized) {
Realm.init(this.context);
Realm.setDefaultConfiguration(new RealmConfiguration.Builder()
.schemaVersion(DataModule.SCHEMA_VERSION)
.deleteRealmIfMigrationNeeded()
.compactOnLaunch()
.build());
DataModule.isInitialized = true;
}
return Realm.getDefaultInstance();
}
}
| package com.github.ayltai.newspaper.data;
import android.content.Context;
import android.support.annotation.NonNull;
import dagger.Module;
import dagger.Provides;
import io.realm.Realm;
import io.realm.RealmConfiguration;
@Module
public final class DataModule {
private static final int SCHEMA_VERSION = 1;
private static boolean isInitialized;
private final Context context;
public DataModule(@NonNull final Context context) {
this.context = context.getApplicationContext();
}
@NonNull
@Provides
Context provideContext() {
return this.context;
}
@NonNull
@Provides
Realm provideRealm() {
if (!DataModule.isInitialized) {
Realm.init(this.context);
Realm.setDefaultConfiguration(new RealmConfiguration.Builder().schemaVersion(DataModule.SCHEMA_VERSION).build());
DataModule.isInitialized = true;
}
return Realm.getDefaultInstance();
}
}
|
Remove db interfaces from the alembic version reset helper script.
Arguably, this script is no longer especially useful now that we
only have a single database for the broker. That said, removed the
interfaces in case folks are still using it. | import argparse
from sqlalchemy import MetaData, Table
from sqlalchemy.sql import update
from dataactcore.interfaces.db import GlobalDB
from dataactvalidator.app import createApp
def reset_alembic(alembic_version):
with createApp().app_context():
db = GlobalDB.db()
engine = db.engine
sess = db.session
metadata = MetaData(bind=engine)
alembic_table = Table('alembic_version', metadata, autoload=True)
u = update(alembic_table)
u = u.values({"version_num": alembic_version})
sess.execute(u)
sess.commit()
parser = argparse.ArgumentParser\
(description="Reset alembic version table.")
parser.add_argument(
'version', help="Version to set the Alembic migration table to.")
v = vars(parser.parse_args())['version']
reset_alembic(v)
| import argparse
from dataactcore.models.errorInterface import ErrorInterface
from dataactcore.models.jobTrackerInterface import JobTrackerInterface
from dataactcore.models.userInterface import UserInterface
from dataactcore.models.validationInterface import ValidationInterface
from sqlalchemy import MetaData, Table
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import update
def reset_alembic(alembic_version):
engine_list = [
ErrorInterface().engine,
JobTrackerInterface().engine,
UserInterface().engine,
ValidationInterface().engine,
]
for e in engine_list:
Session = sessionmaker(bind=e)
session = Session()
metadata = MetaData(bind=e)
alembic_table = Table('alembic_version', metadata, autoload=True)
u = update(alembic_table)
u = u.values({"version_num": alembic_version})
session.execute(u)
session.commit()
parser = argparse.ArgumentParser\
(description="Reset alembic version tables across broker databases.")
parser.add_argument(
'version', help="Version to set the Alembic migration tables to.")
v = vars(parser.parse_args())['version']
reset_alembic(v)
|
Load language config for highlight.js dynamically | // @flow
import { PureComponent } from 'react'
import Lowlight from 'react-lowlight'
import type { Children } from 'react'
import langMap from 'settings/languageNameMap'
type Props = {
className:string,
children: Children,
}
type State = {
language: string,
}
export default class Code extends PureComponent<void, Props, State> {
static languageClassNamePattern = /\s*language-([\w-]+)\s*/
constructor (props: Props) {
super(props)
this.state = {
language: '',
}
}
state: State
componentWillMount () {
this.registerLanguage(this.props.className)
}
componentWillReceiveProps ({ className }: Props) {
this.registerLanguage(className)
}
async registerLanguage (className: string) {
const match = (className || '').match(Code.languageClassNamePattern)
const langName = (match && match[1]) || ''
const lang = langMap[langName]
if (lang == null) {
this.setState({ language: '' })
} else if (Lowlight.hasLanguage(langName)) {
this.setState({ language: langName })
} else {
Lowlight.registerLanguage(langName, await lang.load())
this.setState({ language: langName })
}
}
get value (): string {
return this.props.children[0]
}
render () {
return (
<Lowlight
language={this.state.language}
value={this.value}
inline
/>
)
}
}
| // @flow
import { PureComponent } from 'react'
import Lowlight from 'react-lowlight'
import js from 'highlight.js/lib/languages/javascript'
import type { Children } from 'react'
type Props = {
className:string,
children: Children,
}
Lowlight.registerLanguage('js', js)
export default class Code extends PureComponent<void, Props, void> {
static languageClassNamePattern = /\s*language-([\w-]+)\s*/
// for lint
props: Props
get language (): string {
const match = (this.props.className || '').match(Code.languageClassNamePattern)
const lang = (match && match[1]) || ''
return Lowlight.hasLanguage(lang) ? lang : ''
}
get value (): string {
return this.props.children[0]
}
render () {
return (
<Lowlight
language={this.language}
value={this.value}
inline
/>
)
}
}
|
Use .png as extension on conversion | package core
import (
"errors"
"fmt"
"image"
"image/png"
"io"
"os"
"os/exec"
)
type PNGHandler struct {
}
func (p *PNGHandler) ImageType() string {
return "image/png"
}
func (p *PNGHandler) Decode(reader io.Reader) (image.Image, error) {
return png.Decode(reader)
}
func (p *PNGHandler) Encode(newImgFile *os.File, newImage image.Image) error {
return png.Encode(newImgFile, newImage)
}
func (p *PNGHandler) Convert(newImageTempPath string, quality uint) error {
args := []string{newImageTempPath, "-f", "--ext=.png"}
if quality != 100 {
var qualityMin = quality - 10
qualityParameter := fmt.Sprintf("--quality=%[1]d-%[2]d", qualityMin, quality)
args = append([]string{qualityParameter}, args...)
}
cmd := exec.Command("pngquant", args...)
err := cmd.Run()
if err != nil {
return errors.New("Pngquant command not working")
}
return nil
}
| package core
import (
"errors"
"fmt"
"image"
"image/png"
"io"
"os"
"os/exec"
)
type PNGHandler struct {
}
func (p *PNGHandler) ImageType() string {
return "image/png"
}
func (p *PNGHandler) Decode(reader io.Reader) (image.Image, error) {
return png.Decode(reader)
}
func (p *PNGHandler) Encode(newImgFile *os.File, newImage image.Image) error {
return png.Encode(newImgFile, newImage)
}
func (p *PNGHandler) Convert(newImageTempPath string, quality uint) error {
args := []string{newImageTempPath, "-f", "--ext=\"\""}
if quality != 100 {
var qualityMin = quality - 10
qualityParameter := fmt.Sprintf("--quality=%[1]d-%[2]d", qualityMin, quality)
args = append([]string{qualityParameter}, args...)
}
cmd := exec.Command("pngquant", args...)
err := cmd.Run()
if err != nil {
return errors.New("Pngquant command not working")
}
return nil
}
|
BAP-10873: Apply select2-autocomplete component for business unit own... | <?php
namespace Oro\Bundle\FilterBundle\Event;
use Symfony\Component\EventDispatcher\Event;
use Oro\Bundle\DashboardBundle\Model\WidgetOptionBag;
class ChoiceTreeFilterLoadDataEvent extends Event
{
const EVENT_NAME = 'oro_filter.choice_tree_filter_load_data';
/** @var String */
protected $className;
/** @var array */
protected $values;
/** @var array */
protected $data;
/**
* ChoiceTreeFilterLoadDataEvent constructor.
*
* @param string $className
* @param array $values
*/
public function __construct($className, array $values)
{
$this->className = $className;
$this->values = $values;
}
/**
* Return array id of entity
*
* @return array
*/
public function getValues()
{
return $this->values;
}
/**
* @return WidgetOptionBag
*/
public function getClassName()
{
return $this->className;
}
/**
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* @param $data
*/
public function setData($data)
{
$this->data = $data;
}
}
| <?php
namespace Oro\Bundle\FilterBundle\Event;
use Symfony\Component\EventDispatcher\Event;
use Oro\Bundle\DashboardBundle\Model\WidgetOptionBag;
class ChoiceTreeFilterLoadDataEvent extends Event
{
const EVENT_NAME = 'oro_filter.choice_tree_filter_load_data';
/** @var String */
protected $className;
/** @var array */
protected $values;
/** @var array */
protected $data;
/**
* ChoiceTreeFilterLoadDataEvent constructor.
*
* @param string $className
* @param array $values
*/
public function __construct($className, array $values)
{
$this->className = $className;
$this->values = $values;
}
/**
* Return array id of entity
*
* @return array
*/
public function getValues()
{
return $this->values;
}
/**
* @return WidgetOptionBag
*/
public function getClassName()
{
return $this->className;
}
/**
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* @param $values
*/
public function setData($values)
{
$this->data = $values;
}
}
|
Fix case sensitive LDAP attributes | from django_auth_ldap.backend import LDAPBackend
class NumbasAuthBackend(LDAPBackend):
"""Authentication backend overriding LDAPBackend.
This could be used to override certain functionality within the LDAP authentication backend.
The example here overrides get_or_create_user() to alter the LDAP givenName attribute.
To use this backend, edit settings.py and replace the LDAPBackend line in AUTHENTICATION_BACKENDS with
numbas_auth.NumbasAuthBackend
"""
def get_or_create_user(self, username, ldap_user):
"""Alter the LDAP givenName attribute to the familiar first name in displayName."""
ldap_user.attrs['givenName'] = [ldap_user.attrs['displayName'][0].split()[0]]
return super(NumbasAuthBackend, self).get_or_create_user(username, ldap_user)
| from django_auth_ldap.backend import LDAPBackend
class NumbasAuthBackend(LDAPBackend):
"""Authentication backend overriding LDAPBackend.
This could be used to override certain functionality within the LDAP authentication backend.
The example here overrides get_or_create_user() to alter the LDAP givenName attribute.
To use this backend, edit settings.py and replace the LDAPBackend line in AUTHENTICATION_BACKENDS with
numbas_auth.NumbasAuthBackend
"""
def get_or_create_user(self, username, ldap_user):
"""Alter the LDAP givenName attribute to the familiar first name in displayName."""
ldap_user.attrs['givenname'] = [ldap_user.attrs['displayname'][0].split()[0]]
return super(NumbasAuthBackend, self).get_or_create_user(username, ldap_user)
|
Use more generic values for version | #!/bin/env python
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'localhost', 'date': '1970-01-01', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '0x', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
xml = template.toXML(version)
ova_xml = open("ova.xml", "w")
ova_xml.write(xml)
ova_xml.close()
# Generate tarball containing ova.xml
template_name = os.path.splitext(fname)[0]
tar = tarfile.open("%s.tar" % template_name, "w")
tar.add("ova.xml")
tar.close()
os.remove("ova.xml")
# Import XS template
uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"])
# Set default_template = true
out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
| #!/bin/env python
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'golm-2', 'date': '2016-04-29', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '125122c', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
xml = template.toXML(version)
ova_xml = open("ova.xml", "w")
ova_xml.write(xml)
ova_xml.close()
# Generate tarball containing ova.xml
template_name = os.path.splitext(fname)[0]
tar = tarfile.open("%s.tar" % template_name, "w")
tar.add("ova.xml")
tar.close()
os.remove("ova.xml")
# Import XS template
uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"])
# Set default_template = true
out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
|
Remove empty event handler in chaos monkey | 'use strict';
/**
* Stubby Chaos Money Demo Module
*/
var StubbyChaosMonkey = function() {
/* min is inclusive, and max is exclusive */
var getRandomArbitrary = function(min, max) {
return Math.random() * (max - min) + min;
};
var getRandomHTTPStatus = function() {
return getRandomArbitrary(100, 600);
};
this.register = function(handler) {
// Called before a request and response are matched
handler.on('routesetup', this.onRouteSetup, this);
// Called after a request and response are matched
handler.on('request', this.onRequestExecute, this);
};
this.onRouteSetup = function(request, stub) {
if (!stub.internal.options.chaos) {
return;
}
if (stub.response.status !== 43) {
throw new Error('Response status needs to be `43` for a valid chaos response');
}
};
this.onRequestExecute = function(request, stub) {
if (stub.internal.options.chaos) {
stub.response.status = getRandomHTTPStatus();
}
};
};
if (typeof module === 'undefined') {
window.StubbyChaosMonkey = StubbyChaosMonkey;
} else {
module.exports = StubbyChaosMonkey;
}
| 'use strict';
/**
* Stubby Chaos Money Demo Module
*/
var StubbyChaosMonkey = function() {
/* min is inclusive, and max is exclusive */
var getRandomArbitrary = function(min, max) {
return Math.random() * (max - min) + min;
};
var getRandomHTTPStatus = function() {
return getRandomArbitrary(100, 600);
};
this.register = function(handler) {
// Request is empty on route setup.
handler.on('setup', this.onRequestSetup, this);
// Called before a request and response are matched
handler.on('routesetup', this.onRouteSetup, this);
// Called after a request and response are matched
handler.on('request', this.onRequestExecute, this);
};
this.onRouteSetup = function(request, stub) {
if (!stub.internal.options.chaos) {
return;
}
if (stub.response.status !== 43) {
throw new Error('Response status needs to be `43` for a valid chaos response');
}
};
this.onRequestSetup = function() {
// console.log('[requestsetup] ', request, stub);
};
this.onRequestExecute = function(request, stub) {
if (stub.internal.options.chaos) {
stub.response.status = getRandomHTTPStatus();
}
};
};
if (typeof module === 'undefined') {
window.StubbyChaosMonkey = StubbyChaosMonkey;
} else {
module.exports = StubbyChaosMonkey;
}
|
Bump up the version after fix | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='timeflow',
packages=['timeflow'],
version='0.1.1',
description='Small CLI time logger',
author='Justas Trimailovas',
author_email='j.trimailvoas@gmail.com',
url='https://github.com/trimailov/timeflow',
keywords=['timelogger', 'logging', 'timetracker', 'tracker'],
long_description=read('README.rst'),
entry_points='''
[console_scripts]
timeflow=timeflow.main:main
tf=timeflow.main:main
''',
)
| import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='timeflow',
packages=['timeflow'],
version='0.1',
description='Small CLI time logger',
author='Justas Trimailovas',
author_email='j.trimailvoas@gmail.com',
url='https://github.com/trimailov/timeflow',
keywords=['timelogger', 'logging', 'timetracker', 'tracker'],
long_description=read('README.rst'),
entry_points='''
[console_scripts]
timeflow=timeflow.main:main
tf=timeflow.main:main
''',
)
|
feature/oop-api-refactoring: Fix and cast path to `str` | # -*- coding: utf-8 -*-
from pathlib import Path
import logging
from logging.config import fileConfig
class Logger:
loggers = {}
@staticmethod
def get_logger(name: str = '') -> logging.Logger:
if name not in Logger.loggers.keys():
config_path = Path(__file__).parent / 'logging.ini'
config_path = str(config_path) # for Python 3.5
fileConfig(config_path)
Logger.loggers[name] = logging.getLogger(name)
return Logger.loggers.get(name)
@staticmethod
def set_level(level: int):
for name, logger in Logger.loggers.items():
logger.setLevel(level)
def get_logger(name: str = '') -> logging.Logger:
return Logger.get_logger(name)
def set_level(level: int):
Logger.set_level(level)
| # -*- coding: utf-8 -*-
from pathlib import Path
import logging
from logging.config import fileConfig
class Logger:
loggers = {}
@staticmethod
def get_logger(name: str = '') -> logging.Logger:
if name not in Logger.loggers.keys():
config_path = Path(__file__).parent / 'logging.ini'
fileConfig(config_path)
Logger.loggers[name] = logging.getLogger(name)
return Logger.loggers.get(name)
@staticmethod
def set_level(level: int):
for name, logger in Logger.loggers.items():
logger.setLevel(level)
def get_logger(name: str = '') -> logging.Logger:
return Logger.get_logger(name)
def set_level(level: int):
Logger.set_level(level)
|
lathe[cuboid]: Support string args in BoxGeometry transform helpers.
In addition to object definitions. | /* eslint-env es6 */
/* global THREE, VertexIndices */
function transformBoxVertices( method ) {
'use strict';
const vector = new THREE.Vector3();
const zero = new THREE.Vector3();
function baseTransform( geometry, key, delta, ...args ) {
const indices = VertexIndices[ key.toUpperCase() ];
if ( Array.isArray( delta ) ) {
vector.fromArray( delta );
} else if ( typeof delta === 'object' ) {
Object.assign( vector, zero, delta );
} else if ( typeof delta === 'number' ) {
vector.setScalar( delta );
} else {
return;
}
if ( Array.isArray( indices ) ) {
indices.forEach( index =>
geometry.vertices[ index ][ method ]( vector, ...args )
);
} else {
geometry.vertices[ indices ][ method ]( vector, ...args );
}
return geometry;
}
return function transform( geometry, vectors, ...args ) {
if ( typeof vectors === 'string' ) {
return baseTransform( geometry, vectors, ...args );
} else if ( typeof vectors === 'object' ) {
Object.keys( vectors ).forEach( key => {
const delta = vectors[ key ];
baseTransform( geometry, key, delta, ...args );
});
}
return geometry;
};
}
window.translateBoxVertices = transformBoxVertices( 'add' );
window.scaleBoxVertices = transformBoxVertices( 'multiply' );
window.lerpBoxVertices = transformBoxVertices( 'lerp' );
| /* eslint-env es6 */
/* global THREE, VertexIndices */
function transformBoxVertices( method ) {
'use strict';
const vector = new THREE.Vector3();
const zero = new THREE.Vector3();
return function transform( geometry, vectors, ...args ) {
Object.keys( vectors ).forEach( key => {
const delta = vectors[ key ];
const indices = VertexIndices[ key.toUpperCase() ];
if ( Array.isArray( delta ) ) {
vector.fromArray( delta );
} else if ( typeof delta === 'object' ) {
Object.assign( vector, zero, delta );
} else if ( typeof delta === 'number' ) {
vector.setScalar( delta );
} else {
return;
}
if ( Array.isArray( indices ) ) {
indices.forEach( index =>
geometry.vertices[ index ][ method ]( vector, ...args )
);
} else {
geometry.vertices[ indices ][ method ]( vector, ...args );
}
});
return geometry;
};
}
window.translateBoxVertices = transformBoxVertices( 'add' );
window.scaleBoxVertices = transformBoxVertices( 'multiply' );
window.lerpBoxVertices = transformBoxVertices( 'lerp' );
|
Delete escped variable, replaced with single quotes | #!/usr/bin/env python
import os, sys
# Set arguments values
if len(sys.argv) == 1:
print "Usage: clone-vm.py [new-vm-name]"
exit(1)
else:
new_vm_name = sys.argv[1]
vms_path_dir = os.getenv('HOME') + '/Documents/Virtual Machines.localized/'
vm_source_vmx = vms_home_dir + 'base-centos-64.vmwarevm/base-centos-64.vmx'
vm_dest_dir = vms_home_dir + new_vm_name + ".vmwarevm"
vm_dest_vmx = vm_dest_dir + '/' + new_vm_name + '.vmx'
if not os.path.exists(vm_dest_dir):
os.makedirs(vm_dest_dir)
cmd = 'vmrun clone \'' + vm_source_vmx + '\' \'' + vm_dest_vmx + '\' linked -cloneName=' + new_vm_name
print "[+] Creating new linked vm: " + new_vm_name
os.system(cmd)
| #!/usr/bin/env python
import os
import sys
# Set arguments values
if len(sys.argv) == 1:
print "Usage: clone-vm.py [new-vm-name]"
exit(1)
else:
new_vm_name = sys.argv[1]
vms_home_dir = os.getenv('HOME') + '/Documents/Virtual\ Machines.localized/'
vms_home_dir_not_escaped = os.getenv('HOME') + '/Documents/Virtual Machines.localized/'
vm_source_vmx = vms_home_dir + 'base-centos-64.vmwarevm/base-centos-64.vmx'
vm_dest_dir_not_escaped = vms_home_dir_not_escaped + new_vm_name + ".vmwarevm"
vm_dest_dir = vms_home_dir + new_vm_name
vm_dest_vmx = vm_dest_dir + '/' + new_vm_name + '.vmx'
if not os.path.exists(vm_dest_dir_not_escaped):
os.makedirs(vm_dest_dir_not_escaped)
cmd = 'vmrun clone ' + vm_source_vmx + ' ' + vm_dest_vmx + ' linked -cloneName=' + new_vm_name
print "[+] Creating new linked vm"
os.system(cmd)
|
Fix Checkstyle issues: First sentence should end with a period.
git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1352225 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.example;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;
/**
* Simply changed the last modification time of the given file.
*/
public class ChangeLastModificationTime
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
{
System.err.println("Please pass the name of a file as parameter.");
return;
}
FileObject fo = VFS.getManager().resolveFile(args[0]);
long setTo = System.currentTimeMillis();
System.err.println("set to: " + setTo);
fo.getContent().setLastModifiedTime(setTo);
System.err.println("after set: " + fo.getContent().getLastModifiedTime());
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.example;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;
/**
* Simply changed the last modification time of the given file
*/
public class ChangeLastModificationTime
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
{
System.err.println("Please pass the name of a file as parameter.");
return;
}
FileObject fo = VFS.getManager().resolveFile(args[0]);
long setTo = System.currentTimeMillis();
System.err.println("set to: " + setTo);
fo.getContent().setLastModifiedTime(setTo);
System.err.println("after set: " + fo.getContent().getLastModifiedTime());
}
}
|
Fix single char variable name | import requests
from HTMLParser import HTMLParser
from BeautifulSoup import BeautifulSoup
def run(data, settings):
if data['payload'] == 'urban dictionary me':
req = requests.get('http://www.urbandictionary.com/random.php')
soup = BeautifulSoup(req.text,
convertEntities=BeautifulSoup.HTML_ENTITIES)
# The word is inner text of the child span of the td with class 'word'
word = soup.findAll('td', attrs={'class': 'word'})[0].findChild().text
# Definitions are just innertext of divs with class definition
definition_divs = soup.findAll('div', attrs={'class': 'definition'})
# BS doesn't unescape hex html encoded characaters, need HTMLParser
parser = HTMLParser()
definitions = [ parser.unescape(div.text) for div in definition_divs ]
# Just use the first definition
return '{0} - {1}'.format(word, definitions[0])
| import requests
from HTMLParser import HTMLParser
from BeautifulSoup import BeautifulSoup
def run(data, settings):
if data['payload'] == 'urban dictionary me':
r = requests.get('http://www.urbandictionary.com/random.php')
soup = BeautifulSoup(r.text,
convertEntities=BeautifulSoup.HTML_ENTITIES)
# The word is inner text of the child span of the td with class 'word'
word = soup.findAll('td', attrs={'class': 'word'})[0].findChild().text
# Definitions are just innertext of divs with class definition
definition_divs = soup.findAll('div', attrs={'class': 'definition'})
# BS doesn't unescape hex html encoded characaters, need HTMLParser
parser = HTMLParser()
definitions = [ parser.unescape(div.text) for div in definition_divs ]
# Just use the first definition
return '{0} - {1}'.format(word, definitions[0])
|
Build fix for Unix-likes other than macOS. | // +build linux dragonfly freebsd netbsd openbsd solaris
package common
import (
"os"
"os/user"
"path/filepath"
)
// GetConfigName gets the correct full path of the configuration file.
func GetConfigName(program, filename string) (string, error) {
u, err := user.Current()
if err != nil {
return "", err
}
dir := filepath.Join(u.HomeDir, "."+program)
if !Exists(dir) {
err := os.MkdirAll(dir, 0700)
if err != nil {
return "", err
}
}
return filepath.Join(dir, filename), nil
}
// GetServerConfigName gets the correct full path of the configuration file for servers.
func GetServerConfigName(program, filename string) (string, error) {
dir := filepath.Join("/etc", program)
if !Exists(dir) {
err := os.MkdirAll(dir, 0700)
if err != nil {
return "", err
}
}
return filepath.Join(dir, filename), nil
}
| // +build linux dragonfly freebsd netbsd openbsd solaris
package common
import (
"os"
"os/user"
"path/filepath"
)
// GetConfigName gets the correct full path of the configuration file.
func GetConfigName(program, filename string) (string, error) {
u, err := user.Current()
if err != nil {
return nil, err
}
dir := filepath.Join(u.HomeDir, "."+program)
if !Exists(dir) {
err := os.MkdirAll(dir, 0700)
if err != nil {
return "", err
}
}
return filepath.Join(dir, filename)
}
// GetServerConfigName gets the correct full path of the configuration file for servers.
func GetServerConfigName(program, filename string) (string, error) {
dir := filepath.Join("/etc", program)
if !Exists(dir) {
err := os.MkdirAll(dir, 0700)
if err != nil {
return "", err
}
}
return filepath.Join(dir, filename)
}
|
Update get_time to use a circuit breaker. | """ app.py """
from flask import Flask, render_template
import pybreaker
import requests
app = Flask(__name__)
time_breaker = pybreaker.CircuitBreaker(fail_max=3, reset_timeout=30)
@time_breaker
def _get_time():
try:
response = requests.get('http://localhost:3001/time', timeout=3.0)
except (requests.exceptions.ConnectionError,
requests.exceptions.Timeout):
# please note that this is an example implementation and is
# dangerously masking the original exception. i highly recommend
# you take the appropriate means to capture/log the exception so
# that you are aware of the underlying problem that is triggering
# the circuit breaker!
raise pybreaker.CircuitBreakerError
return response.json().get('datetime')
def get_time():
try:
return _get_time()
except pybreaker.CircuitBreakerError:
return 'Unavailable'
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
| """ app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
try:
response = requests.get('http://localhost:3001/time', timeout=3.0)
except (requests.exceptions.ConnectionError,
requests.exceptions.Timeout):
return 'Unavailable'
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
|
Copy `hasExports` setting from bpack when bundle is reset
Browserify copies this setting manually in b.reset:
https://github.com/substack/node-browserify/blob/a18657c6f363272ce3c7722528c8ec5f325d0eaf/index.js#L732
Since we replace the bpack instance the `hasExports` value has to be
manually copied from the default bpack
Closes bendrucker/proxyquire-universal#7
@thlorenz this should be released as a patch when you have a chance | 'use strict';
var bpack = require('browser-pack');
var fs = require('fs');
var path = require('path');
var xtend = require('xtend');
var preludePath = path.join(__dirname, 'prelude.js');
var prelude = fs.readFileSync(preludePath, 'utf8');
// This plugin replaces the prelude and adds a transform
var plugin = exports.plugin = function (bfy, opts) {
function replacePrelude() {
var packOpts = {
raw : true, // Added in regular Browserifiy as well
preludePath : preludePath,
prelude : prelude
};
// browserify sets "hasExports" directly on bfy._bpack
bfy._bpack = bpack(xtend(bfy._options, packOpts, {hasExports: bfy._bpack.hasExports}));
// Replace the 'pack' pipeline step with the new browser-pack instance
bfy.pipeline.splice('pack', 1, bfy._bpack);
}
bfy.transform(require('./transform'));
bfy.on('reset', replacePrelude);
replacePrelude();
};
// Maintain support for the old interface
exports.browserify = function (files) {
console.error('You are setting up proxyquireify via the old API which will be deprecated in future versions.');
console.error('It is recommended to use it as a browserify-plugin instead - see the example in the README.');
return require('browserify')(files).plugin(plugin);
};
| 'use strict';
var bpack = require('browser-pack');
var fs = require('fs');
var path = require('path');
var xtend = require('xtend');
var preludePath = path.join(__dirname, 'prelude.js');
var prelude = fs.readFileSync(preludePath, 'utf8');
// This plugin replaces the prelude and adds a transform
var plugin = exports.plugin = function (bfy, opts) {
function replacePrelude() {
var packOpts = {
raw : true, // Added in regular Browserifiy as well
preludePath : preludePath,
prelude : prelude
};
// browserify sets "hasExports" directly on bfy._bpack
bfy._bpack = bpack(xtend(bfy._options, packOpts));
// Replace the 'pack' pipeline step with the new browser-pack instance
bfy.pipeline.splice('pack', 1, bfy._bpack);
}
bfy.transform(require('./transform'));
bfy.on('reset', replacePrelude);
replacePrelude();
};
// Maintain support for the old interface
exports.browserify = function (files) {
console.error('You are setting up proxyquireify via the old API which will be deprecated in future versions.');
console.error('It is recommended to use it as a browserify-plugin instead - see the example in the README.');
return require('browserify')(files).plugin(plugin);
};
|
Change to return 'label' not 'name'. | from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode
class LookupBase(object):
def _name(cls):
app_name = cls.__module__.split('.')[-2].lower()
class_name = cls.__name__.lower()
name = u'%s-%s' % (app_name, class_name)
return name
name = classmethod(_name)
def _url(cls):
return reverse('selectable-lookup', args=[cls.name()])
url = classmethod(_url)
def get_query(self, request):
return []
def get_item_label(self, item):
return smart_unicode(item)
def get_item_id(self, item):
return smart_unicode(item)
def get_item_value(self, item):
return smart_unicode(item)
def format_item(self, item):
return {
'id': self.get_item_id(item),
'value': self.get_item_value(item),
'label': self.get_item_label(item)
}
| from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode
class LookupBase(object):
def _name(cls):
app_name = cls.__module__.split('.')[-2].lower()
class_name = cls.__name__.lower()
name = u'%s-%s' % (app_name, class_name)
return name
name = classmethod(_name)
def _url(cls):
return reverse('selectable-lookup', args=[cls.name()])
url = classmethod(_url)
def get_query(self, request):
return []
def get_item_name(self, item):
return smart_unicode(item)
def get_item_id(self, item):
return smart_unicode(item)
def get_item_value(self, item):
return smart_unicode(item)
def format_item(self, item):
return {
'id': self.get_item_id(item),
'value': self.get_item_value(item),
'name': self.get_item_name(item)
}
|
Add basic template for async action creators | export const ADD_ITEM = 'ADD_ITEM';
export const COMPLETE_ITEM = 'COMPLETE_ITEM';
export function addItem(text) {
return {
type: ADD_ITEM,
value: text
};
}
export function completeItem(index) {
return {
type: COMPLETE_ITEM,
id: index
};
}
//========== async ==============================
export const SEND_NEW_ITEM = 'SEND_NEW_ITEM';
export const REQUEST_ITEMS = 'REQUEST_ITEMS';
export const RECEIVE_ITEMS = 'RECEIVE_ITEMS';
export function sendNewItem(text) {
return {
type: SEND_NEW_ITEM,
value: text
};
}
export function requestItems() {
return {
type: REQUEST_ITEMS
};
}
export function receiveItems(items) {
return {
type: RECEIVE_ITEMS,
itemList: items,
receivedAt: Date.now()
};
}
// ===== thunk action creators ==================
export function sendNewItemAPI(text) {
return dispatch => {
dispatch(sendNewItem(text));
// send item to server
}
}
export function requestItemsAPI() {
return dispatch => {
dispatch(requestItems());
// return fetch(`http://localhost:5000/api`)
// .then(response => response.json())
// .then(json => dispatch(receiveItems(json)));
};
}
| export const ADD_ITEM = 'ADD_ITEM';
export const COMPLETE_ITEM = 'COMPLETE_ITEM';
export function addItem(text) {
return {
type: ADD_ITEM,
value: text
};
}
export function completeItem(index) {
return {
type: COMPLETE_ITEM,
id: index
};
}
//========== async ==============================
export const SEND_NEW_ITEM = 'SEND_NEW_ITEM';
export const REQUEST_ITEMS = 'REQUEST_ITEMS';
export const RECEIVE_ITEMS = 'RECEIVE_ITEMS';
export function sendNewItem(text) {
return {
type: SEND_NEW_ITEM,
value: text
};
}
export function requestItems() {
return {
type: REQUEST_ITEMS
};
}
export function receiveItems(items) {
return {
type: RECEIVE_ITEMS,
itemList: items,
receivedAt: Date.now()
};
}
|
Update project URL to readthedocs | #!/usr/bin/env python
import nirvana
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
setup(
name='nirvana',
version=nirvana.__version__,
description=('Library for interacting with the Nirvana task manager '
'(nirvanahq.com)'),
long_description=long_description,
author='Nick Wilson',
author_email='nick@njwilson.net',
url='http://nirvana-python.readthedocs.org',
license='MIT',
packages=['nirvana'],
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| #!/usr/bin/env python
import nirvana
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme:
long_description = readme.read()
setup(
name='nirvana',
version=nirvana.__version__,
description=('Library for interacting with the Nirvana task manager '
'(nirvanahq.com)'),
long_description=long_description,
author='Nick Wilson',
author_email='nick@njwilson.net',
url='http://github.com/njwilson/nirvana-python',
license='MIT',
packages=['nirvana'],
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Use a cryptographically secure PRNG in random_string().
By default python uses a non-CS PRNG, so with some analysis, "random_string"s could be predicted. | __author__ = 'zifnab'
import string
from passlib.hash import sha512_crypt
from random import SystemRandom
import database
from flask_login import login_user
_random = SystemRandom()
def random_string(size=10, chars=string.ascii_letters + string.digits):
return ''.join(_random.choice(chars) for x in range(size))
def create_user(**kwargs):
username = kwargs.get('username')
password = kwargs.get('password')
email = kwargs.get('email')
hash = sha512_crypt.encrypt(password)
user = database.User(username=username,
hash=hash,
email=email)
if database.User.objects().count() == 0:
user.admin = True
user.save()
login_user(user)
def authenticate_user(username, password):
user = database.User.objects(username__iexact=username).first()
if user is None:
return None
if (sha512_crypt.verify(password, user.hash)):
return user
else:
return None
def lookup_user(username):
user = database.User.objects(username__iexact=username).first()
return user | __author__ = 'zifnab'
import string
from passlib.hash import sha512_crypt
import database
from flask_login import login_user
def random_string(size=10, chars=string.ascii_letters + string.digits):
import random
return ''.join(random.choice(chars) for x in range(size))
def create_user(**kwargs):
username = kwargs.get('username')
password = kwargs.get('password')
email = kwargs.get('email')
hash = sha512_crypt.encrypt(password)
user = database.User(username=username,
hash=hash,
email=email)
if database.User.objects().count() == 0:
user.admin = True
user.save()
login_user(user)
def authenticate_user(username, password):
user = database.User.objects(username__iexact=username).first()
if user is None:
return None
if (sha512_crypt.verify(password, user.hash)):
return user
else:
return None
def lookup_user(username):
user = database.User.objects(username__iexact=username).first()
return user |
Downgrade tastypie to test-only dependency | """
Package configuration
"""
# pylint:disable=no-name-in-module, import-error
from distutils.core import setup
from setuptools import find_packages
setup(
name='IXWSAuth',
version='0.1.1',
author='Infoxchanhe Australia dev team',
author_email='devs@infoxchange.net.au',
packages=find_packages(),
url='http://pypi.python.org/pypi/IXWSAuth/',
license='MIT',
description='Authentication libraries for IX web services',
long_description=open('README').read(),
install_requires=(
'Django >= 1.4.0',
'IXDjango >= 0.1.1',
),
tests_require=(
'aloe',
'django-tastypie',
'mock',
'pep8',
'pylint',
'pylint-mccabe',
)
)
| """
Package configuration
"""
# pylint:disable=no-name-in-module, import-error
from distutils.core import setup
from setuptools import find_packages
setup(
name='IXWSAuth',
version='0.1.1',
author='Infoxchanhe Australia dev team',
author_email='devs@infoxchange.net.au',
packages=find_packages(),
url='http://pypi.python.org/pypi/IXWSAuth/',
license='MIT',
description='Authentication libraries for IX web services',
long_description=open('README').read(),
install_requires=(
'Django >= 1.4.0',
'django-tastypie',
'IXDjango >= 0.1.1',
),
tests_require=(
'aloe',
'mock',
'pep8',
'pylint',
'pylint-mccabe',
)
)
|
Allow binary_japan to have dir | module.exports = {
all: {
options: {
separator: ';',
},
files: {
'dist/js/binary.js': [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/javascript/lib/highstock/highstock-exporting.js',
'src/javascript/lib/moment/moment.js',
'src/javascript/lib/**/*.js',
'src/javascript/autogenerated/idd_codes.js',
'src/javascript/autogenerated/texts.js',
'src/javascript/autogenerated/*.js',
'src/javascript/binary/base/*.js',
'src/javascript/binary/**/*.js',
'src/javascript/binary_japan/**/*.js'
]
}
}
};
| module.exports = {
all: {
options: {
separator: ';',
},
files: {
'dist/js/binary.js': [
'src/javascript/lib/jquery.js',
'src/javascript/lib/highstock/highstock.js',
'src/javascript/lib/highstock/highstock-exporting.js',
'src/javascript/lib/moment/moment.js',
'src/javascript/lib/**/*.js',
'src/javascript/autogenerated/idd_codes.js',
'src/javascript/autogenerated/texts.js',
'src/javascript/autogenerated/*.js',
'src/javascript/binary/base/*.js',
'src/javascript/binary/**/*.js',
'src/javascript/binary_japan/*.js'
]
}
}
};
|
Add requirement of argparse on old python | # Copyright 2012 Loop Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup
import sys
from skal import __version__
requirements = []
if sys.version_info < (2, 7):
requirements.append('argparse')
setup(
name = "skal",
version = __version__,
description = "Class based command line wrapper",
author = "Max Persson",
author_email = "max@looplab.se",
url = "https://github.com/looplab/skal",
license = "Apache License 2.0",
py_modules = ["skal"],
install_requires = requirements,
classifiers = [
"Development Status :: 2 - Pre-Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: User Interfaces",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| # Copyright 2012 Loop Lab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup
from skal import __version__
setup(
name = "skal",
version = __version__,
description = "Class based command line wrapper",
author = "Max Persson",
author_email = "max@looplab.se",
url = "https://github.com/looplab/skal",
license = "Apache License 2.0",
py_modules = ["skal"],
classifiers = [
"Development Status :: 2 - Pre-Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: User Interfaces",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
Fix the runner test where it wasn't setting outdir. | # Copyright (c) 2014, Matt Layman
import tempfile
import unittest
from tap import TAPTestRunner
from tap.runner import TAPTestResult
class TestTAPTestRunner(unittest.TestCase):
def test_has_tap_test_result(self):
runner = TAPTestRunner()
self.assertEqual(runner.resultclass, TAPTestResult)
def test_runner_uses_outdir(self):
"""Test that the test runner sets the TAPTestResult OUTDIR so that TAP
files will be written to that location.
Setting class attributes to get the right behavior is a dirty hack, but
the unittest classes aren't very extensible.
"""
# Save the previous outdir in case **this** execution was using it.
previous_outdir = TAPTestResult.OUTDIR
outdir = tempfile.mkdtemp()
TAPTestRunner.set_outdir(outdir)
self.assertEqual(outdir, TAPTestResult.OUTDIR)
TAPTestResult.OUTDIR = previous_outdir
| # Copyright (c) 2014, Matt Layman
import tempfile
import unittest
from tap import TAPTestRunner
from tap.runner import TAPTestResult
class TestTAPTestRunner(unittest.TestCase):
def test_has_tap_test_result(self):
runner = TAPTestRunner()
self.assertEqual(runner.resultclass, TAPTestResult)
def test_runner_uses_outdir(self):
"""Test that the test runner sets the TAPTestResult OUTDIR so that TAP
files will be written to that location.
Setting class attributes to get the right behavior is a dirty hack, but
the unittest classes aren't very extensible.
"""
# Save the previous outdir in case **this** execution was using it.
previous_outdir = TAPTestResult
outdir = tempfile.mkdtemp()
TAPTestRunner.set_outdir(outdir)
self.assertEqual(outdir, TAPTestResult.OUTDIR)
TAPTestResult.OUTDIR = previous_outdir
|
Refactor loadJson so it can be tested. | define(['utils/ajax'], function (Ajax) {
function LoadJson () {
this.ajax = new Ajax();
}
/**
* Loads a JSON File and passes the content to a callback function
* @param {string} jsonFile The location of the JSON file in which to load.
* @param {Function} callback A function in which to run on load complete of file.
*
* @example
* var file = 'http://example.com/pokemon.json',
* callback = function (response) {
* console.log(response);
* };
* // Will console.log the entire contents of the pokemon.json file loaded.
*/
LoadJson.prototype.load = function (jsonFile, callback) {
this.ajax.onload = function (xhr) {
try {
var response = JSON.parse(xhr.responseText);
callback(response);
} catch (error) {}
};
this.ajax.load(jsonFile);
};
return LoadJson;
});
| define(['utils/ajax'], function (Ajax) {
/**
* Loads a JSON File and passes the content to a callback function
* @param {string} jsonFile The location of the JSON file in which to load.
* @param {Function} callback A function in which to run on load complete of file.
*
* @example
* var file = 'http://example.com/pokemon.json',
* callback = function (response) {
* console.log(response);
* };
* // Will console.log the entire contents of the pokemon.json file loaded.
*/
return function (jsonFile, callback) {
var ajax = new Ajax();
ajax.onload = function (xhr) {
try {
var response = JSON.parse(xhr.responseText);
callback(response);
} catch (error) {}
};
ajax.load(jsonFile);
return ajax;
};
});
|
Bring the forum to the foreground
The default landing page is now the forum, to hopefully encourage people to use it | from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView,RedirectView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', RedirectView.as_view(pattern_name='forum:index'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
| from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
# url(r'^$', 'akwriters.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('resources', TemplateView.as_view(template_name='resources.html'), name='resources'),
path('events/', include('events.urls', namespace='events')),
#path(r'^account/', include('account.urls', namespace='account')),
path('alerts/', include('alerts.urls', namespace='alerts')),
path('api/', include('api.urls', namespace='api')),
path('auth/', include('passwordless.urls', namespace='auth')),
path('chat/', include('chat.urls', namespace='chat')),
path('contact/', include('contact.urls', namespace='contact')),
path('favicon/', include('favicon.urls', namespace='favicon')),
path('policies/', include('policies.urls', namespace='policies')),
path('tools/', include('tools.urls', namespace='tools')),
path('forum/', include('forum.urls', namespace='forum')),
path('admin/', admin.site.urls),
]
|
Solve problem with test, method need to throws unchecked exception | package es.ganchix.morphia.utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.mongodb.morphia.utils.ReflectionUtils;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.IOException;
/**
* Created by Rafael Ríos on 5/05/17.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(ReflectionUtils.class)
public class MorphiaFailUtilsTest {
private final String PACKAGE_NAME = "es.ganchix.morphia.utils.context.normal";
@Test(expected = Exception.class)
public void testCallGetClassesWithFail_ShouldReturnAException() throws IOException, ClassNotFoundException {
PowerMockito.mockStatic(ReflectionUtils.class);
BDDMockito.given(ReflectionUtils.getClasses(PACKAGE_NAME, true)).willThrow(new RuntimeException());
MorphiaUtils.getClasses(PACKAGE_NAME);
}
}
| package es.ganchix.morphia.utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.mongodb.morphia.utils.ReflectionUtils;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.IOException;
/**
* Created by Rafael Ríos on 5/05/17.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(ReflectionUtils.class)
public class MorphiaFailUtilsTest {
private final String PACKAGE_NAME = "es.ganchix.morphia.utils.context.normal";
@Test(expected = Exception.class)
public void testCallGetClassesWithFail_ShouldReturnAException() throws IOException, ClassNotFoundException {
PowerMockito.mockStatic(ReflectionUtils.class);
BDDMockito.given(ReflectionUtils.getClasses(PACKAGE_NAME, true)).willThrow(new Exception());
MorphiaUtils.getClasses(PACKAGE_NAME);
}
}
|
Fix revision exclude dist generation | var inherits = require('util').inherits,
Task = require('./Task'),
RevAll = require('gulp-rev-all'),
_ = require('lodash'),
gulp = require('gulp'),
Promise = require('bluebird');
var RevTask = function (buildHelper) {
Task.call(this, buildHelper);
};
inherits(RevTask, Task);
RevTask.prototype.command = "rev";
RevTask.prototype.availableToModule = false;
RevTask.prototype.action = function () {
if (!this._buildHelper.isRelease()) return Promise.resolve();
if (this._buildHelper.options.revisionExclude === "*") {
return gulp.src(this._buildHelper.getTemporaryDirectory() + '**')
.pipe(gulp.dest(this._buildHelper.getDistDirectory()));
}
var excludedFiles = _.union(
['favicon.ico', 'index.html'],
_.map(this._buildHelper.options.revisionExclude, function (rule) {
return rule.regexp ? new RegExp(rule.pattern) : rule.pattern;
}));
var revTransform = new RevAll({
dontRenameFile: excludedFiles,
dontUpdateReference: excludedFiles
});
return gulp.src(this._buildHelper.getTemporaryDirectory() + '**')
.pipe(revTransform.revision())
.pipe(gulp.dest(this._buildHelper.getDistDirectory()));
};
module.exports = RevTask; | var inherits = require('util').inherits,
Task = require('./Task'),
RevAll = require('gulp-rev-all'),
_ = require('lodash'),
gulp = require('gulp'),
Promise = require('bluebird');
var RevTask = function (buildHelper) {
Task.call(this, buildHelper);
};
inherits(RevTask, Task);
RevTask.prototype.command = "rev";
RevTask.prototype.availableToModule = false;
RevTask.prototype.action = function () {
if (!this._buildHelper.isRelease() || this._buildHelper.options.revisionExclude === "*") return Promise.resolve();
var excludedFiles = _.union(
['favicon.ico', 'index.html'],
_.map(this._buildHelper.options.revisionExclude, function (rule) {
return rule.regexp ? new RegExp(rule.pattern) : rule.pattern;
}));
var revTransform = new RevAll({
dontRenameFile: excludedFiles,
dontUpdateReference: excludedFiles
});
return gulp.src(this._buildHelper.getTemporaryDirectory() + '**')
.pipe(revTransform.revision())
.pipe(gulp.dest(this._buildHelper.getDistDirectory()));
};
module.exports = RevTask; |
Reset the WSU API key so the tests never make a real connection and will error if it tries to. | <?php
namespace Tests;
use Faker\Factory;
class TestCase extends \Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
/**
* Ran before every test.
*/
public function setUp()
{
parent::setUp();
// Set these super globals since some packages rely on them
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['HTTP_HOST'] = '';
$_SERVER['REQUEST_URI'] = '';
// Force the top menu to be enabled for now since the tests are written specifically for this condition
config(['app.top_menu_enabled' => true]);
// Reset the WSU API key so we never make real connections to the API
config(['app.wsu_api_key' => '']);
// Create a new faker that every test can use
$this->faker = (new Factory)->create();
}
}
| <?php
namespace Tests;
use Faker\Factory;
class TestCase extends \Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
/**
* Ran before every test.
*/
public function setUp()
{
parent::setUp();
// Set these super globals since some packages rely on them
$_SERVER['HTTP_USER_AGENT'] = '';
$_SERVER['HTTP_HOST'] = '';
$_SERVER['REQUEST_URI'] = '';
// Force the top menu to be enabled for now since the tests are written specifically for this condition
config(['app.top_menu_enabled' => true]);
// Create a new faker that every test can use
$this->faker = (new Factory)->create();
}
}
|
Fix Help not recognizing user input. | package musician101.itembank.commands.ibcommand;
import musician101.itembank.ItemBank;
import musician101.itembank.lib.Constants;
import org.bukkit.command.CommandSender;
/**
* The code used when the Help argument is used in the ItemBank command.
*
* @author Musician101
*/
public class HelpCommand
{
public static boolean execute(ItemBank plugin, CommandSender sender, String[] args)
{
if (args.length == 1)
sender.sendMessage(Constants.HELP_LIST);
else
{
String cmd = args[1].toLowerCase();
if (cmd.equals(Constants.ACCOUNT_CMD))
sender.sendMessage(Constants.ACCOUNT_HELP);
else if (cmd.equals(Constants.DEPOSIT_CMD))
sender.sendMessage(Constants.DEPOSIT_HELP);
else if (cmd.equals(Constants.IA_CMD))
sender.sendMessage(Constants.IA_HELP);
else if (cmd.equals(Constants.PURGE_CMD))
sender.sendMessage(Constants.PURGE_HELP);
else if (cmd.equals(Constants.WITHDRAW_CMD))
sender.sendMessage(Constants.WITHDRAW_HELP);
else
sender.sendMessage(Constants.PREFIX + "Error: Command not recognized.");
}
return true;
}
}
| package musician101.itembank.commands.ibcommand;
import musician101.itembank.ItemBank;
import musician101.itembank.lib.Constants;
import org.bukkit.command.CommandSender;
/**
* The code used when the Help argument is used in the ItemBank command.
*
* @author Musician101
*/
public class HelpCommand
{
public static boolean execute(ItemBank plugin, CommandSender sender, String[] args)
{
if (args.length == 1)
sender.sendMessage(Constants.HELP_LIST);
else
{
String cmd = args[1].toLowerCase();
if (cmd == Constants.ACCOUNT_CMD)
sender.sendMessage(Constants.ACCOUNT_HELP);
else if (cmd == Constants.DEPOSIT_CMD)
sender.sendMessage(Constants.DEPOSIT_HELP);
else if (cmd == Constants.IA_CMD)
sender.sendMessage(Constants.IA_HELP);
else if (cmd == Constants.PURGE_CMD)
sender.sendMessage(Constants.PURGE_HELP);
else if (cmd == Constants.WITHDRAW_CMD)
sender.sendMessage(Constants.WITHDRAW_HELP);
else
sender.sendMessage(Constants.PREFIX + "Error: Command not recognized.");
}
return true;
}
}
|
Use same styling for "Run" button as is used by buttons in Sphinx. | /*global jQuery, document */
/*jslint nomen: true, unparam: true, bitwise: true*/
(function ($) {
"use strict";
var run, register_click_event;
run = function (event) {
$('#my_form').remove();
var button = $(event.currentTarget),
code_block = button.prev();
button.after('<div id="my_form"></div>');
eval(code_block.text());
};
register_click_event = function (node) {
var button = $('<button class="btn btn-neutral coderunner">Run</button>');
node.after(button);
button.click(run);
};
$(document).ready(function () {
$.each(
$('.highlight-javascript').add($('.highlight-js')),
function (index, node) {
register_click_event($(node));
}
);
});
}(jQuery));
| /*global jQuery, document */
/*jslint nomen: true, unparam: true, bitwise: true*/
(function ($) {
"use strict";
var run, register_click_event;
run = function (event) {
$('#my_form').remove();
var button = $(event.currentTarget),
code_block = button.prev();
button.after('<div id="my_form"></div>');
eval(code_block.text());
};
register_click_event = function (node) {
var button = $('<button class="coderunner">Run</button>');
node.after(button);
button.click(run);
};
$(document).ready(function () {
$.each(
$('.highlight-javascript').add($('.highlight-js')),
function (index, node) {
register_click_event($(node));
}
);
});
}(jQuery));
|
Set YKMAN_OATH_DEVICE_SERIAL to select Yubikey
This change enables setting YKMAN_OATH_DEVICE_SERIAL to select a
particular Yubikey if more than one is attached to the device. It does
this by reading the serial from the env var, and adding the `--device
<serial>` to the `ykman` command. | package prompt
import (
"fmt"
"log"
"os"
"os/exec"
"strings"
)
// YkmanProvider runs ykman to generate a OATH-TOTP token from the Yubikey device
// To set up ykman, first run `ykman oath add`
func YkmanMfaProvider(mfaSerial string) (string, error) {
args := []string{}
yubikeyOathCredName := os.Getenv("YKMAN_OATH_CREDENTIAL_NAME")
if yubikeyOathCredName == "" {
yubikeyOathCredName = mfaSerial
}
// Get the serial number of the yubikey device to use.
yubikeyDeviceSerial := os.Getenv("YKMAN_OATH_DEVICE_SERIAL")
if yubikeyDeviceSerial != "" {
// If the env var was set, extend args to support passing the serial.
args = append(args, "--device", yubikeyDeviceSerial)
}
// Add the rest of the args as usual.
args = append(args, "oath", "code", "--single", yubikeyOathCredName)
log.Printf("Fetching MFA code using `ykman %s`", strings.Join(args, " "))
cmd := exec.Command("ykman", args...)
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("ykman: %w", err)
}
return strings.TrimSpace(string(out)), nil
}
func init() {
Methods["ykman"] = YkmanMfaProvider
}
| package prompt
import (
"fmt"
"log"
"os"
"os/exec"
"strings"
)
// YkmanProvider runs ykman to generate a OATH-TOTP token from the Yubikey device
// To set up ykman, first run `ykman oath add`
func YkmanMfaProvider(mfaSerial string) (string, error) {
yubikeyOathCredName := os.Getenv("YKMAN_OATH_CREDENTIAL_NAME")
if yubikeyOathCredName == "" {
yubikeyOathCredName = mfaSerial
}
log.Printf("Fetching MFA code using `ykman oath code --single %s`", yubikeyOathCredName)
cmd := exec.Command("ykman", "oath", "code", "--single", yubikeyOathCredName)
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("ykman: %w", err)
}
return strings.TrimSpace(string(out)), nil
}
func init() {
Methods["ykman"] = YkmanMfaProvider
}
|
Enable React devtools by exposing React (setting window.React) | /**
* This file is provided by Facebook for testing and evaluation purposes
* only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @jsx React.DOM
*/
// This file bootstraps the entire application.
var ChatApp = require('./components/ChatApp.react');
var ChatExampleData = require('./ChatExampleData');
var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils');
var React = require('react');
window.React = React; // export for http://fb.me/react-devtools
ChatExampleData.init(); // load example data into localstorage
ChatWebAPIUtils.getAllMessages();
React.renderComponent(
<ChatApp />,
document.getElementById('react')
);
| /**
* This file is provided by Facebook for testing and evaluation purposes
* only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @jsx React.DOM
*/
// This file bootstraps the entire application.
var ChatApp = require('./components/ChatApp.react');
var ChatExampleData = require('./ChatExampleData');
var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils');
var React = require('react');
ChatExampleData.init(); // load example data into localstorage
ChatWebAPIUtils.getAllMessages();
React.renderComponent(
<ChatApp />,
document.getElementById('react')
);
|
refactor: Use resolveRule instead of resolveRules | var url = require('url');
var properties = require('../lib/properties');
var rules = require('../lib/proxy').rules;
var util = require('../lib/util');
module.exports = function(req, res) {
var tunnelUrl = properties.get('showHostIpInResHeaders') ? req.query.url : null;
if (typeof tunnelUrl != 'string') {
tunnelUrl = null;
} else if (tunnelUrl) {
tunnelUrl = url.parse(tunnelUrl);
tunnelUrl = tunnelUrl.host ? 'https://' + tunnelUrl.host : null;
}
if (!tunnelUrl) {
return res.json({ec: 2, em: 'server busy'});
}
var rule = rules.resolveRule(tunnelUrl);
if (rule) {
var _url = util.setProtocol(util.rule.getMatcher(rule), true);
if (/^https:/i.test(_url)) {
tunnelUrl = _url;
}
}
rules.resolveHost(tunnelUrl, function(err, host) {
if (err) {
res.json({ec: 2, em: 'server busy'});
} else {
res.json({ec: 0, em: 'success', host: host});
}
});
};
| var url = require('url');
var properties = require('../lib/properties');
var rules = require('../lib/proxy').rules;
var util = require('../lib/util');
module.exports = function(req, res) {
var tunnelUrl = properties.get('showHostIpInResHeaders') ? req.query.url : null;
if (typeof tunnelUrl != 'string') {
tunnelUrl = null;
} else if (tunnelUrl) {
tunnelUrl = url.parse(tunnelUrl);
tunnelUrl = tunnelUrl.host ? 'https://' + tunnelUrl.host : null;
}
if (!tunnelUrl) {
return res.json({ec: 2, em: 'server busy'});
}
var _rules = rules.resolveRules(tunnelUrl);
if (_rules.rule) {
var _url = util.setProtocol(util.rule.getMatcher(_rules.rule), true);
if (/^https:/i.test(_url)) {
tunnelUrl = _url;
}
}
rules.resolveHost(tunnelUrl, function(err, host) {
if (err) {
res.json({ec: 2, em: 'server busy'});
} else {
res.json({ec: 0, em: 'success', host: host});
}
});
};
|
Handle logging unicode messages in python2.
Former-commit-id: 257d94eb71d5597ff52a18ec1530d73496901ef4 | import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
| import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
|
Add a bit more help text for Node v8+
In those versions, it doesn't give you the link to open the debugger (just a link to a help article on the Node website). | /**
* Module dependencies
*/
var path = require('path');
var Womb = require('child_process');
var CaptainsLog = require('captains-log');
var chalk = require('chalk');
var Sails = require('../lib/app');
/**
* `sails inspect`
*
* Attach the Node inspector and lift a Sails app.
* You can then use Node inspector to debug your app as it runs.
*
*/
module.exports = function(cmd) {
var extraArgs = cmd.parent.rawArgs.slice(3);
var log = CaptainsLog();
// Use the app's local Sails in `node_modules` if one exists
// But first make sure it'll work...
var appPath = process.cwd();
var pathToSails = path.resolve(appPath, '/node_modules/sails');
if (!Sails.isLocalSailsValid(pathToSails, appPath)) {
// otherwise, use the currently-running instance of Sails
pathToSails = path.resolve(__dirname, './sails.js');
}
console.log();
log.info('Running app in inspect mode...');
if (process.version[1] >= 8) {
log.info('In Google Chrome, go to chrome://inspect for interactive debugging.');
log.info('For other options, see the link below.');
}
log.info(chalk.grey('( to exit, type ' + '<CTRL>+<C>' + ' )'));
console.log();
// Spin up child process for Sails
Womb.spawn('node', ['--inspect', pathToSails, 'lift'].concat(extraArgs), {
stdio: 'inherit'
});
};
| /**
* Module dependencies
*/
var path = require('path');
var Womb = require('child_process');
var CaptainsLog = require('captains-log');
var chalk = require('chalk');
var Sails = require('../lib/app');
/**
* `sails inspect`
*
* Attach the Node inspector and lift a Sails app.
* You can then use Node inspector to debug your app as it runs.
*
*/
module.exports = function(cmd) {
var extraArgs = cmd.parent.rawArgs.slice(3);
var log = CaptainsLog();
// Use the app's local Sails in `node_modules` if one exists
// But first make sure it'll work...
var appPath = process.cwd();
var pathToSails = path.resolve(appPath, '/node_modules/sails');
if (!Sails.isLocalSailsValid(pathToSails, appPath)) {
// otherwise, use the currently-running instance of Sails
pathToSails = path.resolve(__dirname, './sails.js');
}
console.log();
log.info('Running app in inspect mode...');
log.info(chalk.grey('( to exit, type ' + '<CTRL>+<C>' + ' )'));
console.log();
// Spin up child process for Sails
Womb.spawn('node', ['--inspect', pathToSails, 'lift'].concat(extraArgs), {
stdio: 'inherit'
});
};
|
Add some tests, they're commented out right now. Things work! | // Source Model
AV.Source = Backbone.Model.extend({
url: 'php/redirect.php/source',
defaults: {
name: '',
type: 'raw',
contentType: 'txt',
data: ''
},
});
// Source Model Tests
// test_Source = new AV.Source({
// name: 'The Wind and the Rain',
// type: 'raw',
// contentType: 'txt',
// data: "When that I was and a little tiny boy, with a hey-ho, the wind and "+
// the rain, a foolish thing was but a toy, for the rain it raineth every day."
// });
// alert('potato');
// test_Source.save( {
// success: function () {
// alert('success');
// },
// error: function(d){
// alert('everything is terrible');
// }
// });
// other_test = new AV.Source();
// other_test.url = 'php/redirect.php/Source/15';
// other_test.fetch();
// alert(other_test.name);
// Source Model End
| // Source Model
AV.source = Backbone.Model.extend({
url: 'php/redirect.php/source',
defaults: {
name: '',
type: 'raw',
contentType: 'txt',
data: ''
},
});
// Source Model Tests
// test_source = new AV.source({
// name: 'The Wind and the Rain',
// type: 'raw',
// contentType: 'txt',
// data: "When that I was and a little tiny boy, with a hey-ho, the wind and the rain, a foolish thing was but a toy, for the rain it raineth every day."
// });
// alert('potato');
// test_source.save( {
// success: function () {
// alert('success');
// },
// error: function(d){
// alert('everything is terrible');
// }
// });
other_test = new AV.source();
other_test.url = 'php/redirect.php/source/15';
other_test.fetch();
// Source Model End
|
Set minimum version for dependencies. | from setuptools import setup
import os
version = 0.4
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
url='http://github.com/fschulze/mr.awsome',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto >= 1.9b',
'Fabric >= 0.9.0',
],
) | from setuptools import setup
import os
version = 0.4
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
url='http://github.com/fschulze/mr.awsome',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
) |
Make default version target graph build with new builder
Reviewed By: philipjameson
shipit-source-id: f2103da595 | /*
* Copyright 2018-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.versions;
import com.facebook.buck.util.randomizedtrial.WithProbability;
/**
* Whether to use the {@link com.facebook.buck.versions.AsyncVersionedTargetGraphBuilder} or {@link
* com.facebook.buck.versions.ParallelVersionedTargetGraphBuilder}
*/
public enum VersionTargetGraphMode implements WithProbability {
ENABLED(0.5),
DISABLED(0.5),
EXPERIMENT(0.0),
;
public static final VersionTargetGraphMode DEFAULT = ENABLED;
private final double probability;
VersionTargetGraphMode(double probability) {
this.probability = probability;
}
@Override
public double getProbability() {
return probability;
}
}
| /*
* Copyright 2018-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.versions;
import com.facebook.buck.util.randomizedtrial.WithProbability;
/**
* Whether to use the {@link com.facebook.buck.versions.AsyncVersionedTargetGraphBuilder} or {@link
* com.facebook.buck.versions.ParallelVersionedTargetGraphBuilder}
*/
public enum VersionTargetGraphMode implements WithProbability {
ENABLED(0.5),
DISABLED(0.5),
EXPERIMENT(0.0),
;
public static final VersionTargetGraphMode DEFAULT = DISABLED;
private final double probability;
VersionTargetGraphMode(double probability) {
this.probability = probability;
}
@Override
public double getProbability() {
return probability;
}
}
|
Fix Behat scenarios and few final adjustments to reviews and associations | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Repository;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Review\Model\ReviewInterface;
/**
* @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
*/
interface ProductReviewRepositoryInterface extends RepositoryInterface
{
/**
* @param int $productId
* @param int $count
*
* @return ReviewInterface[]
*/
public function findLatestByProductId($productId, $count);
/**
* @param string $slug
* @param string $locale
* @param ChannelInterface $channel
*
* @return ReviewInterface[]
*/
public function findAcceptedByProductSlugAndChannel($slug, $locale, ChannelInterface $channel);
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Repository;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Review\Model\ReviewInterface;
/**
* @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
*/
interface ProductReviewRepositoryInterface extends RepositoryInterface
{
/**
* @param int $count
* @param int $productId
*
* @return ReviewInterface[]
*/
public function findLatestByProductId($count, $productId);
/**
* @param string $slug
* @param string $locale
* @param ChannelInterface $channel
*
* @return ReviewInterface[]
*/
public function findAcceptedByProductSlugAndChannel($slug, $locale, ChannelInterface $channel);
}
|
Remove dead code from test
Signed-off-by: Don MacMillen <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@macmillen.net> | from openroad import Design, Tech
import helpers
import gpl_aux
tech = Tech()
tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib")
tech.readLef("./nangate45.lef")
design = Design(tech)
design.readDef("./simple01-td.def")
design.evalTclString("create_clock -name core_clock -period 2 clk")
design.evalTclString("set_wire_rc -signal -layer metal3")
design.evalTclString("set_wire_rc -clock -layer metal5")
gpl_aux.global_placement(design, timing_driven=True)
design.evalTclString("estimate_parasitics -placement")
design.evalTclString("report_worst_slack")
def_file = helpers.make_result_file("simple01-td.def")
design.writeDef(def_file)
helpers.diff_files(def_file, "simple01-td.defok")
| from openroad import Design, Tech
import helpers
import gpl_aux
tech = Tech()
tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib")
tech.readLef("./nangate45.lef")
design = Design(tech)
design.readDef("./simple01-td.def")
design.evalTclString("create_clock -name core_clock -period 2 clk")
design.evalTclString("set_wire_rc -signal -layer metal3")
design.evalTclString("set_wire_rc -clock -layer metal5")
gpl_aux.global_placement(design, timing_driven=True)
design.evalTclString("estimate_parasitics -placement")
design.evalTclString("report_worst_slack")
def_file = helpers.make_result_file("simple01-td.def")
design.writeDef(def_file)
helpers.diff_files(def_file, "simple01-td.defok")
# source helpers.tcl
# set test_name simple01-td
# read_liberty ./library/nangate45/NangateOpenCellLibrary_typical.lib
# read_lef ./nangate45.lef
# read_def ./$test_name.def
# create_clock -name core_clock -period 2 clk
# set_wire_rc -signal -layer metal3
# set_wire_rc -clock -layer metal5
# global_placement -timing_driven
# # check reported wns
# estimate_parasitics -placement
# report_worst_slack
# set def_file [make_result_file $test_name.def]
# write_def $def_file
# diff_file $def_file $test_name.defok
|
Make sent_by a foreign key | <?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('docusign_envelopes', static function (Blueprint $table): void {
$table->unsignedInteger('sent_by')->nullable();
$table->foreign('sent_by')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('docusign_envelopes', static function (Blueprint $table): void {
$table->dropColumn('sent_by');
});
}
};
| <?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('docusign_envelopes', static function (Blueprint $table): void {
$table->unsignedInteger('sent_by')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('docusign_envelopes', static function (Blueprint $table): void {
$table->dropColumn('sent_by');
});
}
};
|
Comment on resource handler overrides | 'use strict'
// setup
import test from 'ava'
// test something
test.todo('testSomething')
/* API
const pattyOpts = {port: 8081, secret: 'someSecureString', logpath: '/logs'}
const patty = require('paternity')
const handleIt = require('./some-other-resource') // same as resource obj
await patty.init(pattyOpts)
const someResource = await patty.register('some-resource')
const someOtherResource = await patty.register('some-other-resource', handleIt)
await patty.start()
*/
/* RESOURCE OBJECT
{
name: 'some-resource',
search: (req, res) => Promise.resolve('done'),
create: (req, res) => Promise.resolve('done'),
read: (req, res) => Promise.resolve('done'),
update: (req, res) => Promise.resolve('done'),
delete: (req, res) => Promise.resolve('done')
}
*/
/* GLOBAL HELPERS
const logger = patty.logger // {debug, info, warn, fatal}
let record = await patty._find('some-resource', {id: 1})
let records = await patty._findAll('some-resource', {name: 'jerry'})
let newRecord = await patty._create('some-resource', {name: 'jimmy'})
let updatedRecord = await patty._save('some-resource', {id: 1, name: 'john'})
*/
| 'use strict'
// setup
import test from 'ava'
// test something
test.todo('testSomething')
/* API
const pattyOpts = {port: 8081, secret: 'someSecureString', logpath: '/logs'}
const patty = require('paternity')
const handleIt = require('./some-other-resource')
await patty.init(pattyOpts)
const someResource = await patty.register('some-resource')
const someOtherResource = await patty.register('some-other-resource', handleIt)
await patty.start()
*/
/* RESOURCE OBJECT
{
name: 'some-resource',
search: (req, res) => Promise.resolve('done'),
create: (req, res) => Promise.resolve('done'),
read: (req, res) => Promise.resolve('done'),
update: (req, res) => Promise.resolve('done'),
delete: (req, res) => Promise.resolve('done')
}
*/
/* GLOBAL HELPERS
const logger = patty.logger // {debug, info, warn, fatal}
let record = await patty._find('some-resource', {id: 1})
let records = await patty._findAll('some-resource', {name: 'jerry'})
let newRecord = await patty._create('some-resource', {name: 'jimmy'})
let updatedRecord = await patty._save('some-resource', {id: 1, name: 'john'})
*/
|
Fix issue with DatePicker rotation in FROYO/GINGERBREAD | /* (C) 2012 Pragmatic Software
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
package com.googlecode.networklog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import java.util.Calendar;
import android.support.v4.app.DialogFragment;
public class DatePickerFragment extends DialogFragment {
int year;
int month;
int day;
DatePickerDialog.OnDateSetListener listener;
public DatePickerFragment() {
Calendar cal = Calendar.getInstance();
this.year = cal.get(Calendar.YEAR);
this.month = cal.get(Calendar.MONTH);
this.day = cal.get(Calendar.DAY_OF_MONTH);
}
public DatePickerFragment(int year, int month, int day, DatePickerDialog.OnDateSetListener listener) {
this(year, month, day);
this.listener = listener;
}
public DatePickerFragment(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void setListener(DatePickerDialog.OnDateSetListener listener) {
this.listener = listener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(getActivity(), this.listener, this.year, this.month, this.day);
}
}
| /* (C) 2012 Pragmatic Software
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
package com.googlecode.networklog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class DatePickerFragment extends DialogFragment {
int year;
int month;
int day;
DatePickerDialog.OnDateSetListener listener;
public DatePickerFragment() {
}
public DatePickerFragment(int year, int month, int day, DatePickerDialog.OnDateSetListener listener) {
this(year, month, day);
this.listener = listener;
}
public DatePickerFragment(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void setListener(DatePickerDialog.OnDateSetListener listener) {
this.listener = listener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(getActivity(), this.listener, this.year, this.month, this.day);
}
}
|
:recycle: Move `extends` and `env` up | 'use strict';
const path = require('path');
/*
* ECMAScript 6
*/
module.exports = {
extends: path.resolve(__dirname, './index.js'),
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
env: {
es6: true
},
rules: {
'arrow-body-style': [
'error',
'as-needed',
{
requireReturnForObjectLiteral: true
}
],
'arrow-parens': ['error', 'as-needed'],
'arrow-spacing': [
'error',
{
before: true,
after: true
}
],
'generator-star-spacing': ['error', 'after'],
'no-confusing-arrow': [
'warn',
{
allowParens: true
}
],
'no-duplicate-imports': 'error',
'no-var': 'error',
'object-shorthand': [
'error',
'always',
{
avoidQuotes: true
}
],
'prefer-spread': 'warn',
'prefer-template': 'error'
}
};
| 'use strict';
const path = require('path');
/*
* ECMAScript 6
*/
module.exports = {
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
rules: {
'arrow-body-style': [
'error',
'as-needed',
{
requireReturnForObjectLiteral: true
}
],
'arrow-parens': ['error', 'as-needed'],
'arrow-spacing': [
'error',
{
before: true,
after: true
}
],
'generator-star-spacing': ['error', 'after'],
'no-confusing-arrow': [
'warn',
{
allowParens: true
}
],
'no-duplicate-imports': 'error',
'no-var': 'error',
'object-shorthand': [
'error',
'always',
{
avoidQuotes: true
}
],
'prefer-spread': 'warn',
'prefer-template': 'error'
},
env: {
es6: true
},
extends: path.resolve(__dirname, './index.js')
};
|
Add form helper to view composer | <?php
namespace Metrique\Building\Http\Composers;
use Collective\Html\FormBuilder;
use Illuminate\View\View;
use Metrique\Building\Building;
class BuildingViewComposer
{
/**
* The building repository.
*
* @var Building
*/
protected $building;
/**
* The form builder
*/
protected $form;
/**
* Create a new profile composer.
*
* @param Building $building
* @return void
*/
public function __construct(Building $building, FormBuilder $form)
{
$this->building = $building;
$this->form = $form;
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('building', $this->building);
$view->with('form', $this->form);
}
}
| <?php
namespace Metrique\Building\Http\Composers;
use Illuminate\View\View;
use Metrique\Building\Building;
class BuildingViewComposer
{
/**
* The building repository.
*
* @var Building
*/
protected $building;
/**
* Create a new profile composer.
*
* @param Building $building
* @return void
*/
public function __construct(Building $building)
{
$this->building = $building;
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('building', $this->building);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.