text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Replace cwd with current module's path | # coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig
def test_autoconfig_env():
config = AutoConfig()
path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'ENV' == config('KEY')
def test_autoconfig_ini():
config = AutoConfig()
path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'INI' == config('KEY')
def test_autoconfig_none():
config = AutoConfig()
with patch('os.path.exists', return_value=False):
with patch.object(config, '_caller_path', return_value="/"):
with pytest.raises(RuntimeError):
config('KEY')
| # coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig
def test_autoconfig_env():
config = AutoConfig()
path = os.path.join(os.getcwd(), 'autoconfig', 'env', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'ENV' == config('KEY')
def test_autoconfig_ini():
config = AutoConfig()
path = os.path.join(os.getcwd(), 'autoconfig', 'ini', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'INI' == config('KEY')
def test_autoconfig_none():
config = AutoConfig()
with patch('os.path.exists', return_value=False):
with patch.object(config, '_caller_path', return_value="/"):
with pytest.raises(RuntimeError):
config('KEY')
|
dblog: Fix log entry __unicode__ method functionality | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from Instanssi.kompomaatti.models import Event
class DBLogEntry(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
event = models.ForeignKey(Event, blank=True, null=True)
date = models.DateTimeField(auto_now_add=True)
module = models.CharField(max_length=64, blank=True)
level = models.CharField(max_length=10)
message = models.TextField()
def __unicode__(self):
if len(self.message) > 64:
return u'{} ...'.format(self.message[:64])
else:
return self.message
class Meta:
verbose_name = u"lokimerkintä"
verbose_name_plural = u"lokimerkinnät"
| # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from Instanssi.kompomaatti.models import Event
class DBLogEntry(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
event = models.ForeignKey(Event, blank=True, null=True)
date = models.DateTimeField(auto_now_add=True)
module = models.CharField(max_length=64, blank=True)
level = models.CharField(max_length=10)
message = models.TextField()
def __unicode__(self):
if len(self.message) > 48:
return u' ...'.format(self.message[:48])
else:
return self.message
class Meta:
verbose_name = u"lokimerkintä"
verbose_name_plural = u"lokimerkinnät"
|
Fix single quotes issues of Catalog.js | import React, { Component } from 'react'
import Catalog from '../Catalog/Catalog'
class Catalogs extends Component {
constructor(props) {
super(props)
this.state = {catalogs: []}
this.getCatalogs()
}
getCatalogs() {
return fetch('https://inspire.data.gouv.fr/api/geogw/catalogs')
.then((response) => response.json())
.then((catalogs) => {
this.setState({catalogs})
})
.catch((err) => {
console.error(err)
})
}
render() {
const styles = {
container: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
paddingTop: '2em',
},
}
return (
<div className="catalogs">
<div style={styles.container}>
{this.state.catalogs.map((catalog, idx) => <Catalog key={idx} catalog={catalog} />)}
</div>
</div>
)
}
}
export default Catalogs
| import React, { Component } from 'react'
import Catalog from '../Catalog/Catalog'
class Catalogs extends Component {
constructor(props) {
super(props)
this.state = {catalogs: []}
this.getCatalogs()
}
getCatalogs() {
return fetch(`https://inspire.data.gouv.fr/api/geogw/catalogs`)
.then((response) => response.json())
.then((catalogs) => {
this.setState({catalogs})
})
.catch((err) => {
console.error(err)
})
}
render() {
const styles = {
container: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
paddingTop: '2em',
},
}
return (
<div className="catalogs">
<div style={styles.container}>
{this.state.catalogs.map((catalog, idx) => <Catalog key={idx} catalog={catalog} />)}
</div>
</div>
)
}
}
export default Catalogs
|
Add seeder for image_uri column of Users table | <?php
/**
* Created by PhpStorm.
* User: andela
* Date: 8/6/15
* Time: 1:55 PM
*/
use Illuminate\Database\Seeder;
use ChopBox\User;
use Faker\Factory;
class UserTableSeeder extends Seeder {
public function run() {
$faker = Factory::create();
//User::truncate();
foreach(range(1,50) as $index) {
User::create([
'username' => $faker->userName,
'password' => $faker->password(8, 20),
'email' => $faker->email,
'profile_state' => $faker->boolean(),
'image_uri' => $faker->imageUrl()
]);
}
}
} | <?php
/**
* Created by PhpStorm.
* User: andela
* Date: 8/6/15
* Time: 1:55 PM
*/
use Illuminate\Database\Seeder;
use ChopBox\User;
use Faker\Factory;
class UserTableSeeder extends Seeder {
public function run() {
$faker = Factory::create();
//User::truncate();
foreach(range(1,50) as $index) {
User::create([
'username' => $faker->userName,
'password' => $faker->password(8, 20),
'email' => $faker->email,
'profile_state' => $faker->boolean(),
]);
}
}
} |
Make description a string, not a tuple.
Fixes #1 | #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as file:
long_description = file.read()
setup(name='parmap',
version='1.2.1',
description=('map and starmap implementations passing additional '
'arguments and parallelizing if possible'),
long_description=long_description,
author='Sergio Oller',
license='APACHE-2.0',
author_email='sergioller@gmail.com',
url='https://github.com/zeehio/parmap',
py_modules=['parmap'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
],
)
| #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as file:
long_description = file.read()
setup(name='parmap',
version='1.2.1',
description=('map and starmap implementations passing additional',
'arguments and parallelizing if possible'),
long_description=long_description,
author='Sergio Oller',
license='APACHE-2.0',
author_email='sergioller@gmail.com',
url='https://github.com/zeehio/parmap',
py_modules=['parmap'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
],
)
|
Use columns from source node | 'use strict';
var Node = require('../node');
var TYPE = 'buffer';
var PARAMS = {
source: Node.PARAM.NODE,
radio: Node.PARAM.NUMBER
};
var Buffer = Node.create(TYPE, PARAMS);
module.exports = Buffer;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
module.exports.create = require('./factory').create;
// ------------------------------ PUBLIC API ------------------------------ //
Buffer.prototype._getQuery = function() {
return bufferQuery(this.source.getQuery(), this.source.getColumns(), this.radio);
};
// ---------------------------- END PUBLIC API ---------------------------- //
function bufferQuery(inputQuery, columnNames, distance) {
return [
'SELECT ST_Buffer(the_geom::geography, ' + distance + ')::geometry the_geom,',
skipColumns(columnNames).join(','),
'FROM (' + inputQuery + ') _camshaft_buffer'
].join('\n');
}
var SKIP_COLUMNS = {
'the_geom': true,
'the_geom_webmercator': true
};
function skipColumns(columnNames) {
return columnNames
.filter(function(columnName) { return !SKIP_COLUMNS[columnName]; });
}
| 'use strict';
var Node = require('../node');
var TYPE = 'buffer';
var PARAMS = {
source: Node.PARAM.NODE,
radio: Node.PARAM.NUMBER
};
var Buffer = Node.create(TYPE, PARAMS);
module.exports = Buffer;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
module.exports.create = require('./factory').create;
// ------------------------------ PUBLIC API ------------------------------ //
Buffer.prototype._getQuery = function() {
return bufferQuery(this.source.getQuery(), this.columns, this.radio);
};
// ---------------------------- END PUBLIC API ---------------------------- //
function bufferQuery(inputQuery, columnNames, distance) {
return [
'SELECT ST_Buffer(the_geom::geography, ' + distance + ')::geometry the_geom,',
skipColumns(columnNames).join(','),
'FROM (' + inputQuery + ') _camshaft_buffer'
].join('\n');
}
var SKIP_COLUMNS = {
'the_geom': true,
'the_geom_webmercator': true
};
function skipColumns(columnNames) {
return columnNames
.filter(function(columnName) { return !SKIP_COLUMNS[columnName]; });
}
|
Increase tax disc beta AB to ~100%
This should mean most users are presented with
the beta as the primary option during the August
tax disc peak. | //= require govuk/multivariate-test
/*jslint browser: true,
* indent: 2,
* white: true
*/
/*global $, GOVUK */
$(function () {
GOVUK.taxDiscBetaPrimary = function () {
$('.primary-apply').html($('#beta-primary').html());
$('.secondary-apply').html($('#dvla-secondary').html());
};
if(window.location.href.indexOf("/tax-disc") > -1) {
new GOVUK.MultivariateTest({
name: 'tax-disc-beta',
customVarIndex: 20,
cohorts: {
tax_disc_beta_control: { weight: 0, callback: function () { } }, //~0%
tax_disc_beta: { weight: 1, callback: GOVUK.taxDiscBetaPrimary } //~100%
}
});
}
});
| //= require govuk/multivariate-test
/*jslint browser: true,
* indent: 2,
* white: true
*/
/*global $, GOVUK */
$(function () {
GOVUK.taxDiscBetaPrimary = function () {
$('.primary-apply').html($('#beta-primary').html());
$('.secondary-apply').html($('#dvla-secondary').html());
};
if(window.location.href.indexOf("/tax-disc") > -1) {
new GOVUK.MultivariateTest({
name: 'tax-disc-beta',
customVarIndex: 20,
cohorts: {
tax_disc_beta_control: { weight: 60, callback: function () { } }, //~60%
tax_disc_beta: { weight: 40, callback: GOVUK.taxDiscBetaPrimary } //~40%
}
});
}
});
|
Update array tree example for testing |
(function ($) {
"use strict";
$(document).ready(init);
// Tree array testing function
function init($) {
createArrayTree();
// createOther();
}
function createArrayTree() {
var jsav = new JSAV("arrayTree");
var tree = new jsav.ds.arraytree();
var n1 = tree.root([1, 1, 1]);
var n2 = n1.addChild([2,2,2]).child(0);
var n3 = n1.addChild([3,3,3,3]).child(1);
var n4 = n1.addChild([4,4,4]).child(2);
var n5 = n1.addChild([5,5,5]).child(3);
var n6 = n2.addChild([6,6,6]).child(0);
var n7 = n2.addChild([7,7,7]).child(1);
var n8 = n2.addChild([8,8,8]).child(2);
var n9 = n2.addChild([9,9,9]).child(3);
n6.value([6, 5, 4]);
n6.value([6, 5, 4, 3]);
n6.edgeToParent().addClass("superclass");
tree.layout();
}
function createOther() {
var jsav = new JSAV("other");
var arr = new jsav.ds.array([1, 2, 3, 4], {element: $('#hello')});
}
}(jQuery));
|
(function ($) {
"use strict";
$(document).ready(init);
// Tree array testing function
function init($) {
createArrayTree();
// createOther();
}
function createArrayTree() {
var jsav = new JSAV("arrayTree");
var tree = new jsav.ds.arraytree(3);
tree.root([1, 1, 1]);
var child1 = tree.root().addChild([2, 2, 2]);
var child2 = tree.root().addChild([3, 3, 3]);
var child3 = tree.root().addChild([4, 4, 4]);
var child4 = tree.root().addChild([5, 5, 5]);
tree.layout();
}
function createOther() {
var jsav = new JSAV("other");
var arr = new jsav.ds.array([1, 2, 3, 4], {element: $('#hello')});
}
}(jQuery));
|
Handle if it returns a nil
This can happen if it tries to decode an event not called 'weatherstationJSON' | package main
import (
"fmt"
"github.com/peterhellberg/sseclient"
"log"
"os"
)
var logger *log.Logger
var urlFormat, deviceId string
func init() {
logger = log.New(os.Stdout, "", log.LstdFlags|log.Lmicroseconds)
urlFormat = "https://api.particle.io/v1/devices/%s/events/?access_token=%s"
}
func main() {
settings := &OakWeatherSettings{}
var err error
settings, err = findSettings()
if err != nil {
logger.Println("Could not read settings file. reason:", err)
logger.Println("Reverting to asking for the settings.")
settings, err = askForSettings()
saveSettings(*settings)
}
listenForWeatherEvents(settings.SelectedDevice, settings.AccessToken)
}
func listenForWeatherEvents(device Device, accessToken string) {
url := fmt.Sprintf(urlFormat, device.Id, accessToken)
events, err := sseclient.OpenURL(url)
if err != nil {
logger.Println("Error:", err)
os.Exit(1)
}
logger.Printf("Connected to the stream of device %s (%s)", device.Name, device.Id)
for event := range events {
data_decoded := NewWeatherData(event.Data)
if data_decoded != nil {
logger.Println(data_decoded.asString())
}
}
}
| package main
import (
"fmt"
"github.com/peterhellberg/sseclient"
"log"
"os"
)
var logger *log.Logger
var urlFormat, deviceId string
func init() {
logger = log.New(os.Stdout, "", log.LstdFlags|log.Lmicroseconds)
urlFormat = "https://api.particle.io/v1/devices/%s/events/?access_token=%s"
}
func main() {
settings := &OakWeatherSettings{}
var err error
settings, err = findSettings()
if err != nil {
logger.Println("Could not read settings file. reason:", err)
logger.Println("Reverting to asking for the settings.")
settings, err = askForSettings()
saveSettings(*settings)
}
listenForWeatherEvents(settings.SelectedDevice, settings.AccessToken)
}
func listenForWeatherEvents(device Device, accessToken string) {
url := fmt.Sprintf(urlFormat, device.Id, accessToken)
events, err := sseclient.OpenURL(url)
if err != nil {
logger.Println("Error:", err)
os.Exit(1)
}
logger.Printf("Connected to the stream of device %s (%s)", device.Name, device.Id)
for event := range events {
data_decoded := NewWeatherData(event.Data)
logger.Println(data_decoded.asString())
}
}
|
Change name of boundary conditions for Biomeng321 Lab1. | '''
Copyright 2015 University of Auckland
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.
'''
import json
from opencmiss.neon.core.problems.base import BaseProblem
BOUNDARY_CONDITIONS = ['Model 1', 'Model 2', 'Model 3', 'Model 4', 'Model 5']
class Biomeng321Lab1(BaseProblem):
def __init__(self):
super(Biomeng321Lab1, self).__init__()
self.setName('Biomeng321 Lab1')
self._boundary_condition = None
def setBoundaryCondition(self, boundary_condition):
self._boundary_condition = boundary_condition
def getBoundaryCondition(self):
return self._boundary_condition
def serialise(self):
d = {}
d['boundary_condition'] = self._boundary_condition
return json.dumps(d)
def deserialise(self, string):
d = json.loads(string)
self._boundary_condition = d['boundary_condition'] if 'boundary_condition' in d else None
def validate(self):
return True
| '''
Copyright 2015 University of Auckland
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.
'''
import json
from opencmiss.neon.core.problems.base import BaseProblem
BOUNDARY_CONDITIONS = ['Type 1', 'Type 2', 'Type 3', 'Type 4', 'Type 5']
class Biomeng321Lab1(BaseProblem):
def __init__(self):
super(Biomeng321Lab1, self).__init__()
self.setName('Biomeng321 Lab1')
self._boundary_condition = None
def setBoundaryCondition(self, boundary_condition):
self._boundary_condition = boundary_condition
def getBoundaryCondition(self):
return self._boundary_condition
def serialise(self):
d = {}
d['boundary_condition'] = self._boundary_condition
return json.dumps(d)
def deserialise(self, string):
d = json.loads(string)
self._boundary_condition = d['boundary_condition'] if 'boundary_condition' in d else None
def validate(self):
return True
|
[vacation-gardening] Change method _compute_runtime_use_sanitizer => property _runtime_sanitizer_flags. NFC. | # swift_build_support/products/swift.py -------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ----------------------------------------------------------------------------
from . import product
class Swift(product.Product):
def __init__(self, args, toolchain, source_dir, build_dir):
product.Product.__init__(self, args, toolchain, source_dir,
build_dir)
# Add any runtime sanitizer arguments.
self.cmake_options.extend(self._runtime_sanitizer_flags)
@property
def _runtime_sanitizer_flags(self):
sanitizer_list = []
if self.args.enable_tsan_runtime:
sanitizer_list += ['Thread']
if len(sanitizer_list) == 0:
return []
return ["-DSWIFT_RUNTIME_USE_SANITIZERS=%s" %
";".join(sanitizer_list)]
| # swift_build_support/products/swift.py -------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ----------------------------------------------------------------------------
from . import product
class Swift(product.Product):
def __init__(self, args, toolchain, source_dir, build_dir):
product.Product.__init__(self, args, toolchain, source_dir,
build_dir)
# Add any runtime sanitizer arguments.
self.cmake_options.extend(self._compute_runtime_use_sanitizer())
def _compute_runtime_use_sanitizer(self):
sanitizer_list = []
if self.args.enable_tsan_runtime:
sanitizer_list += ['Thread']
if len(sanitizer_list) == 0:
return []
return ["-DSWIFT_RUNTIME_USE_SANITIZERS=%s" %
";".join(sanitizer_list)]
|
Add pip requirement for humanize. | #!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='ecmcli',
version='0.0.2',
description='Command Line Client for Cradlepoint ECM',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/ecmcli/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
install_requires=[
'syndicate',
'humanize'
],
entry_points = {
'console_scripts': ['ecm=ecmcli.main:main'],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='ecmcli',
version='0.0.2',
description='Command Line Client for Cradlepoint ECM',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/ecmcli/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
install_requires=[
'syndicate',
],
entry_points = {
'console_scripts': ['ecm=ecmcli.main:main'],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
Update save methods strategy
- Use anonymous function to save collection methods before overwrite | 'use strict';
var Mongoat = require('mongodb');
var utilsHelper = require('../helpers/utils-helper');
var connect = Mongoat.MongoClient.connect;
var hooks = {
before: {},
after: {}
};
(function(){
var opArray = ['insert', 'update', 'remove'];
var colPrototype = Mongoat.Collection.prototype;
for (var i = 0; i < opArray.length; ++i) {
colPrototype[opArray[i] + 'Method'] = colPrototype[opArray[i]];
}
})();
Mongoat.Collection.prototype.before = function(opName, callback) {
hooks = utilsHelper.beforeAfter('before', opName, hooks, callback);
};
Mongoat.Collection.prototype.after = function(opName, callback) {
hooks = utilsHelper.beforeAfter('after', opName, hooks, callback);
};
Mongoat.Collection.prototype.insert = function(document, options) {
var promises = [];
var _this = this;
options = options || {};
promises = utilsHelper.promisify(hooks.before.insert, document);
return Promise.all(promises).then(function (docToInsert) {
return _this.insertMethod(docToInsert[0], options)
.then(function (mongoObject) {
promises = [];
promises = utilsHelper.promisify(hooks.after.insert, docToInsert[0]);
Promise.all(promises);
return mongoObject;
});
});
};
module.exports = Mongoat; | 'use strict';
var Mongoat = require('mongodb');
var utilsHelper = require('../helpers/utils-helper');
var connect = Mongoat.MongoClient.connect;
var hooks = {
before: {},
after: {}
};
Mongoat.Collection.prototype.before = function(opName, callback) {
hooks = utilsHelper.beforeAfter('before', opName, hooks, callback);
};
Mongoat.Collection.prototype.after = function(opName, callback) {
hooks = utilsHelper.beforeAfter('after', opName, hooks, callback);
};
Mongoat.Collection.prototype.insertTo = Mongoat.Collection.prototype.insert;
Mongoat.Collection.prototype.insert = function(document, options) {
var promises = [];
var _this = this;
options = options || {};
promises = utilsHelper.promisify(hooks.before.insert, document);
return Promise.all(promises).then(function (docToInsert) {
return _this.insertTo(docToInsert[0], options).then(function (mongoObject) {
promises = [];
promises = utilsHelper.promisify(hooks.after.insert, docToInsert[0]);
Promise.all(promises);
return mongoObject;
});
});
};
module.exports = Mongoat; |
Return error message in Code Climate runs
Stringifying an Error object results in {} so the formatter was not
returning the actual underlying error with the Code Climate formatter.
This change returns the error so that they user can take action if an
analysis run fails.
This change returns the Error stack which includes a helpful error
message and the backtrace for debugging purposes. | 'use strict';
module.exports = function (err, data) {
if (err) {
return err.stack;
}
if (!data.length) {
return;
}
var returnString = '';
for (var i = 0, il = data.length; i < il; ++i) {
returnString += JSON.stringify({
type: 'issue',
check_name: 'Vulnerable module "' + data[i].module + '" identified',
description: '`' + data[i].module + '` ' + data[i].title,
categories: ['Security'],
remediation_points: 300000,
content: {
body: data[i].content
},
location: {
path: 'npm-shrinkwrap.json',
lines: {
begin: data[i].line.start,
end: data[i].line.end
}
}
}) + '\0\n';
}
return returnString;
};
| 'use strict';
module.exports = function (err, data) {
if (err) {
return 'Debug output: %j' + JSON.stringify(data) + '\n' + JSON.stringify(err);
}
if (!data.length) {
return;
}
var returnString = '';
for (var i = 0, il = data.length; i < il; ++i) {
returnString += JSON.stringify({
type: 'issue',
check_name: 'Vulnerable module "' + data[i].module + '" identified',
description: '`' + data[i].module + '` ' + data[i].title,
categories: ['Security'],
remediation_points: 300000,
content: {
body: data[i].content
},
location: {
path: 'npm-shrinkwrap.json',
lines: {
begin: data[i].line.start,
end: data[i].line.end
}
}
}) + '\0\n';
}
return returnString;
};
|
Make program close on any keypress | import map
import curses
# Set up Curses screen
screen = curses.initscr()
curses.noecho()
screen.keypad(True)
curses.cbreak()
curses.halfdelay(5) # Wait for half a second for input before continuing
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
# Initialize the map
m = map.Map(screen, "data/test_data.txt")
while True:
# Check for exit key
char = screen.getch()
if char != -1:
break
# Advance the simulation
m.print_cells(x=10, y=10)
m.update_cells()
# Clean up
curses.nocbreak()
screen.keypad(False)
curses.echo()
curses.endwin()
| import map
import curses
# Set up Curses screen
screen = curses.initscr()
curses.noecho()
screen.keypad(True)
curses.cbreak()
curses.halfdelay(5) # Wait for half a second for input before continuing
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
# Initialize the map
m = map.Map(screen, "data/test_data.txt")
i = 0
while True:
# Check for exit key
char = screen.getch()
if char == ord('q'):
break
# Advance the simulation
m.print_cells(x=10, y=10)
m.update_cells()
# Clean up
curses.nocbreak()
screen.keypad(False)
curses.echo()
curses.endwin()
|
Split isexecutable into its own function | import StringIO
import os
from rock.exceptions import ConfigError
ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split()
def isexecutable(path):
return os.path.isfile(path) and os.access(path, os.X_OK)
class Shell(object):
def __init__(self):
self.stdin = StringIO.StringIO()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.run()
def run(self):
if not isexecutable(ROCK_SHELL[0]):
raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL)
os.execl(*(ROCK_SHELL + [self.stdin.getvalue()]))
def write(self, text):
self.stdin.write(text + '\n')
| import StringIO
import os
from rock.exceptions import ConfigError
ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split()
class Shell(object):
def __init__(self):
self.stdin = StringIO.StringIO()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.run()
def run(self):
if not os.path.isfile(ROCK_SHELL[0]) or not os.access(ROCK_SHELL[0], os.X_OK):
raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL)
os.execl(*(ROCK_SHELL + [self.stdin.getvalue()]))
def write(self, text):
self.stdin.write(text + '\n')
|
Allow blank backgrounds to be created with insets. | //
// $Id$
//
// BUI - a user interface library for the JME 3D engine
// Copyright (C) 2005, Michael Bayne, All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.jme.bui.background;
import com.jme.renderer.Renderer;
/**
* A blank background.
*/
public class BlankBackground extends BBackground
{
public BlankBackground ()
{
this(0, 0, 0, 0);
}
public BlankBackground (int left, int top, int right, int bottom)
{
super(left, top, right, bottom);
}
}
| //
// $Id$
//
// BUI - a user interface library for the JME 3D engine
// Copyright (C) 2005, Michael Bayne, All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.jme.bui.background;
import com.jme.renderer.Renderer;
/**
* A blank background.
*/
public class BlankBackground extends BBackground
{
public BlankBackground ()
{
super(0, 0, 0, 0);
}
}
|
Update the examples to explicitly exit the process | "use strict";
var init = require("exp-amqp-connection");
var amqpBehaviour = {
url: "amqp://localhost",
exchange: "my-excchange",
ack: "true",
prefetch: 10
};
var broker = init(amqpBehaviour);
broker.on("connected", function() {
console.log("Connected to amqp server");
});
broker.on("subscribed", function(subscription) {
console.log("Subscription started:", subscription);
});
// Simplest way to deal with errors: abort the process.
// Assuming of course that you have a scheduler or process manager (kubernetes,
// pm2, forever etc) in place to restart your process.
//
// NOTE: See the "subcribe-reconnect" example on how to handle errors without
// restarting the process.
broker.on("error", function(error) {
console.error("Amqp error", error, ", aborting process.");
process.exit(1);
});
function handleMessage(message, meta, notify) {
console.log("Got message", message, "with routing key", meta.fields.routingKey);
notify.ack();
}
broker.subscribe("some-routing-key", "some-queue", handleMessage);
setInterval(function() {
broker.publish("some-routing-key", "Hello " + new Date());
}, 1000); | "use strict";
// Simplest way to subscribe. Start the subscription and don't listen to "error" events
// from the broker. This will cause the process to crash in case of errors.
// This of course requires a process manager such as "pm2" or "forever" in place
// to restart the process.
var init = require("exp-amqp-connection");
var amqpBehaviour = {
url: "amqp://localhost",
exchange: "my-excchange",
ack: "true",
prefetch: 10
};
var broker = init(amqpBehaviour);
broker.on("connected", function () {
console.log("Connected to amqp server");
});
broker.on("subscribed", function (subscription) {
console.log("Subscription started:", subscription);
});
function handleMessage(message, meta, notify) {
console.log("Got message", message, "with routing key", meta.fields.routingKey);
notify.ack();
}
broker.subscribe("some-routing-key", "some-queue", handleMessage);
setInterval(function () {
broker.publish("some-routing-key", "Hello " + new Date());
}, 1000);
|
Update native renderer to be less risky | <?php
namespace Michaeljennings\Carpenter\View;
use Michaeljennings\Carpenter\Contracts\View;
use Michaeljennings\Carpenter\Exceptions\ViewNotFoundException;
class Native implements View
{
/**
* Return the required view
*
* @param $view
* @param array $data
* @return string
* @throws ViewNotFoundException
*/
public function make($view, $data = [])
{
if ( ! file_exists($view)) {
throw new ViewNotFoundException("The table template could not be found. No file found at '{$view}'");
}
ob_start();
if ( ! empty($data)) {
extract($data);
}
include($view);
return ob_get_clean();
}
} | <?php
namespace Michaeljennings\Carpenter\View;
use Michaeljennings\Carpenter\Contracts\View;
use Michaeljennings\Carpenter\Exceptions\ViewNotFoundException;
class Native implements View
{
/**
* Return the required view
*
* @param $view
* @param array $data
* @return string
* @throws ViewNotFoundException
*/
public function make($view, $data = [])
{
if ( ! file_exists($view)) {
throw new ViewNotFoundException("The table template could not be found. No file found at '{$view}'");
}
extract($data);
include($view);
// Get the content
$content = ob_get_contents();
// Clear the output buffer
ob_end_clean();
// Return the content
return $content;
}
} |
Rename the package name to junit-xml-output.
Signed-off-by: David Black <c4b737561a711e07c31fd1e1811f33a5d770e31c@atlassian.com> | #!/usr/bin/env python
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='junit-xml-output',
author = 'David Black',
author_email = 'dblack@atlassian.com',
url = 'https://bitbucket.org/db_atlass/python-junit-xml-output-module',
packages = find_packages(),
description = read('README.md'),
long_description = read('README.md'),
license = "MIT",
version = __import__('junit_xml_output').__version__,
test_suite = 'junit_xml_output.test',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='junit_xml_output',
author = 'David Black',
author_email = 'dblack@atlassian.com',
url = 'https://bitbucket.org/db_atlass/python-junit-xml-output-module',
packages = find_packages(),
description = read('README.md'),
long_description = read('README.md'),
license = "MIT",
version = __import__('junit_xml_output').__version__,
test_suite = 'junit_xml_output.test',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
[OWL-998][backend] Fix the flags of subcommands | package main
import (
"fmt"
"os"
"github.com/Cepave/open-falcon-backend/cmd"
"github.com/spf13/cobra"
)
var versionFlag bool
var RootCmd = &cobra.Command{
Use: "open-falcon",
Run: func(cmd *cobra.Command, args []string) {
if versionFlag {
fmt.Printf("Open-Falcon version %s, build %s\n", Version, GitCommit)
os.Exit(0)
}
},
}
func init() {
RootCmd.AddCommand(cmd.Start)
RootCmd.AddCommand(cmd.Stop)
RootCmd.AddCommand(cmd.Restart)
RootCmd.AddCommand(cmd.Check)
RootCmd.AddCommand(cmd.Monitor)
RootCmd.AddCommand(cmd.Reload)
RootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "show version")
cmd.Start.Flags().BoolVar(&cmd.PreqOrderFlag, "preq-order", false, "start modules in the order of prerequisites")
cmd.Start.Flags().BoolVar(&cmd.ConsoleOutputFlag, "console-output", false, "print the module's output to the console")
}
func main() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
| package main
import (
"fmt"
"os"
"github.com/Cepave/open-falcon-backend/cmd"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
)
var versionFlag bool
var RootCmd = &cobra.Command{
Use: "open-falcon",
}
func init() {
RootCmd.AddCommand(cmd.Start)
RootCmd.AddCommand(cmd.Stop)
RootCmd.AddCommand(cmd.Restart)
RootCmd.AddCommand(cmd.Check)
RootCmd.AddCommand(cmd.Monitor)
RootCmd.AddCommand(cmd.Reload)
cmd.Start.Flags().BoolVar(&cmd.PreqOrderFlag, "preq-order", false, "start modules in the order of prerequisites")
cmd.Start.Flags().BoolVar(&cmd.ConsoleOutputFlag, "console-output", false, "print the module's output to the console")
flag.BoolVarP(&versionFlag, "version", "v", false, "show version")
flag.Parse()
}
func main() {
if versionFlag {
fmt.Printf("Open-Falcon version %s, build %s\n", Version, GitCommit)
os.Exit(0)
}
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
|
Add more details to the javadoc
git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1364421 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.logging.log4j.message;
/**
* A Message that can have a format String attached to it. The format string is used by the
* Message implementation as extra information that it may use to help it to determine how
* to format itself. For example, MapMessage accepts a format of "XML" to tell it to render
* the Map as XML instead of its default format of {key1="value1" key2="value2"}.
*/
public interface FormattedMessage extends Message {
/**
* Set the message format.
* @param format The message format.
*/
void setFormat(String format);
/**
* Return the message format.
* @return the message format String.
*/
String getFormat();
}
| /*
* 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.logging.log4j.message;
/**
* A Message that can have a format String attached to it.
*/
public interface FormattedMessage extends Message {
/**
* Set the message format.
* @param format The message format.
*/
void setFormat(String format);
/**
* Return the message format.
* @return the message format String.
*/
String getFormat();
}
|
Rename Part to PartName to mirror PartSearch getters/setters | package org.amc.servlet.model;
public class PartSearchForm implements WebPageForm
{
private String partName;
private String qSSNumber;
private String company;
/**
* @return the part
*/
public String getPartName()
{
return partName;
}
/**
* @return the qSSNumber
*/
public String getQSSNumber()
{
return qSSNumber;
}
/**
* @return the company
*/
public String getCompany()
{
return company;
}
/**
* @param part the part to set
*/
public void setPartName(String part)
{
this.partName = part;
}
/**
* @param qSSNumber the qSSNumber to set
*/
public void setQSSNumber(String qSSNumber)
{
this.qSSNumber = qSSNumber;
}
/**
* @param company the company to set
*/
public void setCompany(String company)
{
this.company = company;
}
}
| package org.amc.servlet.model;
public class PartSearchForm implements WebPageForm
{
private String part;
private String qSSNumber;
private String company;
/**
* @return the part
*/
public String getPart()
{
return part;
}
/**
* @return the qSSNumber
*/
public String getQSSNumber()
{
return qSSNumber;
}
/**
* @return the company
*/
public String getCompany()
{
return company;
}
/**
* @param part the part to set
*/
public void setPart(String part)
{
this.part = part;
}
/**
* @param qSSNumber the qSSNumber to set
*/
public void setQSSNumber(String qSSNumber)
{
this.qSSNumber = qSSNumber;
}
/**
* @param company the company to set
*/
public void setCompany(String company)
{
this.company = company;
}
}
|
Increase lock timeout to 5 min | package com.netflix.exhibitor.core.config;
import java.util.concurrent.TimeUnit;
public class AutoManageLockArguments
{
private final String prefix;
private final int timeoutMs;
private final int pollingMs;
public AutoManageLockArguments(String prefix)
{
// TODO get defaults right
this(prefix, (int)TimeUnit.MINUTES.toMillis(5), 250);
}
public AutoManageLockArguments(String prefix, int timeoutMs, int pollingMs)
{
this.prefix = prefix;
this.timeoutMs = timeoutMs;
this.pollingMs = pollingMs;
}
public String getPrefix()
{
return prefix;
}
public int getTimeoutMs()
{
return timeoutMs;
}
public int getPollingMs()
{
return pollingMs;
}
}
| package com.netflix.exhibitor.core.config;
import java.util.concurrent.TimeUnit;
public class AutoManageLockArguments
{
private final String prefix;
private final int timeoutMs;
private final int pollingMs;
public AutoManageLockArguments(String prefix)
{
// TODO get defaults right
this(prefix, (int)TimeUnit.MINUTES.toMillis(1), 250);
}
public AutoManageLockArguments(String prefix, int timeoutMs, int pollingMs)
{
this.prefix = prefix;
this.timeoutMs = timeoutMs;
this.pollingMs = pollingMs;
}
public String getPrefix()
{
return prefix;
}
public int getTimeoutMs()
{
return timeoutMs;
}
public int getPollingMs()
{
return pollingMs;
}
}
|
Make Default Ads super rare | package main
import "math/rand"
import "time"
const DEFAULT_AD_CHANCE = 95
type Plug struct {
ID int
S3ID string
Owner string
ViewsRemaining int
}
func (p Plug) IsDefault() bool {
return p.ViewsRemaining >= 0
}
func ChoosePlug(plugs []Plug) Plug {
rand.Seed(time.Now().Unix())
// Split plugs into default and custom ads
var defaults []Plug
var customs []Plug
for i := 0; i < len(plugs); i++ {
if plugs[i].IsDefault() {
defaults = append(defaults, plugs[i])
} else {
customs = append(customs, plugs[i])
}
}
// Decide whether to chose default ad or user submitted ad
var pickDefault int = rand.Intn(100)
if pickDefault >= DEFAULT_AD_CHANCE && len(defaults) != 0 {
return defaults[rand.Intn(len(defaults))]
} else {
return customs[rand.Intn(len(customs))]
}
}
| package main
import "math/rand"
import "time"
const DEFAULT_AD_CHANCE = 85
type Plug struct {
ID int
S3ID string
Owner string
ViewsRemaining int
}
func (p Plug) IsDefault() bool {
return p.ViewsRemaining >= 0
}
func ChoosePlug(plugs []Plug) Plug {
rand.Seed(time.Now().Unix())
// Split plugs into default and custom ads
var defaults []Plug
var customs []Plug
for i := 0; i < len(plugs); i++ {
if plugs[i].IsDefault() {
defaults = append(defaults, plugs[i])
} else {
customs = append(customs, plugs[i])
}
}
// Decide whether to chose default ad or user submitted ad
var pickDefault int = rand.Intn(100)
if pickDefault >= DEFAULT_AD_CHANCE && len(defaults) != 0 {
return defaults[rand.Intn(len(defaults))]
} else {
return customs[rand.Intn(len(customs))]
}
}
|
Clean up all test dbs after test run. | # Copyright 2010 10gen, 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.
"""Clean up databases after running `nosetests`.
"""
from test_connection import get_connection
def teardown():
c = get_connection()
c.drop_database("pymongo-pooling-tests")
c.drop_database("pymongo_test")
c.drop_database("pymongo_test1")
c.drop_database("pymongo_test2")
c.drop_database("pymongo_test_mike")
c.drop_database("pymongo_test_bernie")
| # Copyright 2010 10gen, 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.
"""Clean up databases after running `nosetests`.
"""
from test_connection import get_connection
def teardown():
c = get_connection()
c.drop_database("pymongo-pooling-tests")
c.drop_database("pymongo_test")
c.drop_database("pymongo_test1")
c.drop_database("pymongo_test2")
c.drop_database("pymongo_test_mike")
|
Remove no longer existing files from the cache when scanning external storage | <?php
/**
* Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OCA\Files_Sharing\External;
class Scanner extends \OC\Files\Cache\Scanner {
/**
* @var \OCA\Files_Sharing\External\Storage
*/
protected $storage;
public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1) {
$this->scanAll();
}
public function scanAll() {
$data = $this->storage->getShareInfo();
if ($data['status'] === 'success') {
$this->addResult($data['data'], '');
} else {
throw new \Exception('Error while scanning remote share');
}
}
private function addResult($data, $path) {
$id = $this->cache->put($path, $data);
if (isset($data['children'])) {
$children = array();
foreach ($data['children'] as $child) {
$children[$child['name']] = true;
$this->addResult($child, ltrim($path . '/' . $child['name'], '/'));
}
$existingCache = $this->cache->getFolderContentsById($id);
foreach ($existingCache as $existingChild) {
// if an existing child is not in the new data, remove it
if (!isset($children[$existingChild['name']])) {
$this->cache->remove(ltrim($path . '/' . $existingChild['name'], '/'));
}
}
}
}
}
| <?php
/**
* Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OCA\Files_Sharing\External;
class Scanner extends \OC\Files\Cache\Scanner {
/**
* @var \OCA\Files_Sharing\External\Storage
*/
protected $storage;
public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1) {
$this->scanAll();
}
public function scanAll() {
$data = $this->storage->getShareInfo();
if ($data['status'] === 'success') {
$this->addResult($data['data'], '');
} else {
throw new \Exception('Error while scanning remote share');
}
}
private function addResult($data, $path) {
$this->cache->put($path, $data);
if (isset($data['children'])) {
foreach ($data['children'] as $child) {
$this->addResult($child, ltrim($path . '/' . $child['name'], '/'));
}
}
}
}
|
Update to comply with linter | const {setExamSubmitting, setDirty, isUnsubmitted} =
require('../examSubmission.js');
test('check set exam submitting', () => {
expect(setExamSubmitting()).toBe(true);
});
test('check set dirty', () => {
expect(setDirty()).toBe(true);
});
test('isUnsubmitted when exam has not been submitted but filled in', () =>{
const reply = 'It looks like you have not submitted your exam';
expect(isUnsubmitted('event', false, true)).toBe(reply);
});
test('isUnsubmitted when exam has been submitted and filled in', () =>{
expect(isUnsubmitted('event', true, true )).toBe(undefined);
});
test('isUnsubmitted when exam has not been submitted and not filled in', () =>{
expect(isUnsubmitted('event', false, false)).toBe(undefined);
});
test('isUnsubmitted when exam has been submitted and not filled in', () =>{
expect(isUnsubmitted('event', true, false)).toBe(undefined);
});
| let {setExamSubmitting, setDirty, isUnsubmitted} =
require('../examSubmission.js');
test('check set exam submitting', () => {
expect(setExamSubmitting()).toBe(true);
});
test('check set dirty', () => {
expect(setDirty()).toBe(true);
});
test('isUnsubmitted when exam has not been submitted but filled in', () =>{
const reply = 'It looks like you have not submitted your exam';
expect(isUnsubmitted('event', false, true)).toBe(reply);
})
test('isUnsubmitted when exam has been submitted and filled in', () =>{
expect(isUnsubmitted('event',true, true )).toBe(undefined);
})
test('isUnsubmitted when exam has not been submitted and not filled in', () =>{
expect(isUnsubmitted('event', false, false)).toBe(undefined);
})
test('isUnsubmitted when exam has been submitted and not filled in', () =>{
expect(isUnsubmitted('event', true, false)).toBe(undefined);
})
|
Change SQLOperations to be an eager singleton | /*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.plugin;
import io.crate.action.sql.DDLStatementDispatcher;
import io.crate.action.sql.SQLOperations;
import io.crate.metadata.FulltextAnalyzerResolver;
import io.crate.protocols.postgres.PostgresNetty;
import org.elasticsearch.common.inject.AbstractModule;
public class SQLModule extends AbstractModule {
@Override
protected void configure() {
bind(DDLStatementDispatcher.class).asEagerSingleton();
bind(FulltextAnalyzerResolver.class).asEagerSingleton();
bind(PostgresNetty.class).asEagerSingleton();
bind(SQLOperations.class).asEagerSingleton();
}
}
| /*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.plugin;
import io.crate.action.sql.DDLStatementDispatcher;
import io.crate.metadata.FulltextAnalyzerResolver;
import io.crate.protocols.postgres.PostgresNetty;
import org.elasticsearch.common.inject.AbstractModule;
public class SQLModule extends AbstractModule {
@Override
protected void configure() {
bind(DDLStatementDispatcher.class).asEagerSingleton();
bind(FulltextAnalyzerResolver.class).asEagerSingleton();
bind(PostgresNetty.class).asEagerSingleton();
}
}
|
Fix broken app for clients with react dev tools extension | 'use strict';
if (!window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {};
}
const App = require('./components/app.js');
const React = require('react');
const ReactDom = require('react-dom');
const activeStore = require('./store/activeStore.js');
const alertStore = require('./store/alertStore.js');
const call = require('./call.js');
const debug = require('debug')('peer-calls:index');
const notificationsStore = require('./store/notificationsStore.js');
const play = require('./browser/video.js').play;
const streamStore = require('./store/streamStore.js');
function render() {
debug('rendering');
ReactDom.render(<App />, document.querySelector('#container'));
play();
}
activeStore.addListener(render);
alertStore.addListener(render);
notificationsStore.addListener(render);
streamStore.addListener(render);
render();
call.init();
| 'use strict';
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {};
const App = require('./components/app.js');
const React = require('react');
const ReactDom = require('react-dom');
const activeStore = require('./store/activeStore.js');
const alertStore = require('./store/alertStore.js');
const call = require('./call.js');
const debug = require('debug')('peer-calls:index');
const notificationsStore = require('./store/notificationsStore.js');
const play = require('./browser/video.js').play;
const streamStore = require('./store/streamStore.js');
function render() {
debug('rendering');
ReactDom.render(<App />, document.querySelector('#container'));
play();
}
activeStore.addListener(render);
alertStore.addListener(render);
notificationsStore.addListener(render);
streamStore.addListener(render);
render();
call.init();
|
Add additional checks to update_language_list test
Also make language variable names independent of their actual values. | # test_update_language_list
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
new_language_id = 'kln'
new_language_name = 'Klingon'
langs_path = os.path.join(yvs.PACKAGED_DATA_DIR_PATH, 'languages.json')
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
orig_num_langs = len(langs)
add_lang.update_language_list(new_language_id, new_language_name)
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
num_langs = len(langs)
nose.assert_equal(num_langs, orig_num_langs + 1)
new_lang = None
for lang in langs:
if lang['id'] == new_language_id:
new_lang = lang
nose.assert_is_not_none(new_lang)
nose.assert_equal(new_lang['name'], new_language_name)
| # test_update_language_list
from __future__ import unicode_literals
import json
import os
import os.path
import nose.tools as nose
import yvs.shared as yvs
import utilities.add_language as add_lang
from tests.test_add_language import set_up, tear_down
@nose.with_setup(set_up, tear_down)
def test_update_languge_list_add():
"""should add new languages to language list"""
kln_language_id = 'kln'
kln_language_name = 'Klingon'
add_lang.update_language_list(kln_language_id, kln_language_name)
langs_path = os.path.join(yvs.PACKAGED_DATA_DIR_PATH, 'languages.json')
with open(langs_path, 'r') as langs_file:
langs = json.load(langs_file)
kln_lang = None
for lang in langs:
if lang['id'] == kln_language_id:
kln_lang = lang
nose.assert_is_not_none(kln_lang)
nose.assert_equal(kln_lang['name'], kln_language_name)
|
Multiply inner circle coefficient by .95 to ensure a stroke remains | 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = function CircleBounce (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = 0.95 * curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(.10, 0.45, .9, .45).get(value)
}
| 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = function CircleBounce (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(.10, 0.45, .9, .45).get(value)
}
|
Fix default command so that it doesn't fail on dash-prefixed files
Close #310 | package fzf
import (
"time"
"github.com/junegunn/fzf/src/util"
)
const (
// Current version
Version = "0.10.1"
// Core
coordinatorDelayMax time.Duration = 100 * time.Millisecond
coordinatorDelayStep time.Duration = 10 * time.Millisecond
// Reader
defaultCommand = `find . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | sed s/^..//`
// Terminal
initialDelay = 100 * time.Millisecond
spinnerDuration = 200 * time.Millisecond
// Matcher
progressMinDuration = 200 * time.Millisecond
// Capacity of each chunk
chunkSize int = 100
// Do not cache results of low selectivity queries
queryCacheMax int = chunkSize / 5
// Not to cache mergers with large lists
mergerCacheMax int = 100000
// History
defaultHistoryMax int = 1000
)
// fzf events
const (
EvtReadNew util.EventType = iota
EvtReadFin
EvtSearchNew
EvtSearchProgress
EvtSearchFin
EvtHeader
EvtClose
)
| package fzf
import (
"time"
"github.com/junegunn/fzf/src/util"
)
const (
// Current version
Version = "0.10.1"
// Core
coordinatorDelayMax time.Duration = 100 * time.Millisecond
coordinatorDelayStep time.Duration = 10 * time.Millisecond
// Reader
defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`
// Terminal
initialDelay = 100 * time.Millisecond
spinnerDuration = 200 * time.Millisecond
// Matcher
progressMinDuration = 200 * time.Millisecond
// Capacity of each chunk
chunkSize int = 100
// Do not cache results of low selectivity queries
queryCacheMax int = chunkSize / 5
// Not to cache mergers with large lists
mergerCacheMax int = 100000
// History
defaultHistoryMax int = 1000
)
// fzf events
const (
EvtReadNew util.EventType = iota
EvtReadFin
EvtSearchNew
EvtSearchProgress
EvtSearchFin
EvtHeader
EvtClose
)
|
Update requests version to match ckanext-archiver. | from setuptools import setup, find_packages
from ckanext.qa import __version__
setup(
name='ckanext-qa',
version=__version__,
description='Quality Assurance plugin for CKAN',
long_description='',
classifiers=[],
keywords='',
author='Open Knowledge Foundation',
author_email='info@okfn.org',
url='http://ckan.org/wiki/Extensions',
license='mit',
packages=find_packages(exclude=['tests']),
namespace_packages=['ckanext', 'ckanext.qa'],
include_package_data=True,
zip_safe=False,
install_requires=[
'celery==2.4.2',
'kombu==2.1.3',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests==0.14',
],
tests_require=[
'nose',
'mock',
],
entry_points='''
[paste.paster_command]
qa=ckanext.qa.commands:QACommand
[ckan.plugins]
qa=ckanext.qa.plugin:QAPlugin
[ckan.celery_task]
tasks=ckanext.qa.celery_import:task_imports
''',
)
| from setuptools import setup, find_packages
from ckanext.qa import __version__
setup(
name='ckanext-qa',
version=__version__,
description='Quality Assurance plugin for CKAN',
long_description='',
classifiers=[],
keywords='',
author='Open Knowledge Foundation',
author_email='info@okfn.org',
url='http://ckan.org/wiki/Extensions',
license='mit',
packages=find_packages(exclude=['tests']),
namespace_packages=['ckanext', 'ckanext.qa'],
include_package_data=True,
zip_safe=False,
install_requires=[
'celery==2.4.2',
'kombu==2.1.3',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests==0.6.4',
],
tests_require=[
'nose',
'mock',
],
entry_points='''
[paste.paster_command]
qa=ckanext.qa.commands:QACommand
[ckan.plugins]
qa=ckanext.qa.plugin:QAPlugin
[ckan.celery_task]
tasks=ckanext.qa.celery_import:task_imports
''',
)
|
Remove some dead code in examples.
svn path=/trunk/; revision=409 | IDEToolbarType = {
parent: Gtk.Toolbar.type,
name: "IDEToolbar",
instance_init: function(klass)
{
this.new_button = actions.get_action("new").create_tool_item();
this.open_button = actions.get_action("open").create_tool_item();
this.save_button = actions.get_action("save").create_tool_item();
this.undo_button = actions.get_action("undo").create_tool_item();
this.redo_button = actions.get_action("redo").create_tool_item();
this.execute_button = actions.get_action("execute").create_tool_item();
this.insert(this.new_button, -1);
this.insert(this.open_button, -1);
this.insert(this.save_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.undo_button, -1);
this.insert(this.redo_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.execute_button, -1);
this.show_all();
}};
IDEToolbar = new GType(IDEToolbarType);
| IDEToolbarType = {
parent: Gtk.Toolbar.type,
name: "IDEToolbar",
class_init: function(klass, prototype)
{
},
instance_init: function(klass)
{
this.new_button = actions.get_action("new").create_tool_item();
this.open_button = actions.get_action("open").create_tool_item();
this.save_button = actions.get_action("save").create_tool_item();
this.undo_button = actions.get_action("undo").create_tool_item();
this.redo_button = actions.get_action("redo").create_tool_item();
this.execute_button = actions.get_action("execute").create_tool_item();
this.insert(this.new_button, -1);
this.insert(this.open_button, -1);
this.insert(this.save_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.undo_button, -1);
this.insert(this.redo_button, -1);
this.insert(new Gtk.SeparatorToolItem(), -1);
this.insert(this.execute_button, -1);
this.show_all();
}};
IDEToolbar = new GType(IDEToolbarType);
|
Make windows bigger in this test so the captions can be read.
Index: tests/window/WINDOW_CAPTION.py
===================================================================
--- tests/window/WINDOW_CAPTION.py (revision 777)
+++ tests/window/WINDOW_CAPTION.py (working copy)
@@ -19,8 +19,8 @@
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
- w1 = window.Window(200, 200)
- w2 = window.Window(200, 200)
+ w1 = window.Window(400, 200, resizable=True)
+ w2 = window.Window(400, 200, resizable=True)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
--HG--
extra : convert_revision : svn%3A14d46d22-621c-0410-bb3d-6f67920f7d95/trunk%40781 | #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import time
import unittest
from pyglet import window
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
w1 = window.Window(400, 200, resizable=True)
w2 = window.Window(400, 200, resizable=True)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
last_time = time.time()
while not (w1.has_exit or w2.has_exit):
if time.time() - last_time > 1:
count += 1
w1.set_caption('Window caption %d' % count)
last_time = time.time()
w1.dispatch_events()
w2.dispatch_events()
w1.close()
w2.close()
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import time
import unittest
from pyglet import window
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
w1 = window.Window(200, 200)
w2 = window.Window(200, 200)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
last_time = time.time()
while not (w1.has_exit or w2.has_exit):
if time.time() - last_time > 1:
count += 1
w1.set_caption('Window caption %d' % count)
last_time = time.time()
w1.dispatch_events()
w2.dispatch_events()
w1.close()
w2.close()
if __name__ == '__main__':
unittest.main()
|
Fix TMM as normalization method from edgeR package | import numpy as np
import pandas as pd
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
class TMM(object):
def __init__(self, count_df):
r("suppressMessages(library(edgeR))")
self.count_df = count_df
def calc_size_factors(self):
# Convert pandas dataframe to R dataframe
r_dge = r.DGEList(self.count_df)
# Calculate normalization factors
r_dge = r.calcNormFactors(r_dge, method="TMM")
size_factors = (np.array(r_dge.rx2('samples').rx2("lib.size")) *
np.array(r_dge.rx2("samples").rx2("norm.factors")))
# convert to pandas series
size_factors = pd.Series(size_factors, index=self.count_df.columns)
# adjust size factors so that the maximum is 1.0
size_factors = size_factors/size_factors.max()
return size_factors
| import numpy as np
import pandas as pd
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
class TMM(object):
def __init__(self, count_df):
r("suppressMessages(library(edgeR))")
self.count_df = count_df
def calc_size_factors(self, method="TMM"):
# Convert pandas dataframe to R dataframe
r_dge = r.DGEList(self.count_df)
# Calculate normalization factors
r_dge = r.calcNormFactors(r_dge, method=method)
size_factors = (np.array(r_dge.rx2('samples').rx2("lib.size")) *
np.array(r_dge.rx2("samples").rx2("norm.factors")))
# convert to pandas series
size_factors = pd.Series(size_factors, index=self.count_df.columns)
# adjust size factors so that the maximum is 1.0
size_factors = size_factors/size_factors.max()
return size_factors
|
Change Development status to 5 - Production/Stable for next release | from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='odin',
version='0.5.6',
url='https://github.com/timsavage/odin',
license='LICENSE',
author='Tim Savage',
author_email='tim@savage.company',
description='Object Data Mapping for Python',
long_description=long_description,
packages=find_packages(),
install_requires=['six'],
extras_require={
# Documentation generation
'doc_gen': ["jinja2>=2.7"],
# Pint integration
'pint': ["pint"],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='odin',
version='0.5.6',
url='https://github.com/timsavage/odin',
license='LICENSE',
author='Tim Savage',
author_email='tim@savage.company',
description='Object Data Mapping for Python',
long_description=long_description,
packages=find_packages(),
install_requires=['six'],
extras_require={
# Documentation generation
'doc_gen': ["jinja2>=2.7"],
# Pint integration
'pint': ["pint"],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix , added type to id | <?php
namespace PureBilling\Bundle\SDKBundle\Store\V1\Customer;
use Symfony\Component\Validator\Constraints as Assert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
use PureMachine\Bundle\SDKBundle\Store\Base\BaseStore;
class UpdateCustomer extends BaseStore
{
/**
* @Store\Property(description="customer Id. (read only)")
* @Assert\NotBlank()
* @Assert\Type("string")
*/
protected $id;
/**
* @Store\Property(description="new customer email")
* @Assert\Type("string")
* @Assert\Email()
*/
protected $email;
/**
* @Store\Property(description="new metadata to associate")
* @Assert\Type("array")
*/
protected $metadata = array();
public function setMetadata($meta)
{
$this->metadata = (array) $meta;
}
}
| <?php
namespace PureBilling\Bundle\SDKBundle\Store\V1\Customer;
use Symfony\Component\Validator\Constraints as Assert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
use PureMachine\Bundle\SDKBundle\Store\Base\BaseStore;
class UpdateCustomer extends BaseStore
{
/**
* @Store\Property(description="customer Id. (read only)")
* @Assert\NotBlank()
*/
protected $id;
/**
* @Store\Property(description="new customer email")
* @Assert\Type("string")
* @Assert\Email()
*/
protected $email;
/**
* @Store\Property(description="new metadata to associate")
* @Assert\Type("array")
*/
protected $metadata = array();
public function setMetadata($meta)
{
$this->metadata = (array) $meta;
}
}
|
Add additional tests for parameters that complete code coverage for apply function. | <?php
namespace Mimic\Test;
use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;
/**
* Unit Test for apply Mimic library function.
*
* @since 0.1.0
*/
class ApplyFuncTest extends PHPUnit_Framework_TestCase {
/**
* @covers ::Mimic\Functional\apply
*/
public function testApplyExecutesClosure() {
$this->assertTrue(F\apply(function() {return true; }));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testFileExistsFunction_FileDoesNotExist() {
$this->assertFalse(F\apply(
F\wrap('file_exists', __DIR__ . '/nonexistantfile.doesnotexist')
));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testWrappedFileExistsFunction_DirectoryExists() {
$this->assertTrue(F\apply(F\wrap('file_exists', __DIR__)));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testWrappedFileExistsFunction_FileExists() {
$this->assertTrue(F\apply(F\wrap('file_exists', __FILE__)));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testFileExistsFunction_DirectoryExists() {
$this->assertTrue(F\apply('file_exists', __DIR__));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testFileExistsFunction_FileExists() {
$this->assertTrue(F\apply('file_exists', __FILE__));
}
}
| <?php
namespace Mimic\Test;
use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;
/**
* Unit Test for apply Mimic library function.
*
* @since 0.1.0
*/
class ApplyFuncTest extends PHPUnit_Framework_TestCase {
/**
* @covers ::Mimic\Functional\apply
*/
public function testApplyExecutesClosure() {
$this->assertTrue(F\apply(function() {return true; }));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testFileExistsFunction_FileDoesNotExist() {
$this->assertFalse(F\apply(
F\wrap('file_exists', __DIR__ . '/nonexistantfile.doesnotexist')
));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testFileExistsFunction_DirectoryExists() {
$this->assertTrue(F\apply(F\wrap('file_exists', __DIR__)));
}
/**
* @covers ::Mimic\Functional\apply
*/
public function testFileExistsFunction_FileExists() {
$this->assertTrue(F\apply(F\wrap('file_exists', __FILE__)));
}
}
|
Update BaseTest class (removing registry). | # -*- coding: utf-8 -*-
from django.test import TestCase
from ..models import Translation
from . import settings
from .translations import FooModel
class BaseTestCase(TestCase):
"""
Base test class mixin.
"""
@property
def languages(self):
return [language[0] for language in settings.LANGUAGES]
@property
def translation_en(self):
obj, created = Translation.objects.get_or_create(
identifier='foo',
object_id=self.instance.pk,
language='en',
field_name='title',
field_value='Hello')
return obj
@property
def translation_fr(self):
obj, created = Translation.objects.get_or_create(
identifier='foo',
object_id=self.instance.pk,
language='fr',
field_name='title',
field_value='bonjour')
return obj
def setup_models(self):
self.instance = FooModel()
| # -*- coding: utf-8 -*-
from django.test import TestCase
from ..registry import LinguistRegistry as Registry
from ..models import Translation
from . import settings
from .translations import FooModel, FooTranslation
class BaseTestCase(TestCase):
"""
Base test class mixin.
"""
@property
def languages(self):
return [language[0] for language in settings.LANGUAGES]
@property
def translation_en(self):
obj, created = Translation.objects.get_or_create(
identifier='foo',
object_id=self.instance.pk,
language='en',
field_name='title',
field_value='Hello')
return obj
@property
def translation_fr(self):
obj, created = Translation.objects.get_or_create(
identifier='foo',
object_id=self.instance.pk,
language='fr',
field_name='title',
field_value='bonjour')
return obj
def create_registry(self):
self.registry = Registry()
self.registry.register(FooTranslation)
self.instance = FooModel()
|
Fix incorrect injection of $scope for minification | export default ['config', 'Core', function (config, Core) {
return {
template: require('components/layout/partials/panel-header.directive.html'),
transclude: {
'extraButtons': '?extraButtons',
'extraTitle': '?extraTitle'
},
scope: {
panelName: "@",
panelTitle: "=panelTitle"
},
controller: ['$scope', function ($scope) {
$scope.closePanel = Core.closePanel;
}]
};
}] | export default ['config', 'Core', function (config, Core) {
return {
template: require('components/layout/partials/panel-header.directive.html'),
transclude: {
'extraButtons': '?extraButtons',
'extraTitle': '?extraTitle'
},
scope: {
panelName: "@",
panelTitle: "=panelTitle"
},
controller: function ($scope) {
$scope.closePanel = Core.closePanel;
}
};
}] |
Update Autocomplete to fix namespace bug
Update The file with backslash before InvalidArgumentException so php can find this class.
The current namespace doesn't hold this class | <?php namespace BackupManager\Laravel;
/**
* Class AutoComplete
* @package BackupManager\Laravel
*/
trait AutoComplete {
/**
* @param $dialog
* @param array $list
* @param null $default
* @throws \LogicException
* @throws InvalidArgumentException
* @internal param $question
* @return mixed
*/
public function autocomplete($dialog, array $list, $default = null) {
$validation = function ($item) use ($list) {
if ( ! in_array($item, array_values($list))) {
throw new \InvalidArgumentException("{$item} does not exist.");
}
return $item;
};
$helper = $this->getHelperSet()->get('dialog');
return $helper->askAndValidate($this->output, "<question>{$dialog}</question>", $validation, false, $default, $list);
}
}
| <?php namespace BackupManager\Laravel;
/**
* Class AutoComplete
* @package BackupManager\Laravel
*/
trait AutoComplete {
/**
* @param $dialog
* @param array $list
* @param null $default
* @throws \LogicException
* @throws InvalidArgumentException
* @internal param $question
* @return mixed
*/
public function autocomplete($dialog, array $list, $default = null) {
$validation = function ($item) use ($list) {
if ( ! in_array($item, array_values($list))) {
throw new InvalidArgumentException("{$item} does not exist.");
}
return $item;
};
$helper = $this->getHelperSet()->get('dialog');
return $helper->askAndValidate($this->output, "<question>{$dialog}</question>", $validation, false, $default, $list);
}
}
|
Fix typos: `dolphine` -> `dolphin`, `kangoroo` -> `kangaroo` | #!/usr/bin/env python
"""
Autocompletion example that displays the autocompletions like readline does by
binding a custom handler to the Tab key.
"""
from __future__ import unicode_literals
from prompt_toolkit.shortcuts import prompt, CompleteStyle
from prompt_toolkit.contrib.completers import WordCompleter
animal_completer = WordCompleter([
'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison',
'butterfly', 'cat', 'chicken', 'crocodile', 'dinosaur', 'dog', 'dolphin',
'dove', 'duck', 'eagle', 'elephant', 'fish', 'goat', 'gorilla', 'kangaroo',
'leopard', 'lion', 'mouse', 'rabbit', 'rat', 'snake', 'spider', 'turkey',
'turtle',
], ignore_case=True)
def main():
text = prompt('Give some animals: ', completer=animal_completer,
complete_style=CompleteStyle.READLINE_LIKE)
print('You said: %s' % text)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
Autocompletion example that displays the autocompletions like readline does by
binding a custom handler to the Tab key.
"""
from __future__ import unicode_literals
from prompt_toolkit.shortcuts import prompt, CompleteStyle
from prompt_toolkit.contrib.completers import WordCompleter
animal_completer = WordCompleter([
'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison',
'butterfly', 'cat', 'chicken', 'crocodile', 'dinosaur', 'dog', 'dolphine',
'dove', 'duck', 'eagle', 'elephant', 'fish', 'goat', 'gorilla', 'kangoroo',
'leopard', 'lion', 'mouse', 'rabbit', 'rat', 'snake', 'spider', 'turkey',
'turtle',
], ignore_case=True)
def main():
text = prompt('Give some animals: ', completer=animal_completer,
complete_style=CompleteStyle.READLINE_LIKE)
print('You said: %s' % text)
if __name__ == '__main__':
main()
|
Undo title to lowercase in octopress header. | <?php
function rewriteHeader($headline, $oldTag, $newTag) {
if (strpos($headline, $oldTag) === 0) {
$data = substr($headline, strlen($oldTag));
$data = str_replace('"', '', $data);
return $newTag . $data . "\n";
}
else {
return NULL;
}
}
if (count($argv) < 2) {
echo "Too few params. Need a file name to apply changes.";
exit -1;
}
$filenames = array_slice($argv, 1);
foreach ($filenames as $target) {
$filename = realpath($target);
$content = file_get_contents($filename);
$parts = explode('---', $content);
$tokens = count($parts);
$header = explode("\n", $parts[$tokens - 2]);
$body = $parts[$tokens - 1];
$newHeader = "";
foreach ($header as $headline) {
$newHeader .= rewriteHeader($headline, 'title:', 'Title:');
$newHeader .= rewriteHeader($headline, 'date:', 'Date:');
$newHeader .= rewriteHeader($headline, 'categories:', 'Tags:');
}
$newHeader .= "Category: Blog\n";
$newHeader .= "Author: Antonio Jesus Sanchez Padial\n";
file_put_contents($filename, $newHeader . $body);
}
| <?php
function rewriteHeader($headline, $oldTag, $newTag) {
if (strpos($headline, $oldTag) === 0) {
$data = substr($headline, strlen($oldTag));
$data = str_replace('"', '', $data);
return $newTag . $data . "\n";
}
else {
return NULL;
}
}
if (count($argv) < 2) {
echo "Too few params. Need a file name to apply changes.";
exit -1;
}
$filenames = array_slice($argv, 1);
foreach ($filenames as $target) {
$filename = realpath($target);
$content = file_get_contents($filename);
$parts = explode('---', $content);
$tokens = count($parts);
$header = explode("\n", $parts[$tokens - 2]);
$body = $parts[$tokens - 1];
$newHeader = "";
foreach ($header as $headline) {
$newHeader .= rewriteHeader($headline, 'Title:', 'Title:');
$newHeader .= rewriteHeader($headline, 'date:', 'Date:');
$newHeader .= rewriteHeader($headline, 'categories:', 'Tags:');
}
$newHeader .= "Category: Blog\n";
$newHeader .= "Author: Antonio Jesus Sanchez Padial\n";
file_put_contents($filename, $newHeader . $body);
}
|
Update syncdb to also regenerate the index. | from django.db.models.signals import post_syncdb
from django.conf import settings
from django.core import management
import os
import re
FIXTURE_RE = re.compile(r'^[^.]*.json$')
def load_data(sender, **kwargs):
"""
Loads fixture data after loading the last installed app
"""
if kwargs['app'].__name__ == settings.INSTALLED_APPS[-1] + ".models":
fixture_files = []
for loc in settings.INITIAL_FIXTURE_DIRS:
loc = os.path.abspath(loc)
if os.path.exists(loc):
fixture_files += os.listdir(loc)
fixture_files = filter(lambda v: FIXTURE_RE.match(v), fixture_files)
fixture_files = [os.path.join(loc, f) for f in fixture_files]
if len(fixture_files) > 0:
print "Initializing Fixtures:"
for fixture in fixture_files:
print " >> %s" % (fixture)
management.call_command('loaddata', fixture, verbosity=0)
# Update the index
print 'Generating Index'
management.call_command('index', 'all', flush=True, verbosity=1)
post_syncdb.connect(load_data)
| from django.db.models.signals import post_syncdb
from django.conf import settings
from django.core import management
import os
import re
FIXTURE_RE = re.compile(r'^[^.]*.json$')
def load_data(sender, **kwargs):
"""
Loads fixture data after loading the last installed app
"""
if kwargs['app'].__name__ == settings.INSTALLED_APPS[-1] + ".models":
fixture_files = []
for loc in settings.INITIAL_FIXTURE_DIRS:
loc = os.path.abspath(loc)
if os.path.exists(loc):
fixture_files += os.listdir(loc)
fixture_files = filter(lambda v: FIXTURE_RE.match(v), fixture_files)
fixture_files = [os.path.join(loc, f) for f in fixture_files]
if len(fixture_files) > 0:
print "Initializing Fixtures:"
for fixture in fixture_files:
print " >> %s" % (fixture)
management.call_command('loaddata', fixture, verbosity=0)
post_syncdb.connect(load_data)
|
Remove unnecessary implementation of interface method in abstract class | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
use Composer\Package\PackageInterface;
/**
* Abstract solver operation class.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
abstract class SolverOperation implements OperationInterface
{
protected $reason;
/**
* Initializes operation.
*
* @param string $reason operation reason
*/
public function __construct($reason = null)
{
$this->reason = $reason;
}
/**
* Returns operation reason.
*
* @return string
*/
public function getReason()
{
return $this->reason;
}
}
| <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
use Composer\Package\PackageInterface;
/**
* Abstract solver operation class.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
abstract class SolverOperation implements OperationInterface
{
protected $reason;
/**
* Initializes operation.
*
* @param string $reason operation reason
*/
public function __construct($reason = null)
{
$this->reason = $reason;
}
/**
* Returns operation reason.
*
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param $lock bool Whether this is an operation on the lock file
* @return string
*/
public function show($lock)
{
throw new \RuntimeException('abstract method needs to be implemented in subclass, not marked abstract for compatibility with PHP <= 5.3.8');
}
}
|
Use dict iteration compatible with Python 2 and 3 | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in iter(flowable['cast'].items()):
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in flowable['cast'].iteritems():
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] |
Handle invalid not before claim value | <?php
namespace Emarref\Jwt\Verification;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encoding;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\HeaderParameter;
use Emarref\Jwt\Token;
class NotBeforeVerifier implements VerifierInterface
{
public function verify(Token $token)
{
/** @var Claim\NotBefore $notBeforeClaim */
$notBeforeClaim = $token->getPayload()->findClaimByName(Claim\NotBefore::NAME);
if (null === $notBeforeClaim) {
return null;
}
$now = new \DateTime('now', new \DateTimeZone('UTC'));
if (!is_long($notBeforeClaim->getValue())) {
throw new \InvalidArgumentException(sprintf(
'Invalid not before timestamp "%s"',
$notBeforeClaim->getValue()
));
}
if ($now->getTimestamp() < $notBeforeClaim->getValue()) {
$notBefore = new \DateTime();
$notBefore->setTimestamp($notBeforeClaim->getValue());
throw new VerificationException(sprintf('Token must not be processed before "%s"', $notBefore->format('r')));
}
}
}
| <?php
namespace Emarref\Jwt\Verification;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encoding;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\HeaderParameter;
use Emarref\Jwt\Token;
class NotBeforeVerifier implements VerifierInterface
{
public function verify(Token $token)
{
/** @var Claim\NotBefore $notBeforeClaim */
$notBeforeClaim = $token->getPayload()->findClaimByName(Claim\NotBefore::NAME);
if (null === $notBeforeClaim) {
return null;
}
$now = new \DateTime('now', new \DateTimeZone('UTC'));
if ($now->getTimestamp() < $notBeforeClaim->getValue()) {
$notBefore = new \DateTime();
$notBefore->setTimestamp($notBeforeClaim->getValue());
throw new VerificationException(sprintf('Token must not be processed before "%s"', $notBefore->format('r')));
}
}
}
|
Fix with bookmark fragment not added. | package com.mapswithme.maps.bookmarks;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmFragmentActivity;
import com.mapswithme.util.UiUtils;
public class BookmarkListActivity extends BaseMwmFragmentActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final Toolbar toolbar = getToolbar();
toolbar.setTitle(R.string.bookmarks);
UiUtils.showHomeUpButton(toolbar);
displayToolbarAsActionBar();
}
@Override
protected int getContentLayoutResId()
{
return R.layout.activity_fragment_and_toolbar;
}
@Override
protected String getFragmentClassName()
{
return BookmarksListFragment.class.getName();
}
@Override
protected int getFragmentContentResId()
{
return R.id.fragment_container;
}
}
| package com.mapswithme.maps.bookmarks;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmFragmentActivity;
import com.mapswithme.util.UiUtils;
public class BookmarkListActivity extends BaseMwmFragmentActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final Toolbar toolbar = getToolbar();
toolbar.setTitle(R.string.bookmarks);
UiUtils.showHomeUpButton(toolbar);
displayToolbarAsActionBar();
}
@Override
protected int getContentLayoutResId()
{
return R.layout.activity_fragment_and_toolbar;
}
@Override
protected int getFragmentContentResId()
{
return R.id.fragment_container;
}
}
|
Update stable channel builders to 1.6 branch
Review URL: https://codereview.chromium.org/494783003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291643 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.standalone_deps_path = '/' + branch + '/deps/standalone.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 4),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/1.6', 2, '-stable', 1),
Channel('integration', 'branches/dartium_integration', 3, '-integration', 3),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
| # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.standalone_deps_path = '/' + branch + '/deps/standalone.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 4),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/1.5', 2, '-stable', 1),
Channel('integration', 'branches/dartium_integration', 3, '-integration', 3),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
|
Throw meaningful exception if table does not exist | // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
var data = require('../../data'),
notifications = require('../../notifications'),
attachOperators = require('../../query/attachOperators'),
logger = require('../../logger');
module.exports = function (configuration) {
var dataProvider = data(configuration),
notificationsClient = notifications(configuration.notifications).getClient();
return function (req, res, next) {
req.azureMobile = {
req: req,
res: res,
data: dataProvider,
push: notificationsClient,
configuration: configuration,
logger: logger,
tables: function (name) {
if(!configuration.tables[name])
throw new Error("The table '" + name + "' does not exist.")
return attachOperators(name, dataProvider(configuration.tables[name]));
}
};
next();
};
};
| // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
var data = require('../../data'),
notifications = require('../../notifications'),
attachOperators = require('../../query/attachOperators'),
logger = require('../../logger');
module.exports = function (configuration) {
var dataProvider = data(configuration),
notificationsClient = notifications(configuration.notifications).getClient();
return function (req, res, next) {
req.azureMobile = {
req: req,
res: res,
data: dataProvider,
push: notificationsClient,
configuration: configuration,
logger: logger,
tables: function (name) {
return attachOperators(name, dataProvider(configuration.tables[name]));
}
};
next();
};
};
|
Allow user to select bypass level | import logging
import wpilib
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher
"""
def __init__(self, period, bypassLevel=logging.WARN):
'''
:param period: Wait period (in seconds) between logs
'''
self.period = period
self.loggingLoop = True
self._last_log = -period
self.bypassLevel = bypassLevel
def filter(self, record):
"""Performs filtering action for logger"""
self._refresh_logger()
return self.parent.loggingLoop or record.levelno >= self.bypassLevel
def _refresh_logger(self):
"""Determine if the log wait period has passed"""
now = wpilib.Timer.getFPGATimestamp()
self.loggingLoop = False
if now - self.__last_log > self.logging_interval:
self.loggingLoop = True
self.__last_log = now
| import logging
import wpilib
class PeriodicFilter:
"""
Periodic Filter to help keep down clutter in the console.
Simply add this filter to your logger and the logger will
only print periodically.
The logger will always print logging levels of WARNING or higher
"""
def __init__(self, period):
'''
:param period: Wait period (in seconds) between logs
'''
self.period = period
self.loggingLoop = True
self._last_log = -period
def filter(self, record):
"""Performs filtering action for logger"""
self._refresh_logger()
return self.parent.loggingLoop or record.levelno > logging.INFO
def _refresh_logger(self):
"""Determine if the log wait period has passed"""
now = wpilib.Timer.getFPGATimestamp()
self.loggingLoop = False
if now - self.__last_log > self.logging_interval:
self.loggingLoop = True
self.__last_log = now
|
Remove unneeded comma from BoxHelper test | (function () {
'use strict';
var parameters = {
diameter: 10
};
var geometries;
QUnit.module( "Extras - Helpers - BoxHelper", {
beforeEach: function() {
var greenMaterial = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
// Test with a normal cube and a box helper
var boxGeometry = new THREE.BoxGeometry( parameters.diameter );
var box = new THREE.Mesh( boxGeometry, greenMaterial );
var boxHelper = new THREE.BoxHelper( box );
// The same should happen with a comparable sphere
var sphereGeometry = new THREE.SphereGeometry( parameters.diameter / 2 );
var sphere = new THREE.Mesh( sphereGeometry, greenMaterial );
var sphereBoxHelper = new THREE.BoxHelper( sphere );
// Note that unlike what I'd like to, these doesn't check the equivalency of the two generated geometries
geometries = [ boxHelper.geometry, sphereBoxHelper.geometry ];
}
});
QUnit.test( "standard geometry tests", function( assert ) {
runStdGeometryTests( assert, geometries );
});
})();
| (function () {
'use strict';
var parameters = {
diameter: 10,
};
var geometries;
QUnit.module( "Extras - Helpers - BoxHelper", {
beforeEach: function() {
var greenMaterial = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
// Test with a normal cube and a box helper
var boxGeometry = new THREE.BoxGeometry( parameters.diameter );
var box = new THREE.Mesh( boxGeometry, greenMaterial );
var boxHelper = new THREE.BoxHelper( box );
// The same should happen with a comparable sphere
var sphereGeometry = new THREE.SphereGeometry( parameters.diameter / 2 );
var sphere = new THREE.Mesh( sphereGeometry, greenMaterial );
var sphereBoxHelper = new THREE.BoxHelper( sphere );
// Note that unlike what I'd like to, these doesn't check the equivalency of the two generated geometries
geometries = [ boxHelper.geometry, sphereBoxHelper.geometry ];
}
});
QUnit.test( "standard geometry tests", function( assert ) {
runStdGeometryTests( assert, geometries );
});
})();
|
feat: Add extra default params test | describe("About Functions", function () {
describe("Default Parameters", function () {
it("should understand default parameters basic usage", function () {
function greeting(string = 'party') {
return 'Welcome to the ' + string + ' pal!';
}
expect(greeting()).toEqual(FILL_ME_IN);
expect(greeting('get together')).toEqual(FILL_ME_IN);
expect(undefined).toEqual(FILL_ME_IN);
expect(null).toEqual(FILL_ME_IN);
function getDefaultValue() {
return 'party';
}
function greetingAgain(string = getDefaultValue()) {
return 'Welcome to the ' + string + ' pal!';
}
expect(greetingAgain()).toEqual(FILL_ME_IN);
});
});
// describe('Rest Paramaters', function() {
//
// })
//
// describe('Spread Parameters', function() {
//
// })
//
// describe('Arrow Functions', function() {
//
// })
});
| describe("About Functions", function () {
describe("Default Parameters", function () {
it("should understand default parameters basic usage", function () {
function greeting(string = 'party') {
return 'Welcome to the ' + string + ' pal!';
}
expect(greeting()).toEqual(FILL_ME_IN);
expect(greeting('get together')).toEqual(FILL_ME_IN);
function getDefaultValue() {
return 'party';
}
function greetingAgain(string = getDefaultValue()) {
return 'Welcome to the ' + string + ' pal!';
}
expect(greetingAgain()).toEqual(FILL_ME_IN);
expect(greetingAgain('get together')).toEqual(FILL_ME_IN);
});
});
// describe('Rest Paramaters', function() {
//
// })
//
// describe('Spread Parameters', function() {
//
// })
//
// describe('Arrow Functions', function() {
//
// })
});
|
Fix wrong table preferrence for role_user | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('auth.table'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
|
Mark as stable and bump to 1.0 | from setuptools import setup
VERSION = '1.0'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| from setuptools import setup
VERSION = '0.3'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
|
Use inquirer as constant name | const Configstore = require('configstore');
const Promise = require('promise');
const inquirer = require('inquirer');
const pkg = require('../../../../package.json');
const prompts = require('./setup-prompts');
class ServerConfig {
static DEFAULTS = {
'isFirstRun': true,
'serverPort': '3000'
}
constructor(defaults = this.constructor.DEFAULTS) {
this.db = new Configstore(pkg.name, defaults);
}
prompt() {
return new Promise((resolve, reject) => {
console.log('> Preparing initial setup\n');
this.db.set('isFirstRun', false);
inquirer.prompt(prompts, answers => {
Object.keys(answers).map(key => {
return this.db.set(key, answers[key]);
});
resolve('\n> Setup finished!\n');
});
});
}
}
module.exports = new ServerConfig();
| const Configstore = require('configstore');
const Promise = require('promise');
const inq = require('inquirer');
const pkg = require('../../../../package.json');
const prompts = require('./setup-prompts');
class ServerConfig {
static DEFAULTS = {
'isFirstRun': true,
'serverPort': '3000'
}
constructor(defaults = this.constructor.DEFAULTS) {
this.db = new Configstore(pkg.name, defaults);
}
prompt() {
return new Promise((resolve, reject) => {
console.log('> Preparing initial setup\n');
this.db.set('isFirstRun', false);
inq.prompt(prompts, answers => {
Object.keys(answers).map(key => {
return this.db.set(key, answers[key]);
});
resolve('\n> Setup finished!\n');
});
});
}
}
module.exports = new ServerConfig();
|
Add opacity support for colorscale interpolation | /**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var tinycolor = require('tinycolor2');
var isNumeric = require('fast-isnumeric');
var Lib = require('../../lib');
var Color = require('../color');
module.exports = function makeScaleFunction(scl, cmin, cmax) {
var N = scl.length,
domain = new Array(N),
range = new Array(N),
si;
for(var i = 0; i < N; i++) {
si = scl[i];
domain[i] = cmin + si[0] * (cmax - cmin);
range[i] = tinycolor(si[1]).toRgb();
}
var sclFunc = d3.scale.linear()
.domain(domain)
.interpolate(d3.interpolateObject)
.range(range);
return function(v) {
if(isNumeric(v)) {
var sclVal = Lib.constrain(v, cmin, cmax),
colorObj = sclFunc(sclVal);
return tinycolor(colorObj).toRgbString();
}
else if(tinycolor(v).isValid()) return v;
else return Color.defaultLine;
};
};
| /**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var tinycolor = require('tinycolor2');
var isNumeric = require('fast-isnumeric');
var Lib = require('../../lib');
var Color = require('../color');
module.exports = function makeScaleFunction(scl, cmin, cmax) {
var N = scl.length,
domain = new Array(N),
range = new Array(N),
si;
for(var i = 0; i < N; i++) {
si = scl[i];
domain[i] = cmin + si[0] * (cmax - cmin);
range[i] = si[1];
}
var sclFunc = d3.scale.linear()
.domain(domain)
.interpolate(d3.interpolateRgb)
.range(range);
return function(v) {
if(isNumeric(v)) {
var sclVal = Lib.constrain(v, cmin, cmax);
return sclFunc(sclVal);
}
else if(tinycolor(v).isValid()) return v;
else return Color.defaultLine;
};
};
|
Add linked list node to utils | class Node_Tree {
constructor(val) {
this.val = val;
this.parent = null;
this.children = [];
}
}
class Node_Trie {
constructor(val) {
/*
** The node stores a single character as its value.
** Child nodes are stored in an object instead of an array for constant-time lookup
** because every child node will have a unique value/letter
*/
this.val = val;
this.children = {};
}
}
class Node_BST {
constructor(key, val) {
/*
** Key should be an integer, for proper placement of the node in a Binary Search Tree
*/
this.key = key;
this.val = val;
this.parent = null;
this.left = null;
this.right = null;
}
}
class Node_LinkedList {
constructor(val) {
/*
** A block of information stored in a doubly linked list.
** Stores references to the next and previous nodes.
*/
this.val = val;
this.next = null;
this.prev = null;
}
}
export { Node_Tree, Node_Trie, Node_BST }; | class Node_Tree {
constructor(val) {
this.val = val;
this.parent = null;
this.children = [];
}
}
class Node_Trie {
constructor(val) {
/*
** The node stores a single character as its value.
** Child nodes are stored in an object instead of an array for constant-time lookup
** because every child node will have a unique value/letter
*/
this.val = val;
this.children = {};
}
}
class Node_BST {
constructor(key, val) {
/*
** Key should be an integer, for proper placement of the node in a Binary Search Tree
*/
this.key = key;
this.val = val;
this.parent = null;
this.left = null;
this.right = null;
}
}
export { Node_Tree, Node_Trie, Node_BST }; |
Create layout for log in page | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Container,
TextInput,
Label,
Text,
View,
Button,
} from 'react-native';
export default class LoginScreen extends Component {
static navigationOptions = {
title: 'Welcome Back',
};
render() {
return (
<View>
<Text>Email</Text>
<TextInput
style={styles.textInput}
/>
<Text>Password</Text>
<TextInput
secureTextEntry={true}
style={styles.textInput}
/>
<Button
onPress={() => navigate('#')}
title="Login" />
</View>
);
}
}
const styles = StyleSheet.create({
textInput: {
height: 80,
fontSize: 30,
backgroundColor: '#FFF',
},
});
| import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Container,
TextInput,
Label,
Text,
View,
Button,
} from 'react-native';
export default class LoginScreen extends Component {
static navigationOptions = {
title: 'Login below',
};
render() {
return (
<View>
<View>
<Label text="Email" />
<TextInput
style={styles.textInput}
/>
</View>
<View>
<Label text="Password" />
<TextInput
secureTextEntry={true}
style={styles.textInput}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
textInput: {
height: 80,
fontSize: 30,
backgroundColor: '#FFF',
},
});
|
Add code coverage to karma | module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai-jquery', 'jquery-2.1.0', 'chai', 'sinon-chai', 'fixture'],
files: [
'public/javascripts/vendor/d3.v3.min.js',
'public/javascripts/traffic.js',
'tests/**/*Spec.js',
'tests/fixtures/**/*'
],
exclude: [
'**/*.swp'
],
preprocessors: {
'public/javascripts/*.js': ['coverage'],
'tests/**/*.json' : ['json_fixtures']
},
jsonFixturesPreprocessor: {
variableName: '__json__'
},
reporters: ['progress', 'coverage'],
coverageReporter: {
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'lcov-report' },
],
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
});
};
| module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai-jquery', 'jquery-2.1.0', 'chai', 'sinon-chai', 'fixture'],
files: [
'public/javascripts/vendor/d3.v3.min.js',
'public/javascripts/traffic.js',
'tests/**/*Spec.js',
'tests/fixtures/**/*'
],
exclude: [
'**/*.swp'
],
preprocessors: {
'tests/**/*.json' : ['json_fixtures']
},
jsonFixturesPreprocessor: {
variableName: '__json__'
},
reporters: ['progress', 'coverage'],
coverageReporter: {
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'lcov-report' },
],
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
});
};
|
Fix one more flake8 error. | from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^checks$', 'what_json.views.checks'),
url(r'^add_torrent$', 'what_json.views.add_torrent'),
url(r'^sync$', 'what_json.views.sync'),
url(r'^sync_replicas$', 'what_json.views.sync_replicas'),
url(r'^update_freeleech$', 'what_json.views.update_freeleech'),
url(r'^load_balance$', 'what_json.views.run_load_balance'),
url(r'^move_torrent$', 'what_json.views.move_torrent_to_location'),
url(r'^torrents_info$', 'what_json.views.torrents_info'),
url(r'^refresh_whattorrent$', 'what_json.views.refresh_whattorrent'),
url(r'^what_proxy$', 'what_json.views.what_proxy'),
)
| from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^checks$', 'what_json.views.checks'),
url(r'^add_torrent$', 'what_json.views.add_torrent'),
url(r'^sync$', 'what_json.views.sync'),
url(r'^sync_replicas$', 'what_json.views.sync_replicas'),
url(r'^update_freeleech$', 'what_json.views.update_freeleech'),
url(r'^load_balance$', 'what_json.views.run_load_balance'),
url(r'^move_torrent$', 'what_json.views.move_torrent_to_location'),
url(r'^torrents_info$', 'what_json.views.torrents_info'),
url(r'^refresh_whattorrent$', 'what_json.views.refresh_whattorrent'),
url(r'^what_proxy$', 'what_json.views.what_proxy'),
)
|
Make a sub request to generate homepage | <?php
use Gitiki\Exception\PageNotFoundException;
use Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpKernel\Exception\HttpException,
Symfony\Component\HttpKernel\HttpKernelInterface;
$app->get('/', function () use ($app) {
return $app->handle(Request::create('/_index'), HttpKernelInterface::SUB_REQUEST, false);
})
->bind('homepage')
;
$app->get('/_menu', function () use ($app) {
try {
$page = $app->getPage('_menu');
} catch (PageNotFoundException $e) {
return '';
}
return $app['twig']->render('menu.html.twig', [
'menu' => $page->getMetas(),
]);
});
$app->get('/{page}', function ($page) use ($app) {
try {
$page = $app->getPage($page);
} catch (PageNotFoundException $e) {
throw new HttpException(404, sprintf('The page "%s" was not found.', $e->getPage()), $e);
}
return $app['twig']->render('page.html.twig', [
'page' => $page,
]);
})
->assert('page', '[\w\d-]+')
->bind('page')
;
| <?php
use Gitiki\Exception\PageNotFoundException;
use Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpKernel\Exception\HttpException;
$app->get('/', function () use ($app) {
try {
$page = $app->getPage('_index');
} catch (PageNotFoundException $e) {
throw new HttpException(404, sprintf('The page "%s" was not found.', $e->getPage()), $e);
}
return $app['twig']->render('page.html.twig', [
'page' => $page,
]);
})
->bind('homepage')
;
$app->get('/_menu', function () use ($app) {
try {
$page = $app->getPage('_menu');
} catch (PageNotFoundException $e) {
return '';
}
return $app['twig']->render('menu.html.twig', [
'menu' => $page->getMetas(),
]);
});
$app->get('/{page}', function ($page) use ($app) {
try {
$page = $app->getPage($page);
} catch (PageNotFoundException $e) {
throw new HttpException(404, sprintf('The page "%s" was not found.', $e->getPage()), $e);
}
return $app['twig']->render('page.html.twig', [
'page' => $page,
]);
})
->assert('page', '[\w\d-]+')
->bind('page')
;
|
[FIX] Correct scope in policy engine. | const Promise = require('bluebird');
const requireAll = require('require-all');
const policies = requireAll(__dirname+'/../../config/policies/');
function PolicyEngine() {
var _this = this;
this.policiesOrder = [
'invoice_policy',
'bridge_policy',
'user_policy',
'no_policy'
]
this.policies = [];
this.policiesOrder.forEach(function(name) {
_this.policies.push({
name: name,
policy: policies[name]
});
});
}
PolicyEngine.prototype.determinePolicy = function determinePolicy(payment) {
var match;
var _this = this;
return new Promise(function(resolve, reject) {
var series = []
var policyMatch;
_this.policies.ForEach(function(policy) {
var asyncPolicy = Promise.promisify(policy);
series.push(function(next) {
if (policyMatch) {
return next();
}
asyncPolicy.doesApply(payment)
.then(function() {
policyMatch = policy;
})
.error(next);
})
})
async.series(series, function(error) {
if (error) {
return
} else {
resolve(policy);
}
});
});
}
module.exports = PolicyEngine;
| const Promise = require('bluebird');
const requireAll = require('require-all');
const policies = requireAll(__dirname+'/../../config/policies/');
function PolicyEngine() {
this.policiesOrder = [
'invoice_policy',
'bridge_policy',
'user_policy',
'no_policy'
]
this.policies = [];
policiesOrder.forEach(function(name) {
this.policies.push({
name: name
policy: policies[name]
});
});
}
PolicyEngine.prototype.determinePolicy = function determinePolicy(payment) {
var match;
var _this = this;
return new Promise(function(resolve, reject) {
var series = []
var policyMatch;
_this.policies.ForEach(function(policy) {
var asyncPolicy = Promise.promisify(policy);
series.push(function(next) {
if (policyMatch) {
return next();
}
asyncPolicy.doesApply(payment)
.then(function() {
policyMatch = policy;
})
.error(next);
})
})
async.series(series, function(error) {
if (error) {
return
} else {
resolve(policy);
}
});
});
}
module.exports = PolicyEngine;
|
Order STHs by timestamp, descendingly | 'use strict';
/* Controllers */
angular.module('myApp.controllers', []).
controller('LogServerCtrl', ['$scope', '$routeParams', 'logservers', function($scope, $routeParams, logservers) {
$scope.logserver = $.grep(logservers.all(), function(e) { return e.id === $routeParams.id})[0];
logservers.lookupSthForLogServer($scope.logserver).then(function(results) {
$scope.logserver.sth = _.transform(results.data, function(accum, goodOrBadSet, k) {
accum[k] = _.chain(goodOrBadSet)
.map(function(el) {
el.timestamp = moment(parseInt(el.timestamp,10));
return el;
})
.sortBy('timestamp')
.reverse()
.value()
});
});
}])
.controller('LogServersCtrl', ['$scope', 'logservers', function($scope, logservers) {
$scope.logservers = logservers.all();
}]);
| 'use strict';
/* Controllers */
angular.module('myApp.controllers', []).
controller('LogServerCtrl', ['$scope', '$routeParams', 'logservers', function($scope, $routeParams, logservers) {
$scope.logserver = $.grep(logservers.all(), function(e) { return e.id === $routeParams.id})[0];
logservers.lookupSthForLogServer($scope.logserver).then(function(results) {
$scope.logserver.sth = _.transform(results.data, function(accum, goodOrBadSet, k) {
accum[k] = _.map(goodOrBadSet, function(el) {
el.timestamp = moment(parseInt(el.timestamp,10));
return el;
});
});
});
}])
.controller('LogServersCtrl', ['$scope', 'logservers', function($scope, logservers) {
$scope.logservers = logservers.all();
}]);
|
Support inheritance from Tier Shift
The initialization script of Tier Shift was calling `getTemplate`, which poisoned the dex entries with the `cached` flag | exports.BattleScripts = {
init: function () {
for (var i in this.data.Pokedex) {
if (!this.data.FormatsData[i]) continue;
var tier = this.data.FormatsData[i].tier;
var adjustment = 0;
if (!tier && this.data.Pokedex[i].baseSpecies) {
// mega evolutions get the same stat boost as their base forme
tier = this.data.FormatsData[toId(this.data.Pokedex[i].baseSpecies)].tier;
}
switch (tier) {
case 'BL':
case 'UU':
adjustment = 5;
break;
case 'BL2':
case 'RU':
adjustment = 10;
break;
case 'BL3':
case 'NU':
case 'BL4':
case 'PU':
case 'NFE':
case 'LC Uber':
case 'LC':
adjustment = 15;
}
if (adjustment) {
for (var j in this.data.Pokedex[i].baseStats) {
this.modData('Pokedex', i).baseStats[j] = this.clampIntRange(this.data.Pokedex[i].baseStats[j] + adjustment, 1, 255);
}
}
}
}
};
| exports.BattleScripts = {
init: function () {
for (var i in this.data.Pokedex) {
var tier = '';
var adjustment = 0;
// mega evolutions get the same stat boost as their base forme
if (this.data.FormatsData[i]) tier = this.data.FormatsData[i].tier || this.data.FormatsData[toId(this.getTemplate(i).baseSpecies)].tier;
switch (tier) {
case 'BL':
case 'UU':
adjustment = 5;
break;
case 'BL2':
case 'RU':
adjustment = 10;
break;
case 'BL3':
case 'NU':
case 'BL4':
case 'PU':
case 'NFE':
case 'LC Uber':
case 'LC':
adjustment = 15;
}
if (adjustment) {
for (var j in this.data.Pokedex[i].baseStats) {
this.modData('Pokedex', i).baseStats[j] = this.clampIntRange(this.data.Pokedex[i].baseStats[j] + adjustment, 1, 255);
}
}
}
}
};
|
Use single binding with '*' as scheme. | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String subId, String name, DeployState deployState) {
super(parent, subId, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("*://*/logs");
addComponent(logHandler);
}
}
| // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String subId, String name, DeployState deployState) {
super(parent, subId, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("http://*/logs", "https://*/logs");
addComponent(logHandler);
}
}
|
Add tearDown phase to unlink the test file | <?php
use Maghead\Manager\ConfigManager;
use Maghead\Config;
use Maghead\ConfigLoader;
class ConfigManagerTest extends PHPUnit_Framework_TestCase
{
const TEST_CONFIG = 'tests/.database.config.yml';
public function setUp()
{
copy('tests/database.yml', self::TEST_CONFIG);
parent::setUp();
}
public function tearDown()
{
if (file_exists(self::TEST_CONFIG)) {
unlink(self::TEST_CONFIG);
}
}
public function testAddNodeWithoutOptions()
{
$loader = new ConfigLoader;
$config = $loader->loadFromFile(self::TEST_CONFIG);
// var_dump($config);
$manager = new ConfigManager($config);
$manager->addNode('shard1', 'mysql:host=localhost;dbname=shard1');
$manager->addNode('shard2', 'mysql:host=localhost;dbname=shard2');
$ret = $manager->save(self::TEST_CONFIG);
$this->assertTrue($ret);
$this->assertFileEquals('tests/config/testAddNodeWithoutOptions.expected', self::TEST_CONFIG);
}
}
| <?php
use Maghead\Manager\ConfigManager;
use Maghead\Config;
use Maghead\ConfigLoader;
class ConfigManagerTest extends PHPUnit_Framework_TestCase
{
const TEST_CONFIG = 'tests/.database.config.yml';
public function setUp()
{
copy('tests/database.yml', self::TEST_CONFIG);
parent::setUp();
}
public function tearDown()
{
}
public function testAddNodeWithoutOptions()
{
$loader = new ConfigLoader;
$config = $loader->loadFromFile(self::TEST_CONFIG);
// var_dump($config);
$manager = new ConfigManager($config);
$manager->addNode('shard1', 'mysql:host=localhost;dbname=shard1');
$manager->addNode('shard2', 'mysql:host=localhost;dbname=shard2');
$ret = $manager->save(self::TEST_CONFIG);
$this->assertTrue($ret);
$this->assertFileEquals('tests/config/testAddNodeWithoutOptions.expected', self::TEST_CONFIG);
}
}
|
Use on('exit') instead of on('close') | var assert = require("chai").assert;
var path = require("path");
var compiler = require(path.join(__dirname, ".."));
var childProcess = require("child_process");
var _ = require("lodash");
var fixturesDir = path.join(__dirname, "fixtures");
function prependFixturesDir(filename) {
return path.join(fixturesDir, filename);
}
describe("#compile", function() {
it("works with --yes", function (done) {
// Use a timeout of 10 seconds because Travis on Linux can be slow to build.
this.timeout(10000);
var opts = {yes: true, output: "/dev/null", verbose: true, cwd: fixturesDir};
var compileProcess = compiler.compile(prependFixturesDir("Parent.elm"), opts);
compileProcess.on("exit", function(exitCode) {
assert.equal(exitCode, 0, "Expected elm-make to have exit code 0");
done();
});
});
});
| var assert = require("chai").assert;
var path = require("path");
var compiler = require(path.join(__dirname, ".."));
var childProcess = require("child_process");
var _ = require("lodash");
var fixturesDir = path.join(__dirname, "fixtures");
function prependFixturesDir(filename) {
return path.join(fixturesDir, filename);
}
describe("#compile", function() {
it("works with --yes", function (done) {
// Use a timeout of 10 seconds because Travis on Linux can be slow to build.
this.timeout(10000);
var opts = {yes: true, output: "/dev/null", verbose: true, cwd: fixturesDir};
var compileProcess = compiler.compile(prependFixturesDir("Parent.elm"), opts);
compileProcess.on("close", function(exitCode) {
assert.equal(exitCode, 0, "Expected elm-make to have exit code 0");
done();
});
});
});
|
Fix URL to renamed github repo. | import os
from setuptools import setup
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='pykismet3',
version='0.1.0',
description='A Python 3 module for the Akismet spam comment-spam-detection web service.',
long_description=(read('README.md')),
url='https://github.com/grundleborg/pykismet3',
license='MIT',
author='George Goldberg',
author_email='george@grundleborg.com',
py_modules=['pykismet3'],
include_package_data=True,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
install_requires=[ "requests", ],
)
| import os
from setuptools import setup
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='pykismet3',
version='0.1.0',
description='A Python 3 module for the Akismet spam comment-spam-detection web service.',
long_description=(read('README.md')),
url='https://github.com/grundleborg/pykismet',
license='MIT',
author='George Goldberg',
author_email='george@grundleborg.com',
py_modules=['pykismet3'],
include_package_data=True,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
install_requires=[ "requests", ],
)
|
Add a link to the user profile | @extends('layouts.app')
@section('title', 'Leaderboard')
@section('content')
<h1>Leaderboard</h1>
<div class="row">
@foreach ($users as $user)
<div class="col-lg-6">
<div class="card mb-4">
<div class="card-block">
<div class="d-flex align-items-center">
{!! avatar($user)->medium()->link() !!}
<div class="d-flex flex-column pl-3">
<p class="lead my-0"><a href="{{ route('profile', $user) }}">{{ $user->name }}</a></p>
<p class="mt-1 mb-0">{{ number_format($user->countBestAnswers()) }} Best Answer {{ str_plural('Award', $user->countBestAnswers()) }}</p>
<p class="mt-1 mb-0">{{ number_format($user->points) }} Experience</p>
</div>
</div>
</div>
</div>
</div>
@endforeach
</div>
@endsection | @extends('layouts.app')
@section('title', 'Leaderboard')
@section('content')
<h1>Leaderboard</h1>
<div class="row">
@foreach ($users as $user)
<div class="col-lg-6">
<div class="card mb-4">
<div class="card-block">
<div class="d-flex align-items-center">
{!! avatar($user)->medium()->link() !!}
<div class="d-flex flex-column pl-3">
<p class="lead my-0">{{ $user->name }}</p>
<p class="mt-1 mb-0">{{ number_format($user->countBestAnswers()) }} Best Answer {{ str_plural('Award', $user->countBestAnswers()) }}</p>
<p class="mt-1 mb-0">{{ number_format($user->points) }} Experience</p>
</div>
</div>
</div>
</div>
</div>
@endforeach
</div>
@endsection |
Remove extraneous commas for IE |
//
// Main entry point.
//
require.config( {
paths: {
'jquery' : "jquery-1.7.1.min",
'jquery-ui' : "jquery-ui-1.8.16.custom.min",
'jquery-temporaryClass' : "jquery.temporaryClass",
'mustache' : "require-mustache"
},
shim: {
'jquery' : {
exports: "jQuery"
},
'jquery-ui' : {
exports: "jQuery.ui",
deps: ["jquery"]
},
'jquery-temporaryClass' : {
exports: "jQuery.fn.temporaryClass",
deps: ["jquery"]
}
}
} );
// Require Argumenta
require( ["argumenta"], function( undefined ) {
// Argumenta is loaded & the app is running...
} );
|
//
// Main entry point.
//
require.config( {
paths: {
'jquery' : "jquery-1.7.1.min",
'jquery-ui' : "jquery-ui-1.8.16.custom.min",
'jquery-temporaryClass' : "jquery.temporaryClass",
'mustache' : "require-mustache"
},
shim: {
'jquery' : {
exports: "jQuery",
},
'jquery-ui' : {
exports: "jQuery.ui",
deps: ["jquery"],
},
'jquery-temporaryClass' : {
exports: "jQuery.fn.temporaryClass",
deps: ["jquery"]
}
}
} );
// Require Argumenta
require( ["argumenta"], function( undefined ) {
// Argumenta is loaded & the app is running...
} );
|
Add name and git url | Package.describe({
summary: "Google's Material Design based Bootstrap 3 theme.",
version: "0.1.2",
name: 'html5cat:bootstrap-material-design',
git: 'https://github.com/html5cat/bootstrap-material-design.git'
// git: "https://github.com/FezVrasta/bootstrap-material-design.git"
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@0.9.3');
api.use(['mizzao:bootstrap-3@3.2.0', 'jquery'], 'client');
api.addFiles([
// 'bootstrap-material-design/css-compiled/material-wfont.css',
'bootstrap-material-design/css-compiled/material.css',
'bootstrap-material-design/css-compiled/ripples.css',
'bootstrap-material-design/scripts/ripples.js',
'bootstrap-material-design/scripts/material.js',
'bootstrap-material-design/icons/icons-material-design.css',
'bootstrap-material-design/icons/fonts/Material-Design.eot',
'bootstrap-material-design/icons/fonts/Material-Design.svg',
'bootstrap-material-design/icons/fonts/Material-Design.ttf',
'bootstrap-material-design/icons/fonts/Material-Design.woff'
], 'client', {bare: true});
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('html5cat:bootstrap-material-design');
// api.addFiles('html5cat:bootstrap-material-design-tests.js');
});
| Package.describe({
summary: "Google's Material Design based Bootstrap 3 theme.",
version: "0.1.0",
// git: "https://github.com/FezVrasta/bootstrap-material-design.git"
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@0.9.3');
api.use(['mizzao:bootstrap-3@3.2.0', 'jquery'], 'client');
api.addFiles([
// 'bootstrap-material-design/css-compiled/material-wfont.css',
'bootstrap-material-design/css-compiled/material.css',
'bootstrap-material-design/css-compiled/ripples.css',
'bootstrap-material-design/scripts/ripples.js',
'bootstrap-material-design/scripts/material.js',
'bootstrap-material-design/icons/icons-material-design.css',
'bootstrap-material-design/icons/fonts/Material-Design.eot',
'bootstrap-material-design/icons/fonts/Material-Design.svg',
'bootstrap-material-design/icons/fonts/Material-Design.ttf',
'bootstrap-material-design/icons/fonts/Material-Design.woff'
], 'client', {bare: true});
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('html5cat:bootstrap-material-design');
// api.addFiles('html5cat:bootstrap-material-design-tests.js');
});
|
Fix PHP unit tests with latest version of Redis. | <?php
require_once dirname(__FILE__).'/CredisClusterTest.php';
class CredisStandaloneClusterTest extends CredisClusterTest
{
protected $useStandalone = TRUE;
protected function tearDown()
{
if($this->cluster) {
foreach($this->cluster->clients() as $client){
if($client->isConnected()) {
$client->close();
}
}
$this->cluster = NULL;
}
}
public function testMasterSlave()
{
$this->tearDown();
$this->cluster = new Credis_Cluster(array($this->redisConfig[0],$this->redisConfig[6]), 2, $this->useStandalone);
$this->assertTrue($this->cluster->client('master')->set('key','value'));
$this->waitForSlaveReplication();
$this->assertEquals('value',$this->cluster->client('slave')->get('key'));
$this->assertEquals('value',$this->cluster->get('key'));
$this->setExpectedExceptionShim('CredisException','READONLY You can\'t write against a read only replica.');
$this->cluster->client('slave')->set('key2','value');
}
}
| <?php
require_once dirname(__FILE__).'/CredisClusterTest.php';
class CredisStandaloneClusterTest extends CredisClusterTest
{
protected $useStandalone = TRUE;
protected function tearDown()
{
if($this->cluster) {
foreach($this->cluster->clients() as $client){
if($client->isConnected()) {
$client->close();
}
}
$this->cluster = NULL;
}
}
public function testMasterSlave()
{
$this->tearDown();
$this->cluster = new Credis_Cluster(array($this->redisConfig[0],$this->redisConfig[6]), 2, $this->useStandalone);
$this->assertTrue($this->cluster->client('master')->set('key','value'));
$this->waitForSlaveReplication();
$this->assertEquals('value',$this->cluster->client('slave')->get('key'));
$this->assertEquals('value',$this->cluster->get('key'));
$this->setExpectedExceptionShim('CredisException','READONLY You can\'t write against a read only slave.');
$this->cluster->client('slave')->set('key2','value');
}
}
|
Fix for uploading new images into a record which exists
git-svn-id: 556f41d716a3fdd6f7eefe65000ef9c8a0afec4c@30712 ee427ae8-e902-0410-961c-c3ed070cd9f9 | <?php
class sfValidatorImageJCroppable extends sfValidatorBase
{
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
$this->addRequiredOption('fieldName');
$this->addRequiredOption('fieldValue');
$this->addMessage('badcrop', 'Please select a larger area to crop');
}
protected function doClean($values)
{
$fieldName = $this->getOption('fieldName');
$fieldValue = $this->getOption('fieldValue');
/**
* If there was previously no image and none has been uploaded then pass
*/
if (empty($fieldValue) && empty($values[$fieldName]))
{
return $values;
}
if ($values[$fieldName . '_x1'] && $values[$fieldName . '_x1'] == $values[$fieldName . '_x2'])
{
throw new sfValidatorError($this, 'badcrop');
}
if ($values[$fieldName . '_y1'] && $values[$fieldName . '_y1'] == $values[$fieldName . '_y2'])
{
throw new sfValidatorError($this, 'badcrop');
}
return $values;
}
} | <?php
class sfValidatorImageJCroppable extends sfValidatorBase
{
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
$this->addRequiredOption('fieldName');
$this->addRequiredOption('fieldValue');
$this->addMessage('badcrop', 'Please select a larger area to crop');
}
protected function doClean($values)
{
$fieldName = $this->getOption('fieldName');
$fieldValue = $this->getOption('fieldValue');
/**
* If there was previously no image and none has been uploaded then pass
*/
if (empty($fieldValue) && empty($values[$fieldName]))
{
return $values;
}
if ($values[$fieldName . '_x1'] == $values[$fieldName . '_x2'])
{
throw new sfValidatorError($this, 'badcrop');
}
if ($values[$fieldName . '_y1'] == $values[$fieldName . '_y2'])
{
throw new sfValidatorError($this, 'badcrop');
}
return $values;
}
} |
Fix displaying None in statistics when there's no book sold | from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render
from django.db.models import Sum, Count
from common.auth import user_is_admin
from django.utils.translation import ugettext_lazy as _
from common.models import Purchase, BookType
from egielda import settings
@user_passes_test(user_is_admin)
def index(request):
stats = dict()
stats['books_sold_value'] = BookType.objects.filter(book__sold=True).annotate(count=Count('book')).aggregate(
Sum('price', field='count * price'))['price__sum'] or 0
return render(request, 'stats/index.html', {'page_title': _("Statistics"), 'stats': stats,
'currency': getattr(settings, 'CURRENCY', 'USD')})
@user_passes_test(user_is_admin)
def books_sold(request):
Purchase.objects.all().order_by('-date')
return render(request, 'stats/books_sold.html', {'page_title': _("Books sold")}) | from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render
from django.db.models import Sum, Count
from common.auth import user_is_admin
from django.utils.translation import ugettext_lazy as _
from common.models import Purchase, BookType
from egielda import settings
@user_passes_test(user_is_admin)
def index(request):
stats = dict()
stats['books_sold_value'] = BookType.objects.filter(book__sold=True).annotate(count=Count('book')).aggregate(
Sum('price', field='count * price'))['price__sum']
return render(request, 'stats/index.html', {'page_title': _("Statistics"), 'stats': stats,
'currency': getattr(settings, 'CURRENCY', 'USD')})
@user_passes_test(user_is_admin)
def books_sold(request):
Purchase.objects.all().order_by('-date')
return render(request, 'stats/books_sold.html', {'page_title': _("Books sold")}) |
Add support for disabling text areas | Flame.TextAreaView = Flame.View.extend({
classNames: ['flame-text'],
childViews: ['textArea'],
layout: { left: 0, top: 0 },
defaultHeight: 20,
defaultWidth: 200,
acceptsKeyResponder: true,
value: '',
placeholder: null,
isValid: null,
isVisible: true,
isDisabled: true,
becomeKeyResponder: function() {
this.get('textArea').becomeKeyResponder();
},
textArea: Ember.TextArea.extend(Flame.EventManager, Flame.FocusSupport, {
classNameBindings: ['isInvalid', 'isFocused'],
acceptsKeyResponder: true,
// Start from a non-validated state. 'isValid' being null means that it hasn't been validated at all (perhaps
// there's no validator attached) so it doesn't make sense to show it as invalid.
isValid: null,
isInvalid: Flame.computed.equals('isValid', false),
valueBinding: '^value',
placeholderBinding: '^placeholder',
isVisibleBinding: '^isVisible',
disabledBinding: '^isDisabled',
keyDown: function() { return false; },
keyUp: function() {
this._elementValueDidChange();
return false;
}
})
});
| Flame.TextAreaView = Flame.View.extend({
classNames: ['flame-text'],
childViews: ['textArea'],
layout: { left: 0, top: 0 },
defaultHeight: 20,
defaultWidth: 200,
acceptsKeyResponder: true,
value: '',
placeholder: null,
isValid: null,
isVisible: true,
becomeKeyResponder: function() {
this.get('textArea').becomeKeyResponder();
},
textArea: Ember.TextArea.extend(Flame.EventManager, Flame.FocusSupport, {
classNameBindings: ['isInvalid', 'isFocused'],
acceptsKeyResponder: true,
// Start from a non-validated state. 'isValid' being null means that it hasn't been validated at all (perhaps
// there's no validator attached) so it doesn't make sense to show it as invalid.
isValid: null,
isInvalid: Flame.computed.equals('isValid', false),
valueBinding: '^value',
placeholderBinding: '^placeholder',
isVisibleBinding: '^isVisible',
keyDown: function() { return false; },
keyUp: function() {
this._elementValueDidChange();
return false;
}
})
});
|
Fix __doc__ not being replaced | from virtualbox import library
"""
Add helper code to the default IProgress class.
"""
# Helper function for IProgress to print out a current progress state
# in __str__
_progress_template = """\
(%(o)s/%(oc)s) %(od)s %(p)-3s%% (%(tr)s s remaining)"""
class IProgress(library.IProgress):
__doc__ = library.IProgress.__doc__
def __str__(self):
return _progress_template % dict(o=self.operation, p=self.percent,
oc=self.operation_count, od=self.operation_description,
tr=self.time_remaining)
def wait_for_completion(self, timeout=-1):
super(IProgress, self).wait_for_completion(timeout)
wait_for_completion.__doc__ = library.IProgress.wait_for_completion.__doc__
| from virtualbox import library
"""
Add helper code to the default IProgress class.
"""
# Helper function for IProgress to print out a current progress state
# in __str__
_progress_template = """\
(%(o)s/%(oc)s) %(od)s %(p)-3s%% (%(tr)s s remaining)"""
class IProgress(library.IProgress):
__doct__ = library.IProgress.__doc__
def __str__(self):
return _progress_template % dict(o=self.operation, p=self.percent,
oc=self.operation_count, od=self.operation_description,
tr=self.time_remaining)
def wait_for_completion(self, timeout=-1):
super(IProgress, self).wait_for_completion(timeout)
wait_for_completion.__doc__ = library.IProgress.wait_for_completion.__doc__
|
Make the minion name mandatory and passed before MINIONMSG. | // Copyright 2014, Truveris Inc. All Rights Reserved.
// Use of this source code is governed by the ISC license in the LICENSE file.
//
// Defines all the tools to handle the MINIONMSG messages coming from the
// minions.
//
// TODO: We need to reject unauthenticated messages (wrong user id).
//
package ygor
import (
"regexp"
"strings"
)
var (
// Detect a MINIOMSG (minion communications).
reMinionMsg = regexp.MustCompile(`^([^\s]+) MINIONMSG (.*)`)
)
type MinionMsg struct {
// Name of the minion sending this message.
Name string
// The body of the message as received from the minion.
Body string
// Store the command and its arguments if relevant.
Command string
Args []string
}
func NewMinionMsg(line string) *MinionMsg {
tokens := reMinionMsg.FindStringSubmatch(line)
if tokens == nil {
return nil
}
msg := &MinionMsg{
Name: tokens[1],
Body: tokens[2],
}
tokens = strings.Split(msg.Body, " ")
msg.Command = tokens[0]
if len(tokens) > 1 {
msg.Args = append(msg.Args, tokens[1:]...)
}
return msg
}
| // Copyright 2014, Truveris Inc. All Rights Reserved.
// Use of this source code is governed by the ISC license in the LICENSE file.
package ygor
import (
"regexp"
"strings"
)
var (
// Detect a MINIOMSG (minion communications).
reMinionMsg = regexp.MustCompile(`^MINIONMSG (.*)`)
)
type MinionMsg struct {
// The body of the message as received from the minion.
Body string
// Store the command and its arguments if relevant.
Command string
Args []string
}
func NewMinionMsg(line string) *MinionMsg {
tokens := reMinionMsg.FindStringSubmatch(line)
if tokens == nil {
return nil
}
msg := &MinionMsg{
Body: tokens[1],
}
tokens = strings.Split(msg.Body, " ")
msg.Command = tokens[0]
if len(tokens) > 2 {
msg.Args = append(msg.Args, tokens[1:]...)
}
return msg
}
|
Switch to production analytics account | (() => {
'use strict';
/* jshint ignore:start */
// Standard Google Universal Analytics code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
/* jshint ignore:end */
// init analytics account
// ga('create', 'UA-5200461-4', 'auto'); // test account
ga('create', 'UA-5200461-5', 'auto'); // prod account
// Removes failing protocol check. @see: http://stackoverflow.com/a/22152353/1958200
ga('set', 'checkProtocolTask', function(){});
ga('require', 'displayfeatures');
// track page view
ga('send', 'pageview', '/');
// on message sent from content script...
chrome.runtime.onMessage.addListener(message => {
// ...track analytics events
if (message.command === 'trackEvent') {
var data = message.data;
ga('send', 'event', data.category, data.action, data.label, data.value);
}
});
})();
| (() => {
'use strict';
/* jshint ignore:start */
// Standard Google Universal Analytics code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
/* jshint ignore:end */
// init analytics account
ga('create', 'UA-5200461-4', 'auto');
// Removes failing protocol check. @see: http://stackoverflow.com/a/22152353/1958200
ga('set', 'checkProtocolTask', function(){});
ga('require', 'displayfeatures');
// track page view
ga('send', 'pageview', '/');
// on message sent from content script...
chrome.runtime.onMessage.addListener(message => {
// ...track analytics events
if (message.command === 'trackEvent') {
var data = message.data;
ga('send', 'event', data.category, data.action, data.label, data.value);
}
});
})();
|
Add detail row style adjustments | /* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
import React from 'react';
import { View } from 'react-native';
import PropTypes from 'prop-types';
import { SimpleLabel } from './SimpleLabel';
/**
* Simple layout component render sequential SimpleLabel components
* in a row.
*
* Each SimpleLabel has a label and some other text.
*
* @prop {Array} details Array of objects in the form {label, text}
*/
export const DetailRow = ({ details }) => {
const Details = React.useCallback(
() =>
details.map(({ label, text }) => (
<View style={{ flex: 1 }}>
<SimpleLabel label={label} size="small" text={text} />
</View>
)),
[details]
);
return (
<View style={localStyles.rowContainer}>
<Details />
</View>
);
};
const localStyles = {
rowContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
flex: 1,
},
};
DetailRow.propTypes = { details: PropTypes.array.isRequired };
| /* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
import React from 'react';
import { View } from 'react-native';
import PropTypes from 'prop-types';
import { SimpleLabel } from './SimpleLabel';
/**
* Simple layout component render sequential SimpleLabel components
* in a row.
*
* Each SimpleLabel has a label and some other text.
*
* @prop {Array} details Array of objects in the form {label, text}
*/
export const DetailRow = ({ details }) => {
const Details = React.useCallback(
() =>
details.map(({ label, text }) => (
<View>
<SimpleLabel label={label} size="small" text={text} />
</View>
)),
[details]
);
return (
<View style={localStyles.rowContainer}>
<Details />
</View>
);
};
const localStyles = {
rowContainer: {
flexDirection: 'row',
alignItems: 'center',
},
};
DetailRow.propTypes = { details: PropTypes.array.isRequired };
|
Fix in place; no data reduction occuring now. Code could likely be cleaned up, but this solves this issue at hand. | export function simulate(expr, inputs, overallNumSamples) {
const numSamples = overallNumSamples/window.workers.length
return Promise.all(_.map(
window.workers,
(worker, index) => simulateOnWorker(worker, {expr, numSamples, inputs: sliceData(index, numSamples, inputs)})
)).then(
(results) => {
let finalResult = {values: [], errors: []}
for (let result of results) {
if (result.values) {
finalResult.values = finalResult.values.concat(result.values)
}
if (result.errors) {
finalResult.errors = finalResult.errors.concat(result.errors)
}
}
finalResult.errors = _.uniq(finalResult.errors)
return finalResult
}
)
}
function sliceData(index, numSamples, inputs) {
let slicedInputs = {}
for (let key of Object.keys(inputs)) {
slicedInputs[key] = inputs[key].slice(numSamples*index, numSamples*(index+1))
}
return slicedInputs
}
function simulateOnWorker(worker, data) {
return new Promise(
(resolve, reject) => {
worker.push(data, ({data}) => {resolve(JSON.parse(data))})
}
)
}
| export const simulate = (expr, inputs, numSamples) => {
const data = {expr, numSamples: numSamples/window.workers.length, inputs}
return Promise.all(window.workers.map(worker => simulateOnWorker(worker, data))).then(
(results) => {
let finalResult = {values: [], errors: []}
for (let result of results) {
if (result.values) {
finalResult.values = finalResult.values.concat(result.values)
}
if (result.errors) {
finalResult.errors = finalResult.errors.concat(result.errors)
}
}
finalResult.errors = _.uniq(finalResult.errors)
return finalResult
}
)
}
const simulateOnWorker = (worker, data) => {
return new Promise(
(resolve, reject) => {
worker.push(data, ({data}) => {resolve(JSON.parse(data))})
}
)
}
|
Update error message in tests. | /**
* Copyright © 2015 MicroWorld (contact@microworld.org)
*
* 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.microworld.mangopay.tests;
import org.junit.Test;
import org.microworld.mangopay.MangopayClient;
import org.microworld.mangopay.MangopayConnection;
import org.microworld.mangopay.exceptions.MangopayUnauthorizedException;
public class ConnectIT extends AbstractIntegrationTest {
@Test
public void anExceptionIsThrownWhenConnectingToMangopayWithInvalidCredentials() {
thrown.expect(MangopayUnauthorizedException.class);
thrown.expectMessage("invalid_client: Your authorization do not allow you to access to this information");
final MangopayConnection connection = MangopayConnection.createDefault("api.sandbox.mangopay.com", "bar", "baz");
MangopayClient.createDefault(connection).getUserService().get("42");
}
}
| /**
* Copyright © 2015 MicroWorld (contact@microworld.org)
*
* 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.microworld.mangopay.tests;
import org.junit.Test;
import org.microworld.mangopay.MangopayClient;
import org.microworld.mangopay.MangopayConnection;
import org.microworld.mangopay.exceptions.MangopayUnauthorizedException;
public class ConnectIT extends AbstractIntegrationTest {
@Test
public void anExceptionIsThrownWhenConnectingToMangopayWithInvalidCredentials() {
thrown.expect(MangopayUnauthorizedException.class);
thrown.expectMessage("invalid_client: Authentication failed");
final MangopayConnection connection = MangopayConnection.createDefault("api.sandbox.mangopay.com", "bar", "baz");
MangopayClient.createDefault(connection).getUserService().get("42");
}
}
|
Update future requirement from <0.18,>=0.16 to >=0.16,<0.19
Updates the requirements on [future](https://github.com/PythonCharmers/python-future) to permit the latest version.
- [Release notes](https://github.com/PythonCharmers/python-future/releases)
- [Changelog](https://github.com/PythonCharmers/python-future/blob/master/docs/changelog.rst)
- [Commits](https://github.com/PythonCharmers/python-future/commits)
Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com> | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.23',
'future>=0.16,<0.19',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<3.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.23',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<3.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
Add exceptions to eslint config | module.exports = {
'env': {
'browser': true,
'es6': true,
'node': true,
},
'parser': 'babel-eslint',
'plugins': ['react', 'jsx-a11y', 'import'],
'rules': {
'react/jsx-filename-extension': [1, { 'extensions': ['.js', '.jsx'] }],
'react/no-unescaped-entities': [0],
'react/no-array-index-key': [0],
'react/prop-types': [0],
'prefer-template': [0],
'comma-dangle': [0],
'import/newline-after-import': [0],
'no-mixed-operators': [0],
'indent': ['error', 4],
'react/jsx-indent': [2, 4],
'max-len': [0],
},
'extends': 'airbnb',
};
| module.exports = {
'env': {
'browser': true,
'es6': true,
'node': true,
},
'parser': 'babel-eslint',
'plugins': ['react', 'jsx-a11y', 'import'],
'rules': {
'react/jsx-filename-extension': [1, { 'extensions': ['.js', '.jsx'] }],
'react/no-unescaped-entities': [0],
'react/no-array-index-key': [0],
'react/prop-types': [0],
'no-mixed-operators': [0],
'indent': ['error', 4],
'react/jsx-indent': [2, 4],
'max-len': [0],
},
'extends': 'airbnb',
};
|
Replace the particular boolean returns with a boolean expression on is_winner | #!/usr/bin/env python
from abc import ABCMeta, abstractmethod
from game.gameboard import GameBoard
class Player(object):
__metaclass__ = ABCMeta
def __init__(self, color):
self._color = color.lower()
def color(self):
return self._color
def is_winner(self, board):
return board.game_over() and board.winner_color() == self._color
@abstractmethod
def play(self):
"""This method must be overridden"""
pass
class PlayerWithStrategyOne(Player):
def play(self, board):
board.put_chip(board.retrieve_first_non_full_column(), self._color)
class PlayerWithStrategyTwo(Player):
def play(self, board):
board.put_chip(board.retrieve_emptiest_column(), self._color)
| #!/usr/bin/env python
from abc import ABCMeta, abstractmethod
from game.gameboard import GameBoard
class Player(object):
__metaclass__ = ABCMeta
def __init__(self, color):
self._color = color.lower()
def color(self):
return self._color
def is_winner(self, board):
if board.game_over() and board.winner_color() == self._color:
return True
return False
@abstractmethod
def play(self):
"""This method must be overridden"""
pass
class PlayerWithStrategyOne(Player):
def play(self, board):
board.put_chip(board.retrieve_first_non_full_column(), self._color)
class PlayerWithStrategyTwo(Player):
def play(self, board):
board.put_chip(board.retrieve_emptiest_column(), self._color)
|
Fix test case bug where wrong URL was being hit | from flask.ext.testing import TestCase
from chassis import create_app
from chassis.models import db
import factories
class ChassisTestCase(TestCase):
"""Base TestCase to add in convenience functions, defaults and custom
asserts."""
def create_app(self):
return create_app()
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
class TestCat(ChassisTestCase):
SQLALCHEMY_DATABASE_URI = "sqlite://:memory:"
def test_get_cat(self):
"""Test to see if you can get a message by ID."""
cat = factories.Cat()
db.session.commit()
response = self.client.get("/cats/" + str(cat.id))
self.assert_200(response)
resp_json = response.json
self.assertEquals(resp_json["id"], str(cat.id))
self.assertEquals(resp_json["born_at"], cat.born_at)
self.assertEquals(resp_json["name"], cat.name)
| from flask.ext.testing import TestCase
from chassis import create_app
from chassis.models import db
import factories
class ChassisTestCase(TestCase):
"""Base TestCase to add in convenience functions, defaults and custom
asserts."""
def create_app(self):
return create_app()
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
class TestCat(ChassisTestCase):
SQLALCHEMY_DATABASE_URI = "sqlite://:memory:"
def test_get_cat(self):
"""Test to see if you can get a message by ID."""
cat = factories.Cat()
db.session.commit()
response = self.client.get("/messages/" + str(cat.id))
self.assert_200(response)
resp_json = response.json
self.assertEquals(resp_json["id"], str(cat.id))
self.assertEquals(resp_json["born_at"], cat.born_at)
self.assertEquals(resp_json["name"], cat.name)
|
Fix golint and misspell errors
Found by goreportcard | package rtcp
// RawPacket represents an unparsed RTCP packet. It's returned by Unmarshal when
// a packet with an unknown type is encountered.
type RawPacket []byte
// Marshal encodes the packet in binary.
func (r RawPacket) Marshal() ([]byte, error) {
return r, nil
}
// Unmarshal decodes the packet from binary.
func (r *RawPacket) Unmarshal(b []byte) error {
if len(b) < (headerLength) {
return errPacketTooShort
}
*r = b
var h Header
return h.Unmarshal(b)
}
// Header returns the Header associated with this packet.
func (r RawPacket) Header() Header {
var h Header
if err := h.Unmarshal(r); err != nil {
return Header{}
}
return h
}
// DestinationSSRC returns an array of SSRC values that this packet refers to.
func (r *RawPacket) DestinationSSRC() []uint32 {
return []uint32{}
}
| package rtcp
// RawPacket represents an unparsed RTCP packet. It's returned by Unmarshal when
// a packet with an unknown type is encountered.
type RawPacket []byte
// Marshal encodes the packet in binary.
func (r RawPacket) Marshal() ([]byte, error) {
return r, nil
}
// Unmarshal decodes the packet from binary.
func (r *RawPacket) Unmarshal(b []byte) error {
if len(b) < (headerLength) {
return errPacketTooShort
}
*r = b
var h Header
if err := h.Unmarshal(b); err != nil {
return err
}
return nil
}
// Header returns the Header associated with this packet.
func (r RawPacket) Header() Header {
var h Header
if err := h.Unmarshal(r); err != nil {
return Header{}
}
return h
}
// DestinationSSRC returns an array of SSRC values that this packet refers to.
func (r *RawPacket) DestinationSSRC() []uint32 {
return []uint32{}
}
|
Bump up version number to v0.3.0 | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name="ioc_writer",
version="0.3.0",
author="William Gibb",
author_email="william.gibb@mandiant.com",
url="http://www.github.com/mandiant/iocwriter_11/",
packages=['ioc_writer'],
description="""API providing a limited CRUD for manipulating OpenIOC formatted Indicators of Compromise.""",
long_description=read('README'),
install_requires=['lxml'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Security',
'Topic :: Text Processing :: Markup :: XML'
]
)
| import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name="ioc_writer",
version="0.2.0",
author="William Gibb",
author_email="william.gibb@mandiant.com",
url="http://www.github.com/mandiant/iocwriter_11/",
packages=['ioc_writer'],
description="""API providing a limited CRUD for manipulating OpenIOC formatted Indicators of Compromise.""",
long_description=read('README'),
install_requires=['lxml'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Security',
'Topic :: Text Processing :: Markup :: XML'
]
)
|
Add support for Gift Upgrades 1.4.1 | <?php
class SV_SandboxPaypal_NixFifty_GiftUpgrades_Model_GiftUpgrade extends XFCP_SV_SandboxPaypal_NixFifty_GiftUpgrades_Model_GiftUpgrade
{
public function validateRequest(&$errorString)
{
if (!XenForo_Application::debugMode())
{
$errorString = new XenForo_Phrase('sandboxing_paypal_but_debug_is_off');
XenForo_Error::logException(new Exception($errorString), false);
return false;
}
if (empty($this->_filtered['test_ipn']))
{
$errorString = new XenForo_Phrase('sandboxing_paypal_but_live_paypal_in_use');
XenForo_Error::logException(new Exception($errorString), false);
return false;
}
return parent::validateRequest($errorString);
}
public function buildPayPalQueryUrl($paymentParams)
{
$queryString = XenForo_Link::buildQueryString($paymentParams);
$url = "https://www.sandbox.paypal.com/cgi-bin/webscr?{$queryString}";
return $url;
}
} | <?php
class SV_SandboxPaypal_NixFifty_GiftUpgrades_Model_GiftUpgrade extends XFCP_SV_SandboxPaypal_NixFifty_GiftUpgrades_Model_GiftUpgrade
{
public function validateRequest(&$errorString)
{
if (!XenForo_Application::debugMode())
{
$errorString = new XenForo_Phrase('sandboxing_paypal_but_debug_is_off');
XenForo_Error::logException(new Exception($errorString), false);
return false;
}
if (empty($this->_filtered['test_ipn']))
{
$errorString = new XenForo_Phrase('sandboxing_paypal_but_live_paypal_in_use');
XenForo_Error::logException(new Exception($errorString), false);
return false;
}
return parent::validateRequest($errorString);
}
} |
Remove conditional sql-select on new user creation
Only create a user profile if a new user is actually
created. | import uuid
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
class UserProfile(models.Model):
user = models.OneToOneField(User)
secret_key = models.CharField(max_length=32, blank=False,
help_text='Secret key for feed and API access')
class Meta:
db_table = 'comics_user_profile'
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.generate_new_secret_key()
def __unicode__(self):
return u'User profile for %s' % self.user
def generate_new_secret_key(self):
self.secret_key = uuid.uuid4().hex
| import uuid
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
@receiver(models.signals.post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
UserProfile.objects.get_or_create(user=instance)
class UserProfile(models.Model):
user = models.OneToOneField(User)
secret_key = models.CharField(max_length=32, blank=False,
help_text='Secret key for feed and API access')
class Meta:
db_table = 'comics_user_profile'
def __init__(self, *args, **kwargs):
super(UserProfile, self).__init__(*args, **kwargs)
self.generate_new_secret_key()
def __unicode__(self):
return u'User profile for %s' % self.user
def generate_new_secret_key(self):
self.secret_key = uuid.uuid4().hex
|
Convert node list to array before looping through | window.embetter.activeServices = [
window.embetter.services.youtube,
window.embetter.services.vimeo,
window.embetter.services.soundcloud,
window.embetter.services.dailymotion,
window.embetter.services.mixcloud,
window.embetter.services.codepen,
window.embetter.services.bandcamp,
window.embetter.services.ustream,
]
window.embetter.reloadPlayers = (el = document.body) => {
window.embetter.utils.disposeDetachedPlayers()
window.embetter.utils.initMediaPlayers(el, window.embetter.activeServices)
}
window.embetter.stopPlayers = (el = document.body) => {
window.embetter.utils.unembedPlayers(el)
window.embetter.utils.disposeDetachedPlayers()
}
window.embetter.removePlayers = (el = document.body) => {
window.embetter.stopPlayers(el);
[].slice.call(el.querySelectorAll('.embetter-ready')).forEach((ready) => {
ready.classList.remove('embetter-ready')
});
[].slice.call(el.querySelectorAll('.embetter-static')).forEach((statix) => {
statix.classList.remove('embetter-static')
})
}
window.embetter.reloadPlayers()
| window.embetter.activeServices = [
window.embetter.services.youtube,
window.embetter.services.vimeo,
window.embetter.services.soundcloud,
window.embetter.services.dailymotion,
window.embetter.services.mixcloud,
window.embetter.services.codepen,
window.embetter.services.bandcamp,
window.embetter.services.ustream,
]
window.embetter.reloadPlayers = (el = document.body) => {
window.embetter.utils.disposeDetachedPlayers()
window.embetter.utils.initMediaPlayers(el, window.embetter.activeServices)
}
window.embetter.stopPlayers = (el = document.body) => {
window.embetter.utils.unembedPlayers(el)
window.embetter.utils.disposeDetachedPlayers()
}
window.embetter.removePlayers = (el = document.body) => {
window.embetter.stopPlayers(el)
el.querySelectorAll('.embetter-ready').forEach((ready) => {
ready.classList.remove('embetter-ready')
})
el.querySelectorAll('.embetter-static').forEach((statix) => {
statix.classList.remove('embetter-static')
})
}
window.embetter.reloadPlayers()
|
Fix newline separation for binary lines | module.exports = class Definition {
constructor (props) {
Object.assign(this, props)
// TODO: only guard if missing both source and binaries
// once we're able to build a binary-only package:
// https://github.com/nodenv/node-build/issues/259
if (!this.packageName) throw Error('skipping')
}
get preamble () {
return ''
}
get install () {
return `install_package "${this.packageName}" "${this.downloadUri}"`
}
get postamble () {
return ''
}
get downloadUri () {
return `${this.url}#${this.shasum}`
}
get binarySet () {
return this.binaries.join('\n') + (this.binaries.length ? '\n' : '')
}
toString () {
return (
[]
.concat(this.preamble, this.binarySet, this.install, this.postamble)
.filter(i => i)
.join('\n') + '\n'
)
}
}
| module.exports = class Definition {
constructor (props) {
Object.assign(this, props)
// TODO: only guard if missing both source and binaries
// once we're able to build a binary-only package:
// https://github.com/nodenv/node-build/issues/259
if (!this.packageName) throw Error('skipping')
}
get preamble () {
return ''
}
get install () {
return `install_package "${this.packageName}" "${this.downloadUri}"`
}
get postamble () {
return ''
}
get downloadUri () {
return `${this.url}#${this.shasum}`
}
toString () {
return (
[]
.concat(
this.preamble,
this.binaries,
this.binaries.length ? ' ' : '',
this.install,
this.postamble
)
.filter(i => i)
.join('\n') + '\n'
)
}
}
|
Fix possible crash when clicking DownloadManager notification.
The LocalCompilationsActivity must be launched with the NEW_TASK flag,
since we're calling startActivity() from outside an Activity context.
Bug: T172860
Change-Id: I54a3c8a7a9ea282d94298de4e998e35d0adbabb0 | package org.wikipedia.offline;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class DownloadManagerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
if (intent.getExtras() == null || !intent.hasExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)) {
return;
}
long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
for (long id : ids) {
if (Compilation.MIME_TYPE.equals(downloadManager.getMimeTypeForDownloadedFile(id))) {
context.startActivity(LocalCompilationsActivity.
newIntent(context).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
break;
}
}
}
}
}
| package org.wikipedia.offline;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class DownloadManagerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
if (intent.getExtras() == null || !intent.hasExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)) {
return;
}
long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
for (long id : ids) {
if (Compilation.MIME_TYPE.equals(downloadManager.getMimeTypeForDownloadedFile(id))) {
context.startActivity(LocalCompilationsActivity.newIntent(context));
break;
}
}
}
}
}
|
Improve usability in passphrase input dialog.
Add the possiblity to press Enter to submit the dialog and to press Escape to
dismiss it.
R=akuegel@chromium.org, jhawkins@chromium.org
BUG=171370
Review URL: https://chromiumcodereview.appspot.com/12321166
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@185194 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function load() {
var checkPassphrase = function(event) {
chrome.send('checkPassphrase', [$('passphrase-entry').value]);
};
var closeDialog = function(event) {
// TODO(akuegel): Replace by closeDialog.
chrome.send('DialogClose');
};
// Directly set the focus on the input box so the user can start typing right
// away.
$('passphrase-entry').focus();
$('unlock-passphrase-button').onclick = checkPassphrase;
$('cancel-passphrase-button').onclick = closeDialog;
$('passphrase-entry').oninput = function(event) {
$('unlock-passphrase-button').disabled = $('passphrase-entry').value == '';
$('incorrect-passphrase-warning').hidden = true;
};
$('passphrase-entry').onkeypress = function(event) {
if (!event)
return;
// Check if the user pressed enter.
if (event.keyCode == 13)
checkPassphrase(event);
};
// Pressing escape anywhere in the frame should work.
document.onkeyup = function(event) {
if (!event)
return;
// Check if the user pressed escape.
if (event.keyCode == 27)
closeDialog(event);
};
}
function passphraseCorrect() {
chrome.send('DialogClose', ['true']);
}
function passphraseIncorrect() {
$('incorrect-passphrase-warning').hidden = false;
$('passphrase-entry').focus();
}
window.addEventListener('DOMContentLoaded', load);
| // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function load() {
$('unlock-passphrase-button').onclick = function(event) {
chrome.send('checkPassphrase', [$('passphrase-entry').value]);
};
$('cancel-passphrase-button').onclick = function(event) {
// TODO(akuegel): Replace by closeDialog.
chrome.send('DialogClose');
};
$('passphrase-entry').oninput = function(event) {
$('unlock-passphrase-button').disabled = $('passphrase-entry').value == '';
$('incorrect-passphrase-warning').hidden = true;
};
}
function passphraseCorrect() {
chrome.send('DialogClose', ['true']);
}
function passphraseIncorrect() {
$('incorrect-passphrase-warning').hidden = false;
$('passphrase-entry').focus();
}
window.addEventListener('DOMContentLoaded', load);
|
Whitelist nacl_integration tests to run on new nacl integration bot.
BUG= none
TEST= none
Review URL: http://codereview.chromium.org/7050026
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@86021 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
def Main():
pwd = os.environ.get('PWD', '')
# TODO(ncbray): figure out why this is failing on windows and enable.
if sys.platform in ['win32', 'cygwin'] and 'nacl-chrome' not in pwd: return
# TODO(ncbray): figure out why this is failing on mac and re-enable.
if sys.platform == 'darwin' and 'nacl-chrome' not in pwd: return
# TODO(ncbray): figure out why this is failing on some linux trybots.
if sys.platform in ['linux', 'linux2'] and 'nacl-chrome' not in pwd: return
script_dir = os.path.dirname(os.path.abspath(__file__))
test_dir = os.path.dirname(script_dir)
chrome_dir = os.path.dirname(test_dir)
src_dir = os.path.dirname(chrome_dir)
nacl_integration_script = os.path.join(
src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py')
cmd = [sys.executable, nacl_integration_script] + sys.argv[1:]
print cmd
subprocess.check_call(cmd)
if __name__ == '__main__':
Main()
| #!/usr/bin/python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
def Main():
pwd = os.environ.get('PWD', '')
# TODO(ncbray): figure out why this is failing on windows and enable.
if (sys.platform in ['win32', 'cygwin'] and
'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return
# TODO(ncbray): figure out why this is failing on mac and re-enable.
if (sys.platform == 'darwin' and
'mac-nacl-chrome' not in pwd): return
# TODO(ncbray): figure out why this is failing on some linux trybots.
if (sys.platform in ['linux', 'linux2'] and
'hardy64-nacl-chrome' not in pwd): return
script_dir = os.path.dirname(os.path.abspath(__file__))
test_dir = os.path.dirname(script_dir)
chrome_dir = os.path.dirname(test_dir)
src_dir = os.path.dirname(chrome_dir)
nacl_integration_script = os.path.join(
src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py')
cmd = [sys.executable, nacl_integration_script] + sys.argv[1:]
print cmd
subprocess.check_call(cmd)
if __name__ == '__main__':
Main()
|
Adjust beta ratio to 20% | //= require govuk/multivariate-test
/*jslint browser: true,
* indent: 2,
* white: true
*/
/*global $, GOVUK */
$(function () {
GOVUK.taxDiscBetaPrimary = function () {
$('.primary-apply').html($('#beta-primary').html());
$('.secondary-apply').html($('#dvla-secondary').html());
};
if(window.location.href.indexOf("/tax-disc") > -1) {
new GOVUK.MultivariateTest({
name: 'tax-disc',
customVarIndex: 20,
cohorts: {
tax_disc_beta_control1: { callback: function () { } },
tax_disc_beta_control2: { callback: function () { } },
tax_disc_beta_control3: { callback: function () { } },
tax_disc_beta_control4: { callback: function () { } },
tax_disc_beta1: { callback: GOVUK.taxDiscBetaPrimary }
}
});
}
});
| //= require govuk/multivariate-test
/*jslint browser: true,
* indent: 2,
* white: true
*/
/*global $, GOVUK */
$(function () {
GOVUK.taxDiscBetaPrimary = function () {
$('.primary-apply').html($('#beta-primary').html());
$('.secondary-apply').html($('#dvla-secondary').html());
};
if(window.location.href.indexOf("/tax-disc") > -1) {
new GOVUK.MultivariateTest({
name: 'tax-disc',
customVarIndex: 20,
cohorts: {
tax_disc_beta_control1: { callback: function () { } },
tax_disc_beta_control2: { callback: function () { } },
tax_disc_beta_control3: { callback: function () { } },
tax_disc_beta_control4: { callback: function () { } },
tax_disc_beta_control5: { callback: function () { } },
tax_disc_beta_control6: { callback: function () { } },
tax_disc_beta_control7: { callback: function () { } },
tax_disc_beta_control8: { callback: function () { } },
tax_disc_beta_control9: { callback: function () { } },
tax_disc_beta1: { callback: GOVUK.taxDiscBetaPrimary }
}
});
}
});
|
Revert "Fix Create Room button"
This reverts commit 9cae667c063e67b32e60b89e7256d714a056559b. | /*
Copyright 2017 Vector Creations Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import sdk from '../../../index';
import PropTypes from 'prop-types';
const CreateRoomButton = function(props) {
const ActionButton = sdk.getComponent('elements.ActionButton');
return (
<ActionButton action="view_create_chat"
label="Create new room"
iconPath="img/icons-create-room.svg"
size={props.size}
tooltip={props.tooltip}
/>
);
};
CreateRoomButton.propTypes = {
size: PropTypes.string,
tooltip: PropTypes.bool,
};
export default CreateRoomButton;
| /*
Copyright 2017 Vector Creations Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import sdk from '../../../index';
import PropTypes from 'prop-types';
const CreateRoomButton = function(props) {
const ActionButton = sdk.getComponent('elements.ActionButton');
return (
<ActionButton action="view_create_room"
label="Create new room"
iconPath="img/icons-create-room.svg"
size={props.size}
tooltip={props.tooltip}
/>
);
};
CreateRoomButton.propTypes = {
size: PropTypes.string,
tooltip: PropTypes.bool,
};
export default CreateRoomButton;
|
[API] Fix wrong content-type in case of exception (should be application/json). | package org.talend.dataprep.exception;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class TDPExceptionController {
@ExceptionHandler(InternalException.class)
public @ResponseBody String handleInternalError(HttpServletResponse response, InternalException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
final StringWriter message = new StringWriter();
e.writeTo(message);
return message.toString();
}
@ExceptionHandler(UserException.class)
public @ResponseBody String handleUserError(HttpServletResponse response, UserException e) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
final StringWriter message = new StringWriter();
e.writeTo(message);
return message.toString();
}
}
| package org.talend.dataprep.exception;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class TDPExceptionController {
@ExceptionHandler(InternalException.class)
public @ResponseBody String handleInternalError(HttpServletResponse response, InternalException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
final StringWriter message = new StringWriter();
e.writeTo(message);
return message.toString();
}
@ExceptionHandler(UserException.class)
public @ResponseBody String handleUserError(HttpServletResponse response, UserException e) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
final StringWriter message = new StringWriter();
e.writeTo(message);
return message.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.