text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Refactor tests to include API KEY | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
import os
MAPS_API_KEY = os.environ['MAPS_API_KEY']
class TestOptionalParameters(unittest.TestCase):
def test_invalid_mode(self):
"""
Tests the is_valid_mode function for an invalid input
"""
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA", key=MAPS_API_KEY)
with self.assertRaises(InvalidModeError):
requester.set_mode("flying")
def test_invalid_alternative(self):
"""
Tests for error handling when an invalid value is provided to
the set_alternative function
"""
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA", key=MAPS_API_KEY)
with self.assertRaises(InvalidAlternativeError):
requester.set_alternatives('False')
def test_invalid_restrictions(self):
"""
Tests for invalid route restrictions
"""
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA", key=MAPS_API_KEY)
with self.assertRaises(ValueError):
requester.set_route_restrictions("freeways", "railways")
class TestAPIKey(unittest.TestCase):
def test_invalid_api_key(self):
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA", key=MAPS_API_KEY)
invalid_key = 123456
with self.assertRaises(InvalidAPIKeyError):
requester.set_api_key(invalid_key)
if __name__ == '__main__':
unittest.main() | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
class TestOptionalParameters(unittest.TestCase):
def test_invalid_mode(self):
"""
Tests the is_valid_mode function for an invalid input
"""
with self.assertRaises(InvalidModeError):
requester.set_mode("flying")
def test_invalid_alternative(self):
"""
Tests for error handling when an invalid value is provided to
the set_alternative function
"""
with self.assertRaises(InvalidAlternativeError):
requester.set_alternatives('False')
def test_invalid_restrictions(self):
"""
Tests for invalid route restrictions
"""
with self.assertRaises(ValueError):
requester.set_route_restrictions("freeways", "railways")
class TestAPIKey(unittest.TestCase):
def test_invalid_api_key(self):
invalid_key = 123456
with self.assertRaises(InvalidAPIKeyError):
requester.set_api_key(invalid_key)
if __name__ == '__main__':
unittest.main() |
Test for URL in every scraper. | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2013 Bastian Kleineidam
from unittest import TestCase
from dosagelib import scraper
class ScraperTester(TestCase):
"""Test scraper module functions."""
def test_get_scraperclasses(self):
for scraperclass in scraper.get_scraperclasses():
scraperobj = scraperclass()
scraperobj = scraperclass(indexes=["bla"])
self.assertTrue(scraperobj.url,
"missing url in %s" % scraperobj.getName())
def test_find_scraperclasses_single(self):
result = scraper.find_scraperclasses("CalvinAndHobbes")
self.assertEqual(len(result), 1)
def test_find_scraperclasses_multi(self):
result = scraper.find_scraperclasses("a", multiple_allowed=True)
self.assertTrue(len(result) > 1)
def test_find_scraperclasses_error(self):
self.assertRaises(ValueError, scraper.find_scraperclasses, "")
| # -*- coding: iso-8859-1 -*-
# Copyright (C) 2013 Bastian Kleineidam
from unittest import TestCase
from dosagelib import scraper
class ScraperTester(TestCase):
"""Test scraper module functions."""
def test_get_scraperclasses(self):
for scraperclass in scraper.get_scraperclasses():
scraperclass()
scraperclass(indexes=["bla"])
def test_find_scraperclasses_single(self):
result = scraper.find_scraperclasses("CalvinAndHobbes")
self.assertEqual(len(result), 1)
def test_find_scraperclasses_multi(self):
result = scraper.find_scraperclasses("a", multiple_allowed=True)
self.assertTrue(len(result) > 1)
def test_find_scraperclasses_error(self):
self.assertRaises(ValueError, scraper.find_scraperclasses, "")
|
Check for empty data value | /*
* Copyright (c) 2006 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*
* Contributors:
* Stephan D. Cote
* - Initial API and implementation
*/
package coyote.dataframe;
import java.util.Date;
import coyote.commons.ByteUtil;
/** Type representing a unsigned 64-bit epoch time in milliseconds */
public class DateType implements FieldType {
private static final int _size = 8;
private final static String _name = "DAT";
public boolean checkType( Object obj ) {
return obj instanceof Date;
}
public Object decode( byte[] value ) {
return ByteUtil.retrieveDate( value, 0 );
}
public byte[] encode( Object obj ) {
return ByteUtil.renderDate( (Date)obj );
}
public String getTypeName() {
return _name;
}
public boolean isNumeric() {
return false;
}
public int getSize() {
return _size;
}
/**
* @see coyote.dataframe.FieldType#stringValue(byte[])
*/
@Override
public String stringValue( byte[] val ) {
if ( val == null || val.length == 0 ) {
return "";
} else {
Object obj = decode( val );
if ( obj != null )
return obj.toString();
else
return "";
}
}
}
| /*
* Copyright (c) 2006 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*
* Contributors:
* Stephan D. Cote
* - Initial API and implementation
*/
package coyote.dataframe;
import java.util.Date;
import coyote.commons.ByteUtil;
/** Type representing a unsigned 64-bit epoch time in milliseconds */
public class DateType implements FieldType {
private static final int _size = 8;
private final static String _name = "DAT";
public boolean checkType( Object obj ) {
return obj instanceof Date;
}
public Object decode( byte[] value ) {
return ByteUtil.retrieveDate( value, 0 );
}
public byte[] encode( Object obj ) {
return ByteUtil.renderDate( (Date)obj );
}
public String getTypeName() {
return _name;
}
public boolean isNumeric() {
return false;
}
public int getSize() {
return _size;
}
/**
* @see coyote.dataframe.FieldType#stringValue(byte[])
*/
@Override
public String stringValue( byte[] val ) {
if ( val == null ) {
return "";
} else {
Object obj = decode( val );
if ( obj != null )
return obj.toString();
else
return "";
}
}
}
|
Add ip restriction on dev env | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '89.3.160.138', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
/**
* @var Composer\Autoload\ClassLoader $loader
*/
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
/**
* @var Composer\Autoload\ClassLoader $loader
*/
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Make sure the relative path passed to getResource() starts with a /, sigh. Very bad design. | package to.etc.domui.server;
import org.eclipse.jdt.annotation.NonNull;
import javax.servlet.FilterConfig;
import java.io.File;
import java.net.URL;
public class FilterConfigParameters implements ConfigParameters {
@NonNull
private FilterConfig m_fc;
@NonNull
private File m_webFileRoot;
public FilterConfigParameters(@NonNull FilterConfig fc, @NonNull File webFileRoot) {
m_fc = fc;
m_webFileRoot = webFileRoot;
}
@Override
public String getString(@NonNull String name) {
return m_fc.getInitParameter(name);
}
@NonNull
@Override
public File getWebFileRoot() {
return m_webFileRoot;
}
@NonNull
@Override
public URL getResourcePath(@NonNull String path) throws Exception {
if(path.startsWith("/"))
return m_fc.getServletContext().getResource(path);
return m_fc.getServletContext().getResource("/" + path); // Always nice to have a relative path start with /. Morons.
}
}
| package to.etc.domui.server;
import org.eclipse.jdt.annotation.NonNull;
import javax.servlet.FilterConfig;
import java.io.File;
import java.net.URL;
public class FilterConfigParameters implements ConfigParameters {
@NonNull
private FilterConfig m_fc;
@NonNull
private File m_webFileRoot;
public FilterConfigParameters(@NonNull FilterConfig fc, @NonNull File webFileRoot) {
m_fc = fc;
m_webFileRoot = webFileRoot;
}
@Override
public String getString(@NonNull String name) {
return m_fc.getInitParameter(name);
}
@NonNull
@Override
public File getWebFileRoot() {
return m_webFileRoot;
}
@NonNull
@Override
public URL getResourcePath(@NonNull String path) throws Exception {
URL url = m_fc.getServletContext().getResource(path);
return url;
}
}
|
Handle unexpected errors properly in load_blueprint | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
except Exception as e:
raise click.ClickException("Unexpected error during the blueprint "
"loading: {}".format(e.message))
@click.group()
@click.version_option()
def cli():
pass
@cli.command()
@click.argument('files', nargs=-1)
def predict(files):
"""
Predict how many objects will be created if the given files are used.
"""
blueprint = get_blueprint(*files)
for item in blueprint:
click.echo("{name}: {count} {by}".format(
name=item.name, count=item.total,
by="({} by {})".format(item.count.number, item.count.by)
if item.count.by else ""
))
| import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
except Exception as e:
pass
@click.group()
@click.version_option()
def cli():
pass
@cli.command()
@click.argument('files', nargs=-1)
def predict(files):
"""
Predict how many objects will be created if the given files are used.
"""
blueprint = get_blueprint(*files)
for item in blueprint:
click.echo("{name}: {count} {by}".format(
name=item.name, count=item.total,
by="({} by {})".format(item.count.number, item.count.by)
if item.count.by else ""
))
|
Use better variable names for algorithmic determination | def levenshtein(top_string, bot_string):
if len(top_string) < len(bot_string):
return levenshtein(bot_string, top_string)
# len(s1) >= len(s2)
if len(bot_string) == 0:
return len(top_string)
previous_row = range(len(bot_string) + 1)
for i, top_char in enumerate(top_string):
current_row = [i + 1]
for j, bot_char in enumerate(bot_string):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than bot_string
substitutions = previous_row[j] + (top_char != bot_char)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
| def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
|
Enable usage with multiple jspsych timeline_variables | jsPsych.plugins['conditional-run'] = (function () {
var plugin = {};
plugin.info = {
name: 'conditional-run',
description: 'Only run the specified plugin if a condition is met',
parameters: {
'dependentPluginParameters': {
type: jsPsych.plugins.parameterType.COMPLEX,
description: 'The parameters to pass to the plugin that will be run, including the type of plugin',
nested: {
'type': {
type: jsPsych.plugins.parameterType.STRING,
description: 'The type of the plugin to use if the condition is met'
}
// + Other parameters relevant to the dependent plugin
}
},
'conditionalFunction': {
type: jsPsych.plugins.parameterType.FUNCTION,
description: 'Function that will be executed when this trial is started. If it returns true, the trial is run. Otherwise, it is skipped.'
}
}
}
plugin.trial = function (display_element, trial) {
if (typeof trial.conditionalFunction === 'function' && trial.conditionalFunction()) {
// protect functions in the parameters (only does a shallow copy)
var dependentPluginParams = Object.assign({}, trial.dependentPluginParameters);
jsPsych.plugins[dependentPluginParams.type].trial(display_element, dependentPluginParams);
} else {
// skip
jsPsych.finishTrial();
}
}
return plugin;
})(); | jsPsych.plugins['conditional-run'] = (function () {
var plugin = {};
plugin.info = {
name: 'conditional-run',
description: 'Only run the specified plugin if a condition is met',
parameters: {
'dependentPluginParameters': {
type: jsPsych.plugins.parameterType.COMPLEX,
description: 'The parameters to pass to the plugin that will be run, including the type of plugin',
nested: {
'type': {
type: jsPsych.plugins.parameterType.STRING,
description: 'The type of the plugin to use if the condition is met'
}
// + Other parameters relevant to the dependent plugin
}
},
'conditionalFunction': {
type: jsPsych.plugins.parameterType.FUNCTION,
description: 'Function that will be executed when this trial is started. If it returns true, the trial is run. Otherwise, it is skipped.'
}
}
}
plugin.trial = function (display_element, trial) {
if (typeof trial.conditionalFunction === 'function' && trial.conditionalFunction()) {
jsPsych.plugins[trial.dependentPluginParameters.type].trial(display_element, trial.dependentPluginParameters);
} else {
// skip
jsPsych.finishTrial();
}
}
return plugin;
})(); |
Enable face culling in sponza example | import moderngl
from demosys.effects import effect
class SceneEffect(effect.Effect):
"""Generated default effect"""
def __init__(self):
self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True)
self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0)
def draw(self, time, frametime, target):
self.ctx.enable(moderngl.DEPTH_TEST)
self.ctx.enable(moderngl.CULL_FACE)
self.sys_camera.velocity = self.scene.diagonal_size / 5.0
self.scene.draw(
projection_matrix=self.proj_mat,
camera_matrix=self.sys_camera.view_matrix,
time=time,
)
# Draw bbox
# self.scene.draw_bbox(self.proj_mat, self.sys_camera.view_matrix, all=True)
| import moderngl as mgl
from demosys.effects import effect
class SceneEffect(effect.Effect):
"""Generated default effect"""
def __init__(self):
self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True)
self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0)
def draw(self, time, frametime, target):
self.ctx.enable(mgl.DEPTH_TEST)
self.sys_camera.velocity = self.scene.diagonal_size / 5.0
self.scene.draw(
projection_matrix=self.proj_mat,
camera_matrix=self.sys_camera.view_matrix,
time=time,
)
# Draw bbox
# self.scene.draw_bbox(self.proj_mat, self.sys_camera.view_matrix, all=True)
|
Append License, Topic to classifiers.
Signed-off-by: Kouhei Maeda <c9f1823971fa1a4c79cdb50b3311094021cee31e@palmtb.net> | #!/usr/bin/env python
import sys
assert sys.version >= '2.5', "Requires Python v2.5 or above."
from setuptools import setup
classifiers = [
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries :: Python Modules",
]
setup(
name = "shortuuid",
version = "0.3.1",
author = "Stochastic Technologies",
author_email = "info@stochastictechnologies.com",
url = "https://github.com/stochastic-technologies/shortuuid/",
description = "A generator library for concise, unambiguous and URL-safe UUIDs.",
long_description = "A library that generates short, pretty, unambiguous unique IDs "
" by using an extensive, case-sensitive alphabet and omitting "
"similar-looking letters and numbers.",
license = "BSD",
classifiers=classifiers,
packages = ["shortuuid"],
)
| #!/usr/bin/env python
import sys
assert sys.version >= '2.5', "Requires Python v2.5 or above."
from setuptools import setup
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
]
setup(
name = "shortuuid",
version = "0.3.1",
author = "Stochastic Technologies",
author_email = "info@stochastictechnologies.com",
url = "https://github.com/stochastic-technologies/shortuuid/",
description = "A generator library for concise, unambiguous and URL-safe UUIDs.",
long_description = "A library that generates short, pretty, unambiguous unique IDs "
" by using an extensive, case-sensitive alphabet and omitting "
"similar-looking letters and numbers.",
license = "BSD",
classifiers=classifiers,
packages = ["shortuuid"],
)
|
Correct test for zero hash versus nil on empty db. | // Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package ldb_test
import (
"github.com/conformal/btcdb"
"github.com/conformal/btcwire"
"os"
"testing"
)
// we need to test for empty databas and make certain it returns proper value
func TestEmptyDB(t *testing.T) {
dbname := "tstdbempty"
_ = os.RemoveAll(dbname)
db, err := btcdb.CreateDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer os.RemoveAll(dbname)
// This is a reopen test
db.Close()
db, err = btcdb.OpenDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer db.Close()
sha, height, err := db.NewestSha()
if !sha.IsEqual(&btcwire.ShaHash{}) {
t.Errorf("sha not nil")
}
if height != -1 {
t.Errorf("height not -1 %v", height)
}
}
| // Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package ldb_test
import (
"github.com/conformal/btcdb"
"os"
"testing"
)
// we need to test for empty databas and make certain it returns proper value
func TestEmptyDB(t *testing.T) {
dbname := "tstdbempty"
_ = os.RemoveAll(dbname)
db, err := btcdb.CreateDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer os.RemoveAll(dbname)
// This is a reopen test
db.Close()
db, err = btcdb.OpenDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer db.Close()
sha, height, err := db.NewestSha()
if sha != nil {
t.Errorf("sha not nil")
}
if height != -1 {
t.Errorf("height not -1 %v", height)
}
}
|
Use the correct decoder for the test. | # -*- coding: utf-8 -*-
"""
This module defines substantial HPACK integration tests. These can take a very
long time to run, so they're outside the main test suite, but they need to be
run before every change to HPACK.
"""
from hyper.http20.hpack import Decoder
from hyper.http20.huffman import HuffmanDecoder
from hyper.http20.huffman_constants import REQUEST_CODES, REQUEST_CODES_LENGTH
from binascii import unhexlify
class TestHPACKDecoderIntegration(object):
def test_can_decode_a_story(self, story):
d = Decoder()
if story['context'] == 'request':
d.huffman_coder = HuffmanDecoder(REQUEST_CODES, REQUEST_CODES_LENGTH)
for case in story['cases']:
d.header_table_size = case['header_table_size']
decoded_headers = d.decode(unhexlify(case['wire']))
# The correct headers are a list of dicts, which is annoying.
correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()}
assert correct_headers == decoded_headers
| # -*- coding: utf-8 -*-
"""
This module defines substantial HPACK integration tests. These can take a very
long time to run, so they're outside the main test suite, but they need to be
run before every change to HPACK.
"""
from hyper.http20.hpack import Decoder
from binascii import unhexlify
class TestHPACKDecoderIntegration(object):
def test_can_decode_a_story(self, story):
d = Decoder()
for case in story['cases']:
d.header_table_size = case['header_table_size']
decoded_headers = d.decode(unhexlify(case['wire']))
# The correct headers are a list of dicts, which is annoying.
correct_headers = {(item[0], item[1]) for header in case['headers'] for item in header.items()}
assert correct_headers == decoded_headers
|
Use OrderedDict for repo data | import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
for repo in repos:
if 'name' in repo and not repo['fork']:
data.append(collections.OrderedDict([('name', repo['name']),
('desc', repo['description']),
('lang', repo['language']),
('stars', repo['stargazers_count'])]))
return data
if __name__ == '__main__':
import pprint
u = 'kshvmdn'
pprint.pprint(main(u))
| import requests
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
for repo in repos:
if 'name' in repo and not repo['fork']:
data.append({
'name': repo['name'],
'desc': repo['description'],
'lang': repo['language'],
'stars': repo['stargazers_count']
})
return data
if __name__ == '__main__':
import pprint
u = 'kshvmdn'
pprint.pprint(main(u))
|
Add schema constraints + documentation | <?php
return [
'specificationBuildMode' => env('OPARL_BUILD_MODE', 'native'),
/**
* These constraints are used for the site-internal functions like
* displaying the specification's web view or providing the
* validation service.
*/
'versions' => [
'specification' => [
'stable' => '~1.0',
'latest' => 'master',
],
'liboparl' => [
'stable' => '~0.2',
'latest' => 'master'
],
'validator' => [
'stable' => '~0.1',
'latest' => 'master'
]
],
/**
* These constraints are used to provide downloads for specified component
*/
'downloads' => [
'specification' => [
'~1.0',
'master'
]
],
/**
* Mapping of Schema endpoints to version constraints of the specification repository
*/
'schema' => [
'1.0' => '~1.0',
'1.1' => 'master',
'master' => 'master'
]
];
| <?php
return [
'specificationBuildMode' => env('OPARL_BUILD_MODE', 'native'),
'versions' => [
'specification' => [
'stable' => '~1.0',
'latest' => 'master',
],
'liboparl' => [
'stable' => '~0.2',
'latest' => 'master'
],
'validator' => [
'stable' => '~0.1',
'latest' => 'master'
]
],
'downloads' => [
'specification' => [
'~1.0',
'master'
]
]
];
|
Add null check to property generator | // @flow
import * as React from 'react';
import { Helmet } from 'react-helmet';
import config from 'app/config';
import { type ComponentType, createElement } from 'react';
/**
* A higher order component that wraps the given component in
* LoadingIndicator while `props[loadingProp]` is being fetched.
*/
type PropertyGenerator = (
props: Object,
config?: Object
) => Array<{
property?: string,
content?: string,
element?: string,
children?: string,
rel?: string,
href?: string
}>;
export default function helmet<T>(propertyGenerator: ?PropertyGenerator) {
return (Component: ComponentType<T>) => ({
PropertyGenerator,
...props
}: T & {
propertyGenerator: PropertyGenerator
}) => [
<Helmet key="helmet">
{!!propertyGenerator &&
propertyGenerator(props, config).map(
({ element, children, ...props }, index) =>
createElement(element || 'meta', { key: index, ...props }, children)
)}
</Helmet>,
<Component key="component" {...props} />
];
}
| // @flow
import * as React from 'react';
import { Helmet } from 'react-helmet';
import config from 'app/config';
import { type ComponentType, createElement } from 'react';
/**
* A higher order component that wraps the given component in
* LoadingIndicator while `props[loadingProp]` is being fetched.
*/
type PropertyGenerator = (
props: Object,
config?: Object
) => Array<{
property?: string,
content?: string,
element?: string,
children?: string,
rel?: string,
href?: string
}>;
export default function helmet<T>(propertyGenerator: PropertyGenerator) {
return (Component: ComponentType<T>) => ({
PropertyGenerator,
...props
}: T & {
propertyGenerator: PropertyGenerator
}) => [
<Helmet key="helmet">
{propertyGenerator(props, config).map(
({ element, children, ...props }, index) =>
createElement(element || 'meta', { key: index, ...props }, children)
)}
</Helmet>,
<Component key="component" {...props} />
];
}
|
Remove bonzo and qwery dependencies | // Scans your stylesheet for pseudo classes and adds a class with the same name.
// Thanks to Knyle Style Sheets for the idea.
(function () {
'use strict';
var toArray = function(arr) { return Array.prototype.slice.call(arr, 0); };
var add = function(a, b) { return a + b; };
// Compile regular expression.
var pseudos = [ 'link', 'visited', 'hover', 'active', 'focus', 'target',
'enabled', 'disabled', 'checked' ];
var pseudoRe = new RegExp(":((" + pseudos.join(")|(") + "))", "gi");
var processedPseudoClasses = toArray(document.styleSheets).filter(function(ss) {
return !(ss.href != null);
}).map(function(ss) {
return toArray(ss.cssRules).filter(function(rule) {
// Keep only rules with pseudo classes.
return rule.selectorText && rule.selectorText.match(pseudoRe);
}).map(function(rule) {
// Replace : with . and encoded :
return rule.cssText.replace(pseudoRe, ".\\3A $1");
}).reduce(add);
}).reduce(add, '');
if (processedPseudoClasses.length) {
// Add a new style element with the processed pseudo class styles.
var styleEl = document.createElement('style');
styleEl.innerText = processedPseudoClasses;
return document.querySelectorAll('head')[0].appendChild(styleEl);
}
}());
| // Scans your stylesheet for pseudo classes and adds a class with the same name.
// Thanks to Knyle Style Sheets for the idea.
(function () {
'use strict';
var toArray = function(arr) {
return Array.prototype.slice.call(arr, 0);
};
var add = function(a, b) { return a + b; };
// Compile regular expression.
var pseudos = ['link', 'visited', 'hover', 'active', 'focus', 'target', 'enabled', 'disabled', 'checked'];
var pseudoRe = new RegExp(":((" + pseudos.join(")|(") + "))", "gi");
var processedPseudoClasses = toArray(document.styleSheets).filter(function(ss) {
return !(ss.href != null);
}).map(function(ss) {
return toArray(ss.cssRules).filter(function(rule) {
// Keep only rules with pseudo classes.
return rule.selectorText && rule.selectorText.match(pseudoRe);
}).map(function(rule) {
// Replace : with . and encoded :
return rule.cssText.replace(pseudoRe, ".\\3A $1");
}).reduce(add);
}).reduce(add, '');
if (processedPseudoClasses.length) {
// Add a new style element with the processed pseudo class styles.
return $('head').append($('<style />').text(processedPseudoClasses));
}
}());
|
Fix issue with imezone on IsPaid Permission |
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > datetime.today() |
from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > timezone.now() |
Fix timeout issue when running end to end test in local environment.
This issue is caused by saving code coverage result file to a
non-exist folder(/tmp/.nay_output).
To fix this issue, two check points were added.
1. The code coverage result file will not be genreated and saved
if code coverage is not enabeled.
2. If there is no /tmp/.nay_output folder in current system, create
one. | /* eslint no-undef: off */
/* eslint no-console: off */
/* eslint global-require: off */
/* eslint no-underscore-dangle: off */
// collects coverage from the tested page,
// calls nightmare.end() and calls done()
module.exports = {
coverage: (nightmare, done) => {
nightmare
.evaluate(() => window.__coverage__)
.end()
.then((cov) => {
if (cov) {
const fs = require('fs');
const strCoverage = JSON.stringify(cov);
const hash = require('crypto').createHmac('sha256', '')
.update(strCoverage)
.digest('hex');
const covOutDir = '/tmp/.nyc_output/';
if (!fs.existsSync(covOutDir)) fs.mkdirSync(covOutDir);
const fileName = `${covOutDir}coverage-${hash}.json`;
fs.writeFileSync(fileName, strCoverage);
}
done();
})
.catch(err => console.log(err));
},
};
| /* eslint no-undef: off */
/* eslint no-console: off */
/* eslint global-require: off */
/* eslint no-underscore-dangle: off */
// collects coverage from the tested page,
// calls nightmare.end() and calls done()
module.exports = {
coverage: (nightmare, done) => {
nightmare
.evaluate(() => window.__coverage__)
.end()
.then((cov) => {
const strCoverage = JSON.stringify(cov);
const hash = require('crypto').createHmac('sha256', '')
.update(strCoverage)
.digest('hex');
const fileName = `/tmp/.nyc_output/coverage-${hash}.json`;
require('fs').writeFileSync(fileName, strCoverage);
done();
})
.catch(err => console.log(err));
},
};
|
Remove wpautop from wysiwyg field | <?php
if( ! defined( 'ABSPATH' ) ) exit;
class Cuztom_Field_Wysiwyg extends Cuztom_Field
{
var $_supports_ajax = true;
var $_supports_bundle = true;
function __construct( $field, $parent )
{
parent::__construct( $field, $parent );
$this->args = array_merge(
array(
'textarea_name' => 'cuztom[' . $this->id . ']',
'editor_class' => ''
),
$this->args
);
$this->args['editor_class'] .= ' cuztom-input';
}
function _output( $value )
{
$this->args['textarea_name'] = 'cuztom' . $this->pre . '[' . $this->id . ']' . $this->after;
return wp_editor( ( ! empty( $value ) ? $value : $this->default_value ), $this->pre_id . $this->id . $this->after_id, $this->args ) . $this->output_explanation();
}
} | <?php
if( ! defined( 'ABSPATH' ) ) exit;
class Cuztom_Field_Wysiwyg extends Cuztom_Field
{
var $_supports_ajax = true;
var $_supports_bundle = true;
function __construct( $field, $parent )
{
parent::__construct( $field, $parent );
$this->args = array_merge(
array(
'textarea_name' => 'cuztom[' . $this->id . ']',
'editor_class' => ''
),
$this->args
);
$this->args['editor_class'] .= ' cuztom-input';
}
function _output( $value )
{
$this->args['textarea_name'] = 'cuztom' . $this->pre . '[' . $this->id . ']' . $this->after;
return wp_editor( ( ! empty( $value ) ? $value : $this->default_value ), $this->pre_id . $this->id . $this->after_id, $this->args ) . $this->output_explanation();
}
function save_value( $value ) {
return wpautop( $value );
}
} |
Switch back to using the old SVN update location.
While changing the download location would be nice, this keeps the option of putting a final data file that would force users to update. | """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://svn.code.sf.net/p/mlox/code/trunk/downloads/' + UPDATE_BASE
| """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://sourceforge.net/projects/mlox/files/mlox/' + UPDATE_BASE
|
BAP-12467: Add ButtonContext Class
- updated test | <?php
namespace Oro\Bundle\ActionBundle\Tests\Unit\Model;
use Oro\Bundle\ActionBundle\Model\ButtonContext;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
class ButtonContextTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
/** @var ButtonContext */
protected $buttonContext;
/**
* {@inheritdoc}
*/
public function setUp()
{
$this->buttonContext = new ButtonContext();
}
public function testGetSetButtonContext()
{
$context = [
['routeName', 'test_route'],
['datagridName', 'datagrid'],
['group', 'test_group'],
['executionUrl', 'test_url1'],
['dialogUrl', 'test_url2'],
['enabled', true],
['unavailableHidden', true]
];
$this->assertPropertyAccessors($this->buttonContext, $context);
}
public function testSetGetEntity()
{
$this->buttonContext->setEntity('Class', 10);
$this->assertSame('Class', $this->buttonContext->getEntityClass());
$this->assertSame(10, $this->buttonContext->getEntityId());
}
}
| <?php
namespace Oro\Bundle\ActionBundle\Tests\Unit\Model;
use Oro\Bundle\ActionBundle\Model\ButtonContext;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
class ButtonContextTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
/** @var ButtonContext */
protected $buttonContext;
/**
* {@inheritdoc}
*/
public function setUp()
{
$this->buttonContext = new ButtonContext();
}
public function testGetSetButtonContext()
{
$context = [
['routeName', 'test_route'],
['datagridName', 'datagrid'],
['group', 'test_group'],
['executionUrl', 'test_url1'],
['dialogUrl', 'test_url2'],
['enabled', true]
];
$this->assertPropertyAccessors($this->buttonContext, $context);
}
public function testSetGetEntity()
{
$this->buttonContext->setEntity('Class', 10);
$this->assertSame('Class', $this->buttonContext->getEntityClass());
$this->assertSame(10, $this->buttonContext->getEntityId());
}
}
|
Add another invalid use case | import test from 'ava';
import avaRuleTester from 'eslint-ava-rule-tester';
import rule from '../src/rules/jsx-no-logical-expression';
const ruleTester = avaRuleTester(test, {
parserOptions: {
ecmaVersion: 2018,
ecmaFeatures: {
jsx: true
}
}
});
const ruleId = 'jsx-no-logical-expression';
const message = 'JSX should not use logical expression';
const error = {
ruleId,
message,
type: 'LogicalExpression'
};
ruleTester.run(ruleId, rule, {
valid: [
'{true ? <div /> : null}',
'{false || false ? <div /> : null}',
'{true && true ? <div /> : null}'
],
invalid: [
{
code: '{true && <div />}',
errors: [error]
},
{
code: '{true || <div />}',
errors: [error]
},
{
code: '{false && <div />}',
errors: [error]
},
{
code: '{undefined && <div />}',
errors: [error]
},
{
code: '{0 && <div />}',
errors: [error]
}
]
});
| import test from 'ava';
import avaRuleTester from 'eslint-ava-rule-tester';
import rule from '../src/rules/jsx-no-logical-expression';
const ruleTester = avaRuleTester(test, {
parserOptions: {
ecmaVersion: 2018,
ecmaFeatures: {
jsx: true
}
}
});
const ruleId = 'jsx-no-logical-expression';
const message = 'JSX should not use logical expression';
const error = {
ruleId,
message,
type: 'LogicalExpression'
};
ruleTester.run(ruleId, rule, {
valid: [
'{true ? <div /> : null}',
'{false || false ? <div /> : null}',
'{true && true ? <div /> : null}'
],
invalid: [
{
code: '{true && <div />}',
errors: [error]
},
{
code: '{true || <div />}',
errors: [error]
}
]
});
|
Remove array from state status. | import React, {Component} from 'react';
import $ from 'jquery';
import CurrentWeatherCard from './CurrentWeatherCard';
export default class App extends Component {
constructor(){
super()
this.state = {
location:'',
weatherData: null,
};
}
handleInput(e) {
this.setState({
location: e.target.value,
})
}
handleSubmit(){
const currentLocation = this.state.location
$.get(`http://api.wunderground.com/api/878e77b9c3411d19/hourly/conditions/forecast10day/q/${currentLocation}.json`).then((data)=> {
this.setState({
location:'',
weatherData: data,
})
})
}
render() {
return (
<div>
<navbar>
<input type="text" value={this.state.location} onChange={this.handleInput.bind(this)}/>
<input type="submit" onClick={this.handleSubmit.bind(this)}/>
</navbar>
<h1 className="welcomeHeader">Weathrly</h1>
<CurrentWeatherCard weatherData={this.state.weatherData}/>
</div>
)
}
}
| import React, {Component} from 'react';
import $ from 'jquery';
import CurrentWeatherCard from './CurrentWeatherCard';
export default class App extends Component {
constructor(){
super()
this.state = {
location:'',
weatherData: [],
};
}
handleInput(e) {
this.setState({
location: e.target.value,
})
}
handleSubmit(){
const currentLocation = this.state.location
$.get(`http://api.wunderground.com/api/878e77b9c3411d19/hourly/conditions/forecast10day/q/${currentLocation}.json`).then((data)=> {
this.state.weatherData.push(data)
this.setState({
location:'',
weatherData: this.state.weatherData,
})
})
}
render() {
return (
<div>
<navbar>
<input type="text" value={this.state.location} onChange={this.handleInput.bind(this)}/>
<input type="submit" onClick={this.handleSubmit.bind(this)}/>
</navbar>
<h1 className="welcomeHeader">Weathrly</h1>
<CurrentWeatherCard weatherData={this.state.weatherData}/>
</div>
)
}
}
|
Change the way semantic is called to allow for looping and handling [SS] | #!/usr/bin/env python
from sys import *
from myreglexer import *
from getopt import *
from myparser import *
from tree import *
from semantic import *
contents = []
def main(argv):
try:
opts, args = getopt(argv, "h", ["help"])
except GetoptError:
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
for arg in args:
try:
with open(arg, 'r') as f:
readin = f.read()
tree = parser(readin)
#tree.traverse_pre()
temp = tree.build_stack_pre()
#print temp
semantic_check(temp)
temp = tree.build_stack_post()
for i in temp:
print i.data[1]
#tree.traverse_post()
except IOError:
print "File %s not found!" % arg
sys.exit(1)
def no_args():
for line in sys.stdin:
contents.append(line)
def usage():
print "Usage: driver.py [-h] infile1 infile2 infile3 ..."
print "Or just take intput from stdin"
if __name__ == "__main__":
if len(sys.argv) < 2:
no_args()
#usage()
#sys.exit(1)
main(sys.argv[1:]) | #!/usr/bin/env python
from sys import *
from myreglexer import *
from getopt import *
from myparser import *
from tree import *
from semantic import *
contents = []
def main(argv):
try:
opts, args = getopt(argv, "h", ["help"])
except GetoptError:
usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
for arg in args:
try:
with open(arg, 'r') as f:
readin = f.read()
tree = parser(readin)
#tree.traverse_pre()
temp = tree.build_stack_pre()
#print temp
print semantic_check(temp)
temp = tree.build_stack_post()
for i in temp:
print i.data[1]
#tree.traverse_post()
except IOError:
print "File %s not found!" % arg
sys.exit(1)
def no_args():
for line in sys.stdin:
contents.append(line)
def usage():
print "Usage: driver.py [-h] infile1 infile2 infile3 ..."
print "Or just take intput from stdin"
if __name__ == "__main__":
if len(sys.argv) < 2:
no_args()
#usage()
#sys.exit(1)
main(sys.argv[1:]) |
Switch express to use twig |
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var gzippo = require('gzippo');
var app = express();
app.configure(function(){
app.set('package', require('../../package.json'));
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'twig');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(gzippo.staticGzip(path.join(__dirname, '../../public')));
app.use(gzippo.compress());
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/views/*.html', routes.view);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
|
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var gzippo = require('gzippo');
var app = express();
app.configure(function(){
app.set('package', require('../../package.json'));
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(gzippo.staticGzip(path.join(__dirname, '../../public')));
app.use(gzippo.compress());
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/views/*.html', routes.view);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
|
Add email tag to fronted deploy failures |
if alert['resource'].startswith('R1'):
alert['service'] = [ 'R1' ]
elif alert['resource'].startswith('R2'):
alert['service'] = [ 'R2' ]
elif 'content-api' in alert['resource'].lower():
alert['service'] = [ 'ContentAPI' ]
elif alert['resource'].startswith('frontend'):
alert['service'] = [ 'Frontend' ]
if alert['event'] == 'DeployFailed':
alert['severity'] = 'CRITICAL'
alert['tags'].append('email:frontend')
elif 'flexible' in alert['resource'].lower():
alert['service'] = [ 'FlexibleContent' ]
elif alert['resource'].startswith('Identity'):
alert['service'] = [ 'Identity' ]
elif alert['resource'].startswith('Mobile'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Android'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('iOS'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Soulmates'):
alert['service'] = [ 'Soulmates' ]
elif alert['resource'].startswith('Microapps'):
alert['service'] = [ 'MicroApp' ]
elif alert['resource'].startswith('Mutualisation'):
alert['service'] = [ 'Mutualisation' ]
elif alert['resource'].startswith('Ophan'):
alert['service'] = [ 'Ophan' ]
else:
alert['service'] = [ 'Unknown' ]
|
if alert['resource'].startswith('R1'):
alert['service'] = [ 'R1' ]
elif alert['resource'].startswith('R2'):
alert['service'] = [ 'R2' ]
elif 'content-api' in alert['resource'].lower():
alert['service'] = [ 'ContentAPI' ]
elif alert['resource'].startswith('frontend'):
alert['service'] = [ 'Frontend' ]
if alert['event'] == 'DeployFailed':
alert['severity'] = 'CRITICAL'
elif 'flexible' in alert['resource'].lower():
alert['service'] = [ 'FlexibleContent' ]
elif alert['resource'].startswith('Identity'):
alert['service'] = [ 'Identity' ]
elif alert['resource'].startswith('Mobile'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Android'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('iOS'):
alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Soulmates'):
alert['service'] = [ 'Soulmates' ]
elif alert['resource'].startswith('Microapps'):
alert['service'] = [ 'MicroApp' ]
elif alert['resource'].startswith('Mutualisation'):
alert['service'] = [ 'Mutualisation' ]
elif alert['resource'].startswith('Ophan'):
alert['service'] = [ 'Ophan' ]
else:
alert['service'] = [ 'Unknown' ]
|
Save the image of the selection (to be able to reinitialise later) |
from SimpleCV import ColorSegmentation, Image, Camera, VirtualCamera, Display, Color
# Open reference video
cam=VirtualCamera('/media/bat/DATA/Baptiste/Nautilab/kite_project/zenith-wind-power-read-only/KiteControl-Qt/videos/kiteFlying.avi','video')
# Select reference image
img=cam.getFrame(50)
modelImage = img.crop(255, 180, 70, 20)
modelImage = Image('kite_detail.jpg')
ts = []
disp=Display()
for i in range(0,50):
img = cam.getImage()
while (disp.isNotDone()):
img = cam.getImage()
bb = (255, 180, 70, 20)
ts = img.track("camshift",ts,modelImage,bb, num_frames = 1)
modelImage = Image('kite_detail.jpg')
# now here in first loop iteration since ts is empty,
# img0 and bb will be considered.
# New tracking object will be created and added in ts (TrackSet)
# After first iteration, ts is not empty and hence the previous
# image frames and bounding box will be taken from ts and img0
# and bb will be ignored.
ts.draw()
ts.drawBB()
ts.showCoordinates()
img.show()
|
from SimpleCV import ColorSegmentation, Image, Camera, VirtualCamera, Display
# Open reference video
cam=VirtualCamera('/media/bat/DATA/Baptiste/Nautilab/kite_project/zenith-wind-power-read-only/KiteControl-Qt/videos/kiteFlying.avi','video')
# Select reference image
img=cam.getFrame(50)
modelImage = img.crop(255, 180, 70, 20)
modelImage = Image('kite_detail.jpg')
ts = []
disp=Display()
for i in range(0,50):
img = cam.getImage()
while (disp.isNotDone()):
img = cam.getImage()
bb = (255, 180, 70, 20)
ts = img.track("camshift",ts,modelImage,bb, num_frames = 1)
# now here in first loop iteration since ts is empty,
# img0 and bb will be considered.
# New tracking object will be created and added in ts (TrackSet)
# After first iteration, ts is not empty and hence the previous
# image frames and bounding box will be taken from ts and img0
# and bb will be ignored.
ts.drawPath()
img.show()
|
Use async attribute on the script tag for our single script
We are loading a single script (in the minified/compiled/built
version of the app). Because the JS loads the HTML fragment
and then decorates it in the correct order, we can do
this asynchronously after the DOM has fully loaded. | /*
condense script and link tags to a single instance of each in the
specified HTML file; like grunt-usemin but less confusing and more dumb
example config:
condense: {
dist: {
file: 'build/app/index.html',
script: 'js/all.js',
stylesheet: 'css/all.css'
}
}
*/
module.exports = function (grunt) {
var fs = require('fs');
grunt.registerMultiTask('condense', 'Condense script and link elements', function () {
var stylesheet = this.data.stylesheet;
var script = this.data.script;
var file = this.data.file;
var content = fs.readFileSync(file, 'utf8');
// remove all link and script elements with a src
content = content.replace(/<link.+?>/g, '');
content = content.replace(/<script.*?src.*?.+?><\/script>/g, '');
// add single <script> just before the closing </body>
var html = '<script async="async" src="' + script + '"></script></body>';
content = content.replace(/<\/body>/, html);
// add a single <link> just above the closing </head>
html = '<link rel="stylesheet" href="' + stylesheet + '"></head>';
content = content.replace(/<\/head>/, html);
// overwrite the original file
fs.writeFileSync(file, content, 'utf8');
});
};
| /*
condense script and link tags to a single instance of each in the
specified HTML file; like grunt-usemin but less confusing and more dumb
example config:
condense: {
dist: {
file: 'build/app/index.html',
script: 'js/all.js',
stylesheet: 'css/all.css'
}
}
*/
module.exports = function (grunt) {
var fs = require('fs');
grunt.registerMultiTask('condense', 'Condense script and link elements', function () {
var stylesheet = this.data.stylesheet;
var script = this.data.script;
var file = this.data.file;
var content = fs.readFileSync(file, 'utf8');
// remove all link and script elements with a src
content = content.replace(/<link.+?>/g, '');
content = content.replace(/<script.*?src.*?.+?><\/script>/g, '');
// add single <script> just before the closing </body>
var html = '<script src="' + script + '"></script></body>';
content = content.replace(/<\/body>/, html);
// add a single <link> just above the closing </head>
html = '<link rel="stylesheet" href="' + stylesheet + '"></head>';
content = content.replace(/<\/head>/, html);
// overwrite the original file
fs.writeFileSync(file, content, 'utf8');
});
};
|
Remove in memory mongodb
When running tests, it use the same port than real mongodb so it cause some tests issues if a read mongodb is running. | package org.jongo;
import org.bson.types.ObjectId;
import org.jongo.model.Friend;
import org.jongo.util.JongoTestCase;
import org.jongo.util.MongoInMemoryRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Iterator;
import static org.fest.assertions.Assertions.assertThat;
public class FindWithHintTest extends JongoTestCase {
private MongoCollection collection;
@Before
public void setUp() throws Exception {
collection = createEmptyCollection("friends");
}
@After
public void tearDown() throws Exception {
dropCollection("friends");
}
@Test
public void canFindWithHint() throws Exception {
/* given */
Friend noName = new Friend(new ObjectId(), null);
collection.save(noName);
collection.ensureIndex("{name: 1}", "{sparse: true}");
/* when */
// force to use _id index instead of name index which is sparsed
Iterator<Friend> friends = collection.find().hint("{$natural: 1}").sort("{name: 1}").as(Friend.class).iterator();
/* then */
assertThat(friends.hasNext()).isTrue();
}
}
| package org.jongo;
import org.bson.types.ObjectId;
import org.jongo.model.Friend;
import org.jongo.util.JongoTestCase;
import org.jongo.util.MongoInMemoryRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.Iterator;
import static org.fest.assertions.Assertions.assertThat;
public class FindWithHintTest extends JongoTestCase {
@Rule
public static final MongoInMemoryRule mongo = new MongoInMemoryRule();
private MongoCollection collection;
@Before
public void setUp() throws Exception {
collection = createEmptyCollection("friends");
}
@After
public void tearDown() throws Exception {
dropCollection("friends");
}
@Test
public void canFindWithHint() throws Exception {
/* given */
Friend noName = new Friend(new ObjectId(), null);
collection.save(noName);
collection.ensureIndex("{name: 1}", "{sparse: true}");
/* when */
// force to use _id index instead of name index which is sparsed
Iterator<Friend> friends = collection.find().hint("{$natural: 1}").sort("{name: 1}").as(Friend.class).iterator();
/* then */
assertThat(friends.hasNext()).isTrue();
}
}
|
Drop supplemental groups for "run"
Drop supplemental group resolution for the "run" command. The necessary
functions weren't in go 1.5, and the runtime spec doesn't give us a
place to put supplemental group information anyway.
Signed-off-by: Nalin Dahyabhai <f562fcb2a0b898bf0be1afc867ea92325d8f825f@redhat.com> | package buildah
import (
"os/user"
"strconv"
"github.com/opencontainers/runtime-spec/specs-go"
)
// TODO: we should doing these lookups using data that's actually in the container.
func getUser(username string) (specs.User, error) {
if username == "" {
return specs.User{}, nil
}
runuser, err := user.Lookup(username)
if err != nil {
return specs.User{}, err
}
uid, err := strconv.ParseUint(runuser.Uid, 10, 32)
if err != nil {
return specs.User{}, nil
}
gid, err := strconv.ParseUint(runuser.Gid, 10, 32)
if err != nil {
return specs.User{}, nil
}
u := specs.User{
UID: uint32(uid),
GID: uint32(gid),
Username: username,
}
return u, nil
}
| package buildah
import (
"os/user"
"strconv"
"github.com/opencontainers/runtime-spec/specs-go"
)
// TODO: we should doing these lookups using data that's actually in the container.
func getUser(username string) (specs.User, error) {
if username == "" {
return specs.User{}, nil
}
runuser, err := user.Lookup(username)
if err != nil {
return specs.User{}, err
}
uid, err := strconv.ParseUint(runuser.Uid, 10, 32)
if err != nil {
return specs.User{}, nil
}
gid, err := strconv.ParseUint(runuser.Gid, 10, 32)
if err != nil {
return specs.User{}, nil
}
groups, err := runuser.GroupIds()
if err != nil {
return specs.User{}, err
}
gids := []uint32{}
for _, group := range groups {
if g, err := user.LookupGroup(group); err == nil {
if gid, err := strconv.ParseUint(g.Gid, 10, 32); err == nil {
gids = append(gids, uint32(gid))
}
}
}
u := specs.User{
UID: uint32(uid),
GID: uint32(gid),
AdditionalGids: gids,
Username: username,
}
return u, nil
}
|
Throw error on unsuccessful execCommand | function copy(text) {
var range = document.createRange();
var newDiv = document.createElement("div");
var newContent = document.createTextNode(text);
newDiv.appendChild(newContent);
document.body.appendChild(newDiv);
range.selectNode(newDiv);
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
if (!successful) {
throw(new Error('copy command was unsuccessful'));
}
} catch(err) {
console.error('unable to copy, trying IE specific stuff');
try {
window.clipboardData.setData("Text", text);
} catch(err) {
console.error('unable to copy, fallback to prompt');
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
} finally {
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
document.body.removeChild(newDiv);
window.getSelection().removeAllRanges();
}
}
module.exports = copy; | function copy(text) {
var range = document.createRange();
var newDiv = document.createElement("div");
var newContent = document.createTextNode(text);
newDiv.appendChild(newContent);
document.body.appendChild(newDiv);
range.selectNode(newDiv);
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
if (!successful) {
console.error('copy command was unsuccessful');
}
} catch(err) {
console.error('unable to copy, trying IE specific stuff');
try {
window.clipboardData.setData("Text", text);
} catch(err) {
console.error('unable to copy, fallback to prompt');
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
} finally {
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
document.body.removeChild(newDiv);
window.getSelection().removeAllRanges();
}
}
module.exports = copy; |
[PAXWEB-955] Fix typo in Accept-Language header | /*
* 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.ops4j.pax.web.itest.base.client;
public class HttpTestClientFactory {
/**
* creates a default HttpTestClient based on Apache HttpComponents with
* some default configuration.
* <ul>
* <li>Return-Code: 200 OK</li>
* <li>Keystore: src/test/resources/keystore</li>
* <li>Request-Header: Accept-Language=en</li>
* </ul>
* @return Apache HttpComponents HttpTestClient
*/
public static HttpTestClient createHttpComponentsTestClient(){
return new HttpComponentsTestClient()
.withKeystore("src/test/resources/keystore", "admin", "admin")
.addRequestHeader("Accept-Language", "en")
.withReturnCode(200);
}
}
| /*
* 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.ops4j.pax.web.itest.base.client;
public class HttpTestClientFactory {
/**
* creates a default HttpTestClient based on Apache HttpComponents with
* some default configuration.
* <ul>
* <li>Return-Code: 200 OK</li>
* <li>Keystore: src/test/resources/keystore</li>
* <li>Request-Header: Accept-Language=en</li>
* </ul>
* @return Apache HttpComponents HttpTestClient
*/
public static HttpTestClient createHttpComponentsTestClient(){
return new HttpComponentsTestClient()
.withKeystore("src/test/resources/keystore", "admin", "admin")
.addRequestHeader("Acccept-Language", "en")
.withReturnCode(200);
}
}
|
Remove user salt from deserialize | import passport from 'koa-passport';
import User from '../src/models/users'
import { Strategy } from 'passport-local'
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id, '-password -salt')
done(null, user)
} catch(err) {
done(err)
}
})
passport.use('local', new Strategy({
usernameField: 'username',
passwordField: 'password'
}, async (username, password, done) => {
try {
const user = await User.findOne({ username })
if(!user) { return done(null, false) }
try {
const isMatch = await user.validatePassword(password)
if(!isMatch) { return done(null, false) }
done(null, user)
} catch(err) {
done(err)
}
} catch(err) {
return done(err)
}
}))
| import passport from 'koa-passport';
import User from '../src/models/users'
import { Strategy } from 'passport-local'
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id, '-password')
done(null, user)
} catch(err) {
done(err)
}
})
passport.use('local', new Strategy({
usernameField: 'username',
passwordField: 'password'
}, async (username, password, done) => {
try {
const user = await User.findOne({ username })
if(!user) { return done(null, false) }
try {
const isMatch = await user.validatePassword(password)
if(!isMatch) { return done(null, false) }
done(null, user)
} catch(err) {
done(err)
}
} catch(err) {
return done(err)
}
}))
|
Enable in-memory cache backend for development environment, but not tests | from .settings import *
import os
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'getyourdatadevdb',
'USER': 'getyourdatadevuser',
'PASSWORD': 'getyourdatadevpwd',
'HOST': 'localhost',
'PORT': '',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
if TESTING:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
AUTH_PASSWORD_VALIDATORS = []
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
if TESTING:
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
os.environ["RECAPTCHA_TESTING"] = 'True'
PIPELINE['PIPELINE_ENABLED'] = False
STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
| from .settings import *
import os
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'getyourdatadevdb',
'USER': 'getyourdatadevuser',
'PASSWORD': 'getyourdatadevpwd',
'HOST': 'localhost',
'PORT': '',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
AUTH_PASSWORD_VALIDATORS = []
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
if TESTING:
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
os.environ["RECAPTCHA_TESTING"] = 'True'
PIPELINE['PIPELINE_ENABLED'] = False
STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
|
Improve readability of code to extend options | const { fields, validators, widgets, create: createForm } = require('forms');
function extendOptions(options, newOptions) {
return Object.assign({ }, options, newOptions);
}
function textField(label, maxlength, options = { }) {
return fields.string(extendOptions(options, {
widget: widgets.text({
maxlength,
classes: [ 'pixel' ],
placeholder: options.placeholder,
}),
label,
validators: [
validators.maxlength(maxlength),
],
cssClasses,
}));
}
const cssClasses = {
error: [ 'error' ],
label: [ 'form-label-longform' ],
field: [ 'form-row', 'form-row-margin' ],
};
const requiredField = validators.required('This field is required.');
/**
* Create the object representation of our application form.
*
* To support client side validation in browsers that don't have sufficient APIs, there is
* an option to disable file validation.
*/
exports.createTeamForm = function createTeamForm(defaults = { }) {
for (const def in defaults) {
defaults[def] = { value: defaults[def] };
}
return createForm({
memberB: textField('B', 256, extendOptions(defaults.memberB, { required: requiredField, placeholder: 'Enter the Application ID' })),
memberC: textField('C', 256, extendOptions(defaults.memberC, { placeholder: 'Enter the Application ID' })),
memberD: textField('D', 256, extendOptions(defaults.memberD, { placeholder: 'Enter the Application ID' })),
}, {
validatePastFirstError: true,
});
}; | const { fields, validators, widgets, create: createForm } = require('forms');
function textField(label, maxlength, options = { }) {
return fields.string(Object.assign({ }, options, {
widget: widgets.text({
maxlength,
classes: [ 'pixel' ],
placeholder: options.placeholder,
}),
label,
validators: [
validators.maxlength(maxlength),
],
cssClasses,
}));
}
const cssClasses = {
error: [ 'error' ],
label: [ 'form-label-longform' ],
field: [ 'form-row', 'form-row-margin' ],
};
const requiredField = validators.required('This field is required.');
/**
* Create the object representation of our application form.
*
* To support client side validation in browsers that don't have sufficient APIs, there is
* an option to disable file validation.
*/
exports.createTeamForm = function createTeamForm(defaults = { }) {
for (const def in defaults) {
defaults[def] = { value: defaults[def] };
}
return createForm({
memberB: textField('B', 256, Object.assign({ required: requiredField, placeholder: 'Enter the Application ID' }, defaults.memberB)),
memberC: textField('C', 256, Object.assign({ placeholder: 'Enter the Application ID' }, defaults.memberC)),
memberD: textField('D', 256, Object.assign({ placeholder: 'Enter the Application ID' }, defaults.memberD)),
}, {
validatePastFirstError: true,
});
}; |
Remove interface method "add" since Facebook class work differently so not nedded anymore | <?php
/**
* @title Interface Api Class
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Connect / Inc / Class
* @version 1.1
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
interface IApi
{
/**
* Set an user authentication.
*
* @param integer $iId
* @param object \PH7\UserCoreModel $oUserModel
* @return void
*/
public function setLogin($iId, UserCoreModel $oUserModel);
/**
* Set Avatar.
*
* @param string $sUrl URL of avatar.
* @return void
*/
public function setAvatar($sUrl);
/**
* Get Avatar.
*
* @param string $sUrl
* @return string The Avatar
*/
public function getAvatar($sUrl);
}
| <?php
/**
* @title Interface Api Class
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Connect / Inc / Class
* @version 1.1
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
interface IApi
{
/**
* Set an user authentication.
*
* @param integer $iId
* @param object \PH7\UserCoreModel $oUserModel
* @return void
*/
public function setLogin($iId, UserCoreModel $oUserModel);
/**
* Set Avatar.
*
* @param string $sUrl URL of avatar.
* @return void
*/
public function setAvatar($sUrl);
/**
* Get Avatar.
*
* @param string $sUrl
* @return string The Avatar
*/
public function getAvatar($sUrl);
/**
* Add User.
*
* @param array $aData
* @param object \PH7\UserCoreModel $oUserModel
* @return void
*/
public function add(array $aData, UserCoreModel $oUserModel);
}
|
Add a start and end method to MockRequest | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
| #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
|
Set redis socket timeout to 5s | from flask import Flask, render_template, request, make_response, g
from redis import Redis
import os
import socket
import random
import json
option_a = os.getenv('OPTION_A', "Cats")
option_b = os.getenv('OPTION_B', "Dogs")
hostname = socket.gethostname()
app = Flask(__name__)
def get_redis():
if not hasattr(g, 'redis'):
g.redis = Redis(host="redis", db=0, socket_timeout=5)
return g.redis
@app.route("/", methods=['POST','GET'])
def hello():
voter_id = request.cookies.get('voter_id')
if not voter_id:
voter_id = hex(random.getrandbits(64))[2:-1]
vote = None
if request.method == 'POST':
redis = get_redis()
vote = request.form['vote']
data = json.dumps({'voter_id': voter_id, 'vote': vote})
redis.rpush('votes', data)
resp = make_response(render_template(
'index.html',
option_a=option_a,
option_b=option_b,
hostname=hostname,
vote=vote,
))
resp.set_cookie('voter_id', voter_id)
return resp
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
| from flask import Flask, render_template, request, make_response, g
from redis import Redis
import os
import socket
import random
import json
option_a = os.getenv('OPTION_A', "Cats")
option_b = os.getenv('OPTION_B', "Dogs")
hostname = socket.gethostname()
app = Flask(__name__)
def get_redis():
if not hasattr(g, 'redis'):
g.redis = Redis(host="redis", db=0)
return g.redis
@app.route("/", methods=['POST','GET'])
def hello():
voter_id = request.cookies.get('voter_id')
if not voter_id:
voter_id = hex(random.getrandbits(64))[2:-1]
vote = None
if request.method == 'POST':
redis = get_redis()
vote = request.form['vote']
data = json.dumps({'voter_id': voter_id, 'vote': vote})
redis.rpush('votes', data)
resp = make_response(render_template(
'index.html',
option_a=option_a,
option_b=option_b,
hostname=hostname,
vote=vote,
))
resp.set_cookie('voter_id', voter_id)
return resp
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
|
Fix issue with Sass encoding
Sass::SyntaxError on line LINE of FILE: Invalid US-ASCII character CHAR | /**
* Compass task config
*/
exports.task = function () {
return {
dist: {
options: {
importPath: [
'tmp/sass/cartoassets'
],
sassDir: 'tmp/sass/editor',
cssDir: '<%= assets_dir %>/stylesheets',
fontsDir: '<%= assets_dir %>/fonts',
httpFontsPath: '<%= env.http_path_prefix %>/assets/<%= pkg.version %>/fonts',
imagesDir: 'app/assets/images/',
generatedImagesDir: '<%= assets_dir %>/images/',
httpImagesPath: '<%= env.http_path_prefix %>/assets/<%= pkg.version %>/images/',
httpGeneratedImagesPath: '<%= env.http_path_prefix %>/assets/<%= pkg.version %>/images/',
environment: 'production',
outputStyle: 'compressed',
noLineComments: true,
force: false,
time: true,
raw: 'Encoding.default_external = \'utf-8\'\n'
}
}
};
};
| /**
* Compass task config
*/
exports.task = function () {
return {
dist: {
options: {
importPath: [
'tmp/sass/cartoassets'
],
sassDir: 'tmp/sass/editor',
cssDir: '<%= assets_dir %>/stylesheets',
fontsDir: '<%= assets_dir %>/fonts',
httpFontsPath: '<%= env.http_path_prefix %>/assets/<%= pkg.version %>/fonts',
imagesDir: 'app/assets/images/',
generatedImagesDir: '<%= assets_dir %>/images/',
httpImagesPath: '<%= env.http_path_prefix %>/assets/<%= pkg.version %>/images/',
httpGeneratedImagesPath: '<%= env.http_path_prefix %>/assets/<%= pkg.version %>/images/',
environment: 'production',
outputStyle: 'compressed',
noLineComments: true,
force: false,
time: true
}
}
};
};
|
Return unmodified source immediately if no generator functions detected.
Closes #13. | var assert = require("assert");
var path = require("path");
var transform = require("./lib/visit").transform;
var guessTabWidth = require("./lib/util").guessTabWidth;
var recast = require("recast");
var esprimaHarmony = require("esprima");
var genFunExp = /\bfunction\s*\*/;
assert.ok(
/harmony/.test(esprimaHarmony.version),
"Bad esprima version: " + esprimaHarmony.version
);
function regenerate(source) {
if (!genFunExp.test(source)) {
return source; // Shortcut: no generators to transform.
}
var options = {
tabWidth: guessTabWidth(source),
// Use the harmony branch of Esprima that installs with regenerator
// instead of the master branch that recast provides.
esprima: esprimaHarmony
};
var ast = recast.parse(source, options);
return recast.print(transform(ast), options);
}
// To modify an AST directly, call require("regenerator").transform(ast).
regenerate.transform = transform;
regenerate.runtime = {
dev: path.join(__dirname, "runtime", "dev.js"),
min: path.join(__dirname, "runtime", "min.js")
};
// To transform a string of ES6 code, call require("regenerator")(source);
module.exports = regenerate;
| var assert = require("assert");
var path = require("path");
var transform = require("./lib/visit").transform;
var guessTabWidth = require("./lib/util").guessTabWidth;
var recast = require("recast");
var esprimaHarmony = require("esprima");
assert.ok(
/harmony/.test(esprimaHarmony.version),
"Bad esprima version: " + esprimaHarmony.version
);
function regenerate(source) {
var options = {
tabWidth: guessTabWidth(source),
// Use the harmony branch of Esprima that installs with regenerator
// instead of the master branch that recast provides.
esprima: esprimaHarmony
};
var ast = recast.parse(source, options);
return recast.print(transform(ast), options);
}
// To modify an AST directly, call require("regenerator").transform(ast).
regenerate.transform = transform;
regenerate.runtime = {
dev: path.join(__dirname, "runtime", "dev.js"),
min: path.join(__dirname, "runtime", "min.js")
};
// To transform a string of ES6 code, call require("regenerator")(source);
module.exports = regenerate;
|
Solve typo in xtreme testing
PiperOrigin-RevId: 477195014 | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for xtreme."""
from tensorflow_datasets.dataset_collections.xtreme import xtreme
from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase
class TestXtreme(DatasetCollectionTestBase):
DATASET_COLLECTION_CLASS = xtreme.Xtreme
| # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for xtreme."""
from tensorflow_datasets.dataset_collections.xtreme import xtreme
from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase
class TestLongt5(DatasetCollectionTestBase):
DATASET_COLLECTION_CLASS = xtreme.Xtreme
|
Revert "Use the more common type name T instead of L."
This reverts commit 146fa40dd6b6889277a86f6e5858ffacb672480c. | /*
* 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.spi;
import java.io.Closeable;
/**
* A basic registry for {@link LoggerContext} objects and their associated external
* Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
* other external log systems.
*
* @param <L> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
* @since 2.1
*/
public interface LoggerAdapter<L> extends Closeable {
/**
* Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
*
* @param name the name of the logger to get
* @return the named logger
*/
L getLogger(String name);
}
| /*
* 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.spi;
import java.io.Closeable;
/**
* A basic registry for {@link LoggerContext} objects and their associated external
* Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
* other external log systems.
*
* @param <T> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
* @since 2.1
*/
public interface LoggerAdapter<T> extends Closeable {
/**
* Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
*
* @param name the name of the logger to get
* @return the named logger
*/
T getLogger(String name);
}
|
leapp: Add back missing manager creation | from leapp.utils.clicmd import command, command_opt
from leapp.repository.scan import find_and_scan_repositories
from leapp.config import get_config
from leapp.logger import configure_logger
def load_repositories_from(name, repo_path, manager=None):
if get_config().has_option('repositories', name):
repo_path = get_config().get('repositories', name)
return find_and_scan_repositories(repo_path, manager=manager)
def load_repositories():
manager = load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
return manager
@command('upgrade', help='')
@command_opt('resume', is_flag=True, help='Continue the last execution after it was stopped (e.g. after reboot)')
def upgrade(args):
configure_logger()
repositories = load_repositories()
workflow = repositories.lookup_workflow('IPUWorkflow')
workflow.run()
| from leapp.utils.clicmd import command, command_opt
from leapp.repository.scan import find_and_scan_repositories
from leapp.config import get_config
from leapp.logger import configure_logger
def load_repositories_from(name, repo_path, manager=None):
if get_config().has_option('repositories', name):
repo_path = get_config().get('repositories', name)
return find_and_scan_repositories(repo_path, manager=manager)
def load_repositories():
load_repositories_from('custom_repo_path', '/etc/leapp/repos.d/', manager=None)
manager.load()
return manager
@command('upgrade', help='')
@command_opt('resume', is_flag=True, help='Continue the last execution after it was stopped (e.g. after reboot)')
def upgrade(args):
configure_logger()
repositories = load_repositories()
workflow = repositories.lookup_workflow('IPUWorkflow')
workflow.run()
|
Use the logger within exception handler and shutdown function | <?php
namespace akilli;
use ErrorException;
use Throwable;
/**
* Initialize application
*/
foreach (glob(__DIR__ . '/../src/*.php') as $file) {
include_once $file;
}
/**
* Error handler
*/
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
);
set_exception_handler(
function (Throwable $e) {
critical((string) $e);
}
);
register_shutdown_function(
function () {
$error = error_get_last();
$errors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING];
if ($error && in_array($error['type'], $errors)) {
critical(print_r($error, 1));
}
}
);
/**
* Run application
*/
app();
| <?php
namespace akilli;
use ErrorException;
use Throwable;
/**
* Initialize application
*/
foreach (glob(__DIR__ . '/../src/*.php') as $file) {
include_once $file;
}
/**
* Error handler
*/
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
);
set_exception_handler(
function (Throwable $e) {
echo '<pre>' . (string) $e . '</pre>';
}
);
register_shutdown_function(
function () {
$error = error_get_last();
$errors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING];
if ($error && in_array($error['type'], $errors)) {
echo '<pre>' . print_r($error, 1) . '</pre>';
}
}
);
/**
* Run application
*/
app();
|
Update status validation to allow for new voter-reg statuses | <?php
namespace Rogue\Http\Requests;
class PostRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'campaign_id' => 'required',
'campaign_run_id' => 'integer',
'northstar_id' => 'nullable|objectid',
'type' => 'required|string|in:photo,voter-reg,text',
'action' => 'required|string',
'why_participated' => 'nullable|string',
'text' => 'nullable|string|max:256',
'quantity' => 'nullable|integer',
'file' => 'image|dimensions:min_width=400,min_height=400',
'status' => 'in:pending,accepted,rejected,register-form,register-OVR,confirmed,ineligible,uncertain',
'details'=> 'json',
];
}
}
| <?php
namespace Rogue\Http\Requests;
class PostRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'campaign_id' => 'required',
'campaign_run_id' => 'integer',
'northstar_id' => 'nullable|objectid',
'type' => 'required|string|in:photo,voter-reg,text',
'action' => 'required|string',
'why_participated' => 'nullable|string',
'text' => 'nullable|string|max:256',
'quantity' => 'nullable|integer',
'file' => 'image|dimensions:min_width=400,min_height=400',
'status' => 'in:pending,accepted,rejected',
'details'=> 'json',
];
}
}
|
Add ModelNotFound Exception in exception handler | <?php namespace App\Exceptions;
use Exception;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
return response()->json([ 'error' => [
'message' => 'Resource Not Found!',
'code' => 404
]],404);
}
return parent::render($request, $e);
}
}
| <?php namespace App\Exceptions;
use Exception;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
return parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}
|
Add my email to the submit php form | <?php
$EmailFrom = "";
$EmailTo = "kimmarieallen@gmail.com";
$Subject = "";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?> | <?php
$EmailFrom = "";
$EmailTo = "kimmarieallen@gmail.com";
$Subject = "subject of message here";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?> |
Set gasprice for Ropsten to 23 gwei | module.exports = {
migrations_directory: "./migrations",
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "6666" // RNG ;)
},
live: {
host: "localhost",
port: 8546,
network_id: 1,
},
Ropsten: {
host: "localhost",
port: 8547,
network_id: 3,
gasprice: 23000000000, // 23 gwei
},
Rinkeby: {
host: "localhost",
port: 8548,
network_id: 4,
}
}
}
| module.exports = {
migrations_directory: "./migrations",
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "6666" // RNG ;)
},
live: {
host: "localhost",
port: 8546,
network_id: 1,
},
Ropsten: {
host: "localhost",
port: 8547,
network_id: 3,
},
Rinkeby: {
host: "localhost",
port: 8548,
network_id: 4,
}
}
}
|
Add toString method for CallSiteContext | // Context for k-CFA analysis
//
// Assume a context is an array of numbers.
// A number in such list denotes a call site, that is @label of a CallExpression.
// We keep the most recent 'k' callsites.
// Equality on contexts should look into the numbers.
var callSiteContextParameter = {
// maximum length of context
maxDepthK: 0,
// function list for sensitive analysis
sensFuncs: {}
};
function CallSiteContext() {
this.csList = [];
}
CallSiteContext.prototype.equals = function (other) {
if (this.csList.length != other.csList.length) return false;
for (var i = 0; i < this.csList.length; i++) {
if (this.csList[i] != other.csList[i]) return false;
}
return true;
};
CallSiteContext.prototype.appendOne = function (callSite) {
// use concat to create a new array
// oldest one comes first
var appended = this.csList.concat(callSite);
if (appended.length > callSiteContextParameter.maxDepthK) {
appended.shift();
}
};
CallSiteContext.prototype.toString = function () {
return this.csList.toString();
};
exports.callSiteContextParameter = callSiteContextParameter;
exports.CallSiteContext = CallSiteContext; | // Context for k-CFA analysis
//
// Assume a context is an array of numbers.
// A number in such list denotes a call site, that is @label of a CallExpression.
// We keep the most recent 'k' callsites.
// Equality on contexts should look into the numbers.
var callSiteContextParameter = {
// maximum length of context
maxDepthK: 0,
// function list for sensitive analysis
sensFuncs: {}
};
function CallSiteContext() {
this.csList = [];
}
CallSiteContext.prototype.isEqual = function (other) {
if (this.csList.length != other.csList.length) return false;
for (var i = 0; i < this.csList.length; i++) {
if (this.csList[i] != other.csList[i]) return false;
}
return true;
};
CallSiteContext.prototype.appendOne = function (callSite) {
// use concat to create a new array
// oldest one comes first
var appended = this.csList.concat(callSite);
if (appended.length > callSiteContextParameter.maxDepthK) {
appended.shift();
}
};
exports.callSiteContextParameter = callSiteContextParameter;
exports.CallSiteContext = CallSiteContext; |
:bug: Fix invalid source map for imported files in transformer-less | // @flow
import path from 'path'
import { createFileTransformer, loadLocalFromContext } from 'pundle-api'
import manifest from '../package.json'
function createComponent({ extensions = ['.less'], options = {} }: { extensions?: Array<string>, options?: Object } = {}) {
return createFileTransformer({
name: 'pundle-transformer-less',
version: manifest.version,
priority: 2000,
async callback({ file, context }) {
const extName = path.extname(file.filePath)
if (!extensions.includes(extName)) return null
const { name, exported } = loadLocalFromContext(context, ['less'])
if (!name) {
throw new Error(`'less' not found in '${context.config.rootDirectory}'`)
}
const processed = await exported.render(typeof file.contents === 'string' ? file.contents : file.contents.toString(), {
filename: file.filePath,
sourceMap: {},
...options,
})
return {
contents: processed.css,
sourceMap: JSON.parse(processed.map),
}
},
})
}
module.exports = createComponent
| // @flow
import path from 'path'
import { createFileTransformer, loadLocalFromContext } from 'pundle-api'
import manifest from '../package.json'
function createComponent({ extensions = ['.less'], options = {} }: { extensions?: Array<string>, options?: Object } = {}) {
return createFileTransformer({
name: 'pundle-transformer-less',
version: manifest.version,
priority: 2000,
async callback({ file, context }) {
const extName = path.extname(file.filePath)
if (!extensions.includes(extName)) return null
const { name, exported } = loadLocalFromContext(context, ['less'])
if (!name) {
throw new Error(`'less' not found in '${context.config.rootDirectory}'`)
}
const processed = await exported.render(typeof file.contents === 'string' ? file.contents : file.contents.toString(), {
sourceMap: {},
paths: [path.dirname(file.filePath)],
...options,
})
return {
contents: processed.css,
sourceMap: JSON.parse(processed.map),
}
},
})
}
module.exports = createComponent
|
Check match exists before extracting latestYear | module.exports = function (licenseContent, done) {
var thisYear = (new Date()).getFullYear();
var latestYear, originalYearInfo, updatedYearInfo, match, updatedLicenseContent;
match = licenseContent.match(/Copyright \(c\) (\d{4})\s*[~-]\s*(\d{4})/);
if (match) {
latestYear = match[2];
if (parseInt(latestYear) < thisYear) {
originalYearInfo = match[0];
updatedYearInfo = originalYearInfo.replace(latestYear, thisYear);
updatedLicenseContent = licenseContent
.replace(originalYearInfo, updatedYearInfo);
done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo);
return;
}
} else {
match = licenseContent.match(/Copyright \(c\) (\d{4})/);
if (match) {
latestYear = match[1];
if (parseInt(latestYear) < thisYear) {
originalYearInfo = match[0];
updatedYearInfo = originalYearInfo + '-' + thisYear;
updatedLicenseContent = licenseContent
.replace(originalYearInfo, updatedYearInfo);
done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo);
return;
}
}
}
// Otherwise update is not needed
done();
};
| module.exports = function (licenseContent, done) {
var thisYear = (new Date()).getFullYear();
var latestYear, originalYearInfo, updatedYearInfo, match, updatedLicenseContent;
match = licenseContent.match(/Copyright \(c\) (\d{4})\s*[~-]\s*(\d{4})/);
if (match) {
latestYear = match[2];
if (parseInt(latestYear) < thisYear) {
originalYearInfo = match[0];
updatedYearInfo = originalYearInfo.replace(latestYear, thisYear);
updatedLicenseContent = licenseContent
.replace(originalYearInfo, updatedYearInfo);
done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo);
return;
}
} else {
match = licenseContent.match(/Copyright \(c\) (\d{4})/);
latestYear = match[1];
if (parseInt(latestYear) < thisYear) {
originalYearInfo = match[0];
updatedYearInfo = originalYearInfo + '-' + thisYear;
updatedLicenseContent = licenseContent
.replace(originalYearInfo, updatedYearInfo);
done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo);
return;
}
}
// Otherwise update is not needed
done();
};
|
Add explanation to spreadsheet title input | import React from 'react';
import './Options.css';
export default class Options extends React.Component {
constructor() {
super();
this.state = {
filename: ''
};
}
componentDidMount() {
this.setState({ filename: this.props.filename });
}
onKeyDown(event) {
const { onFilenameChange } = this.props;
//return
if(event.keyCode === 13) {
onFilenameChange(this.refs.spreadSheetNameInput.value);
}
}
onBlur() {
const { onFilenameChange } = this.props;
onFilenameChange(this.refs.spreadSheetNameInput.value);
}
onTextChange(event) {
this.setState({ filename: event.target.value });
}
render() {
const { filename } = this.state;
return (
<div className="spreadsheet-options">
<h1>Give you spreadsheet a name</h1>
<input
ref='spreadSheetNameInput'
type="text"
onBlur={this.onBlur.bind(this)}
onKeyDown={this.onKeyDown.bind(this)}
placeholder="Spreadsheet name"
onChange={this.onTextChange.bind(this)}
value={filename}
/>
</div>
);
}
} | import React from 'react';
import './Options.css';
export default class Options extends React.Component {
constructor() {
super();
this.state = {
filename: ''
};
}
componentDidMount() {
this.setState({ filename: this.props.filename });
}
onKeyDown(event) {
const { onFilenameChange } = this.props;
//return
if(event.keyCode === 13) {
onFilenameChange(this.refs.spreadSheetNameInput.value);
}
}
onBlur() {
const { onFilenameChange } = this.props;
onFilenameChange(this.refs.spreadSheetNameInput.value);
}
onTextChange(event) {
this.setState({ filename: event.target.value });
}
render() {
const { filename } = this.state;
return (
<div className="spreadsheet-options">
<input
ref='spreadSheetNameInput'
type="text"
onBlur={this.onBlur.bind(this)}
onKeyDown={this.onKeyDown.bind(this)}
placeholder="Spreadsheet name"
onChange={this.onTextChange.bind(this)}
value={filename}
/>
</div>
);
}
} |
Fix place deletion view logic | class ManageController {
constructor($scope, toastr, _, PlaceFactory) {
'ngInject';
$scope.headers = [
'ID',
'Name',
'Country',
'Image',
'Enabled',
'Actions'
];
$scope.places = [];
$scope.delete = function(id, name) {
var result = confirm("Are you sure you want to delete place " + name + "?");
if(result) {
PlaceFactory.delete(id).then(function(data) {
$scope.places = _.remove($scope.places, function(place) {
return place.place_id !== id;
});
toastr.success('Place deleted.');
}, function(error) {
toastr.error('Failed to delete place: ' + error.data.detail);
});
}
};
PlaceFactory.getList().success(function(data) {
data = _.sortBy(data, "place_id");
data = _.each(data, function(place) {
place.continent = place.continent === null ? "-" : place.continent;
place.image = place.image === null ? "" : place.image;
});
$scope.places = data;
});
}
}
export default ManageController;
| class ManageController {
constructor($scope, toastr, _, PlaceFactory) {
'ngInject';
$scope.headers = [
'ID',
'Name',
'Country',
'Image',
'Enabled',
'Actions'
];
$scope.places = [];
$scope.delete = function(id, name) {
var result = confirm("Are you sure you want to delete place " + name + "?");
if(result) {
PlaceFactory.delete(id).then(function(data) {
$scope.places = _.remove($scope.places, function(place) {
return place.country_id !== id;
});
toastr.success('Place deleted.');
}, function(error) {
toastr.error('Failed to delete place: ' + error.data.detail);
});
}
};
PlaceFactory.getList().success(function(data) {
data = _.sortBy(data, "country_id");
data = _.each(data, function(place) {
place.continent = place.continent === null ? "-" : place.continent;
place.image = place.image === null ? "" : place.image;
});
$scope.places = data;
});
}
}
export default ManageController;
|
Fix public URL of static assets | var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var context = path.resolve('pyconcz_2016', 'static');
module.exports = {
context: context,
entry: [
'webpack-dev-server/client?http://localhost:8001',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: context,
filename: "[name]-[hash].js",
publicPath: 'http://lan.pycon.cz:8001/static/_build/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new BundleTracker({
filename: './pyconcz_2016/static/_build/webpack-stats.json'
})
],
module: {
loaders: [
{ test: /\.scss$/, loaders: ['style', 'css', 'sass']}
]
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js']
}
};
| var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var context = path.resolve('pyconcz_2016', 'static');
module.exports = {
context: context,
entry: [
'webpack-dev-server/client?http://localhost:8001',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: context,
filename: "[name]-[hash].js",
publicPath: 'http://localhost:8001/static/_build/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new BundleTracker({
filename: './pyconcz_2016/static/_build/webpack-stats.json'
})
],
module: {
loaders: [
{ test: /\.scss$/, loaders: ['style', 'css', 'sass']}
]
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js']
}
};
|
Move lists to the left | import React, { Component } from "react";
import styled from "styled-components";
import { Row, RowContent, ColumnContainer } from "../SharedComponents.js";
import Loading from "../loading.js";
import List from "./List.js";
import CreateList from "./CreateList.js";
import Notes from "./Notes.js";
class ListsView extends Component {
render() {
const { user, lists, loading } = this.props;
if (loading) {
return <Loading />;
}
return (
<ColumnContainer>
<Row>
<RowContent>
Du är: {user.nick}
</RowContent>
</Row>
<MainContainer>
<ListContainer width={(lists.length - 2) * 20}>
{lists.map(list => <List key={list.id} list={list} user={user} />)}
</ListContainer>
{user.isAdmin && <CreateList />}
<Notes />
</MainContainer>
</ColumnContainer>
);
}
}
const ListContainer = Row.extend`
margin-left: -${props => props.width}em;
`;
const MainContainer = styled(Row)`
padding-top: 2em;
`;
export default ListsView;
| import React, { Component } from "react";
import styled from "styled-components";
import { Row, RowContent, ColumnContainer } from "../SharedComponents.js";
import Loading from "../loading.js";
import List from "./List.js";
import CreateList from "./CreateList.js";
import Notes from "./Notes.js";
class ListsView extends Component {
render() {
const { user, lists, loading } = this.props;
if (loading) {
return <Loading />;
}
return (
<ColumnContainer>
<Row>
<RowContent>
Du är: {user.nick}
</RowContent>
</Row>
<ListsContainer>
{lists.map(list => <List key={list.id} list={list} user={user} />)}
<Notes />
{user.isAdmin && <CreateList />}
</ListsContainer>
</ColumnContainer>
);
}
}
const ListsContainer = styled(Row)`
padding-top: 2em;
`;
export default ListsView;
|
Use a constant for num NPCs. | !function(seine, exports) {
'use strict';
var Component = seine.Component,
Keylogger = demo.Keylogger,
Player = demo.Player,
NPC = demo.NPC,
Tile = demo.Tile;
var NUM_NPCS = 20;
var World = Component.extend({
init: function() {
var i, tile,
numTiles = Math.ceil(document.body.clientWidth / 48);
this.push(new Keylogger);
for(i = 0; i < numTiles; i++) {
tile = new Tile;
tile.hitbox.y = 48 * 10;
tile.hitbox.x = i * 48;
this.push(tile);
}
tile = new Tile;
tile.hitbox.y = 48 * 9;
tile.hitbox.x = (numTiles - 1) * 48;
this.push(tile);
for(i = 0; i < NUM_NPCS; i++) {
this.push(new NPC);
}
this.push(new Player);
}
});
exports.World = World;
}(seine, demo);
| !function(seine, exports) {
'use strict';
var Component = seine.Component,
Keylogger = demo.Keylogger,
Player = demo.Player,
NPC = demo.NPC,
Tile = demo.Tile;
var World = Component.extend({
init: function() {
var i, tile,
numTiles = Math.ceil(document.body.clientWidth / 48);
this.push(new Keylogger);
for(i = 0; i < numTiles; i++) {
tile = new Tile;
tile.hitbox.y = 48 * 10;
tile.hitbox.x = i * 48;
this.push(tile);
}
tile = new Tile;
tile.hitbox.y = 48 * 9;
tile.hitbox.x = (numTiles - 1) * 48;
this.push(tile);
for(i = 0; i < 20; i++) {
this.push(new NPC);
}
this.push(new Player);
}
});
exports.World = World;
}(seine, demo);
|
Add import for db and close it at the end of the request | import sqlite from 'sqlite3';
module.exports = {
setupRestApiGet : function(app) {
// get sent a lat, long, send all items near it
app.get('/parkItems', function(req, res) {
var lat = req.body.lat;
var long = req.body.long;
var items = findAllNearbyItems(lat, long);
res.send(JSON.stringify(items));
});
}
}
function findAllNearbyItems(lat, long) {
var db = new sqlite.Database('UUUYou.db');
db.all(`SELECT * FROM Items WHERE latitude BETWEEN ${lat-0.02} AND ${lat+0.02} AND longitude BETWEEN ${long-0.02} AND ${long+0.02}`, function(err, rows) {
return rows;
});
db.close();
} |
module.exports = {
setupRestApiGet : function(app) {
// get sent a lat, long, send all items near it
app.get('/parkItems', function(req, res) {
var lat = req.body.lat;
var long = req.body.long;
var items = findAllNearbyItems(lat, long);
res.send(JSON.stringify(items));
});
}
}
function findAllNearbyItems(lat, long) {
var db = new sqlite.Database('UUUYou.db');
db.all(`SELECT * FROM Items WHERE latitude BETWEEN ${lat-0.02} AND ${lat+0.02} AND longitude BETWEEN ${long-0.02} AND ${long+0.02}`, function(err, rows) {
return rows;
});
} |
Add a 1 second sleep before we stop recording, so we can hopefully see the browser closing | package com.mooo.aimmac23.node;
import java.io.File;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class VideoRecordController {
private ThreadPoolExecutor executor;
RecordVideoCallable currentCallable;
private Future<File> currentFuture;
public VideoRecordController() {
executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(5));
executor.setThreadFactory(new RecorderThreadFactory());
executor.prestartAllCoreThreads();
}
public void startRecording() {
if(currentCallable != null) {
throw new IllegalStateException("Video recording currently in progress, cannot record again");
}
currentCallable = new RecordVideoCallable();
currentFuture = executor.submit(currentCallable);
}
public File stopRecording() throws Exception {
if(currentCallable == null) {
throw new IllegalStateException("Video recording not currently in progress, cannot stop!");
}
// sleep for one second, to make sure we catch the end of the test
Thread.sleep(1000);
currentCallable.stopRecording();
currentCallable = null;
return currentFuture.get();
}
class RecorderThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("VideoRecordingThread");
return thread;
}
}
}
| package com.mooo.aimmac23.node;
import java.io.File;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class VideoRecordController {
private ThreadPoolExecutor executor;
RecordVideoCallable currentCallable;
private Future<File> currentFuture;
public VideoRecordController() {
executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(5));
executor.setThreadFactory(new RecorderThreadFactory());
executor.prestartAllCoreThreads();
}
public void startRecording() {
if(currentCallable != null) {
throw new IllegalStateException("Video recording currently in progress, cannot record again");
}
currentCallable = new RecordVideoCallable();
currentFuture = executor.submit(currentCallable);
}
public File stopRecording() throws Exception {
if(currentCallable == null) {
throw new IllegalStateException("Video recording not currently in progress, cannot stop!");
}
currentCallable.stopRecording();
currentCallable = null;
return currentFuture.get();
}
class RecorderThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("VideoRecordingThread");
return thread;
}
}
}
|
Fix typo and data structure | const inquirer = require('inquirer')
const exchangers = require('../config/exchangers.json')
let exchangeSelected = ''
const prompt = new Promise((resolve, reject) => {
inquirer.prompt({
type: 'list',
name: 'exchange',
message: 'Select your favorite exchange?',
choices: Object.keys(exchangers),
validate: function (answer) {
if (answer.length < 1) {
return 'You must choose at least one exchange.'
}
return true
}
}).then((answer) => {
exchangeSelected = answer.exchange
inquirer.prompt({
type: 'checkbox',
name: 'markets',
message: 'And your favorite market?',
choices: Object.keys(exchangers[answer.exchange].markets),
validate: function (answer) {
if (answer.length < 1) {
return 'You must choose at least one market.';
}
return true
}
}).then((answer) => {
resolve({
exchange: exchangeSelected,
markets: answer.markets
})
})
})
})
module.exports = prompt
| const inquirer = require('inquirer')
const exchangers = require('../config/exchangers.json')
const prompt = new Promise((resolve, reject) => {
inquirer.prompt({
type: 'checkbox',
name: 'market',
message: 'Select your favorite market?',
choices: ['POLONIEX', 'YUNBI'],
validate: function (answer) {
if (answer.length < 1) {
return 'You must choose at least one market.'
}
return true
}
}).then((answer) => {
inquirer.prompt({
type: 'checkbox',
name: 'pairs',
message: 'And your favorite pairs?',
choices: Object.keys(exchangers.pairs),
validate: function (answer) {
if (answer.length < 1) {
return 'You must choose at least one pair.';
}
return true
}
}).then((answer) => {
resolve(answer)
})
})
})
module.exports = prompt
|
Remove method implemented in parent. | <?php
require_once 'Inquisition/admin/components/Option/Order.php';
require_once 'CME/admin/components/Option/include/CMEOptionHelper.php';
/**
* @package CME
* @copyright 2014 silverorange
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
abstract class CMEOptionOrder extends InquisitionOptionOrder
{
// {{{ protected properties
/**
* @var CMEOptionHelper
*/
protected $helper;
// }}}
// init phase
// {{{ protected function initInternal()
protected function initInternal()
{
parent::initInternal();
$this->helper = $this->getOptionHelper();
$this->helper->initInternal();
}
// }}}
// {{{ abstract protected function getOptionHelper()
abstract protected function getOptionHelper();
// }}}
// build phase
// {{{ protected function buildNavBar()
protected function buildNavBar()
{
parent::buildNavBar();
$this->helper->buildNavBar($this->navbar);
}
// }}}
}
?>
| <?php
require_once 'Inquisition/admin/components/Option/Order.php';
require_once 'CME/admin/components/Option/include/CMEOptionHelper.php';
/**
* @package CME
* @copyright 2014 silverorange
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
abstract class CMEOptionOrder extends InquisitionOptionOrder
{
// {{{ protected properties
/**
* @var CMEOptionHelper
*/
protected $helper;
// }}}
// init phase
// {{{ protected function initInternal()
protected function initInternal()
{
parent::initInternal();
$this->helper = $this->getOptionHelper();
$this->helper->initInternal();
}
// }}}
// {{{ abstract protected function getOptionHelper()
abstract protected function getOptionHelper();
// }}}
// build phase
// {{{ protected function buildForm()
protected function buildForm()
{
parent::buildForm();
$form = $this->ui->getWidget('order_form');
$form->addHiddenField('inquisition', $this->inquisition->id);
}
// }}}
// {{{ protected function buildNavBar()
protected function buildNavBar()
{
parent::buildNavBar();
$this->helper->buildNavBar($this->navbar);
}
// }}}
}
?>
|
Remove RedisCloud URL form Heroku | import os
from .base import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Sym Roe', 'lmtools@talusdesign.co.uk'),
)
MANAGERS = ADMINS
ALLOWED_HOSTS = ['.herokuapp.com']
INTERNAL_IPS = ()
# Redirect any non-HTTP request to HTTPS
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Only allow sessions when serving the site over HTTPS
SESSION_COOKIE_SECURE = True
# Only send CSRF protection cookies when serving the site over HTTPS
CSRF_COOKIE_SECURE = True
# Use the X-Request=ID HTTP Header as the request ID
LOG_REQUEST_ID_HEADER = "HTTP_X_REQUEST_ID"
import dj_database_url
DATABASES['default'] = dj_database_url.config()
DATABASES['default']['ENGINE'] = 'django_postgrespool'
EMAIL_HOST = os.environ['MAILGUN_SMTP_SERVER']
EMAIL_HOST_USER = os.environ['MAILGUN_SMTP_LOGIN']
EMAIL_HOST_PASSWORD = os.environ['MAILGUN_SMTP_PASSWORD']
EMAIL_PORT = os.environ['MAILGUN_SMTP_PORT']
EMAIL_USE_TLS = True
| import os
from .base import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Sym Roe', 'lmtools@talusdesign.co.uk'),
)
MANAGERS = ADMINS
ALLOWED_HOSTS = ['.herokuapp.com']
INTERNAL_IPS = ()
# Redirect any non-HTTP request to HTTPS
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Only allow sessions when serving the site over HTTPS
SESSION_COOKIE_SECURE = True
# Only send CSRF protection cookies when serving the site over HTTPS
CSRF_COOKIE_SECURE = True
# Use the X-Request=ID HTTP Header as the request ID
LOG_REQUEST_ID_HEADER = "HTTP_X_REQUEST_ID"
import dj_database_url
DATABASES['default'] = dj_database_url.config()
DATABASES['default']['ENGINE'] = 'django_postgrespool'
REDIS_URL = os.environ['REDISCLOUD_URL']
EMAIL_HOST = os.environ['MAILGUN_SMTP_SERVER']
EMAIL_HOST_USER = os.environ['MAILGUN_SMTP_LOGIN']
EMAIL_HOST_PASSWORD = os.environ['MAILGUN_SMTP_PASSWORD']
EMAIL_PORT = os.environ['MAILGUN_SMTP_PORT']
EMAIL_USE_TLS = True
|
Remove extra reference to karma-phantomjs-launcher plugin. | /**
* Created by Sean on 1/3/2015.
*/
module.exports = function(config) {
config.set({
basePath: '.',
frameworks: ['dart-unittest'],
files: [
{pattern: 'test/resolutionizer_test.dart', included: true},
{pattern: '**/*.dart', included: false},
{pattern: '**/*.html', included: false}
],
autoWatch: true,
captureTimeout: 20000,
browserNoActivityTimeout: 300000,
plugins: [
'karma-dart',
'karma-chrome-launcher'
],
browsers: ['Dartium']
});
}; | /**
* Created by Sean on 1/3/2015.
*/
module.exports = function(config) {
config.set({
basePath: '.',
frameworks: ['dart-unittest'],
files: [
{pattern: 'test/resolutionizer_test.dart', included: true},
{pattern: '**/*.dart', included: false},
{pattern: '**/*.html', included: false}
],
autoWatch: true,
captureTimeout: 20000,
browserNoActivityTimeout: 300000,
plugins: [
'karma-dart',
'karma-chrome-launcher',
'karma-phantomjs-launcher'
],
browsers: ['Dartium']
});
}; |
Simplify readlines() to add requirements | # coding=utf-8
from setuptools import setup, find_packages
from sii import __LIBRARY_VERSION__
with open('requirements.txt', 'r') as f:
INSTALL_REQUIRES = f.readlines()
with open('requirements-dev.txt', 'r') as f:
TESTS_REQUIRE = f.readlines()
PACKAGES_DATA = {'sii': ['data/*.xsd']}
setup(
name='sii',
description='Librería de Suministro Inmediato de Información',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
url='http://www.gisce.net',
version=__LIBRARY_VERSION__,
license='General Public Licence 2',
long_description=open('README.rst').read(),
provides=['sii'],
install_requires=INSTALL_REQUIRES,
tests_require=TESTS_REQUIRE,
packages=find_packages(exclude=['spec']),
package_data=PACKAGES_DATA
)
| # coding=utf-8
from setuptools import setup, find_packages
from sii import __LIBRARY_VERSION__
INSTALL_REQUIRES = [line for line in open('requirements.txt')]
TESTS_REQUIRE = [line for line in open('requirements-dev.txt')]
PACKAGES_DATA = {'sii': ['data/*.xsd']}
setup(
name='sii',
description='Librería de Suministro Inmediato de Información',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
url='http://www.gisce.net',
version=__LIBRARY_VERSION__,
license='General Public Licence 2',
long_description=open('README.rst').read(),
provides=['sii'],
install_requires=INSTALL_REQUIRES,
tests_require=TESTS_REQUIRE,
packages=find_packages(exclude=['spec']),
package_data=PACKAGES_DATA
)
|
Add support for shuffling the library. | console.log('loaded play.js');
var playPauseButton = function() {
return document.querySelector("button[data-id='play-pause']");
};
var currentTrackInfo = function() {
return {
song: document.getElementById('playerSongTitle').innerHTML,
artist: document.getElementById('player-artist').innerHTML,
album: document.getElementsByClassName('player-album')[0].innerHTML,
state: playPauseButton().className.indexOf('playing') === -1 ? 'paused' : 'playing'
};
};
var commands = {
play: function() {
playPauseButton().click();
},
next: function() {
document.querySelector("button[data-id='forward']").click();
},
previous: function() {
document.querySelector("button[data-id='rewind']").click();
},
shuffle: function() {
document.querySelector("li[data-type='artists']").click();
document.querySelector("button[data-id='shuffle-my-library']").click();
}
};
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(request.command);
commands[request.command]();
var response = {
track: currentTrackInfo()
};
sendResponse(response);
});
| console.log('loaded play.js');
var playPauseButton = function() {
return document.querySelector("button[data-id='play-pause']");
};
var currentTrackInfo = function() {
return {
song: document.getElementById('playerSongTitle').innerHTML,
artist: document.getElementById('player-artist').innerHTML,
album: document.getElementsByClassName('player-album')[0].innerHTML,
state: playPauseButton().className.indexOf('playing') === -1 ? 'paused' : 'playing'
};
};
var commands = {
play: function() {
playPauseButton().click();
},
next: function() {
document.querySelector("button[data-id='forward']").click();
},
previous: function() {
document.querySelector("button[data-id='rewind']").click();
}
};
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(request.command);
commands[request.command]();
var response = {
track: currentTrackInfo()
};
sendResponse(response);
}); |
Add dirname RegExps to REPL context | 'use strict';
var NS = {};
// MODULES //
var getKeys = require( 'object-keys' ).shim();
NS.RE_EOL = require( '@stdlib/regexp/eol' );
NS.RE_DIRNAME = require( '@stdlib/regexp/dirname' );
NS.RE_DIRNAME_POSIX = require( '@stdlib/regexp/dirname-posix' );
NS.RE_DIRNAME_WINDOWS = require( '@stdlib/regexp/dirname-windows' );
NS.RE_EXTNAME = require( '@stdlib/regexp/extname' );
NS.RE_EXTNAME_POSIX = require( '@stdlib/regexp/extname-posix' );
NS.RE_EXTNAME_WINDOWS = require( '@stdlib/regexp/extname-windows' );
NS.RE_FUNCTION_NAME = require( '@stdlib/regexp/function-name' );
// VARIABLES //
var KEYS = getKeys( NS );
// BIND //
/**
* Binds functions to a REPL namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* bind( ns );
* // returns <input_namespace>
*/
function bind( ns ) {
var key;
var i;
for ( i = 0; i < KEYS.length; i++ ) {
key = KEYS[ i ];
ns[ key ] = NS[ key ];
}
return ns;
} // end FUNCTION bind()
// EXPORTS //
module.exports = bind;
| 'use strict';
var NS = {};
// MODULES //
var getKeys = require( 'object-keys' ).shim();
NS.RE_EOL = require( '@stdlib/regexp/eol' );
NS.RE_EXTNAME = require( '@stdlib/regexp/extname' );
NS.RE_EXTNAME_POSIX = require( '@stdlib/regexp/extname-posix' );
NS.RE_EXTNAME_WINDOWS = require( '@stdlib/regexp/extname-windows' );
NS.RE_FUNCTION_NAME = require( '@stdlib/regexp/function-name' );
// VARIABLES //
var KEYS = getKeys( NS );
// BIND //
/**
* Binds functions to a REPL namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* bind( ns );
* // returns <input_namespace>
*/
function bind( ns ) {
var key;
var i;
for ( i = 0; i < KEYS.length; i++ ) {
key = KEYS[ i ];
ns[ key ] = NS[ key ];
}
return ns;
} // end FUNCTION bind()
// EXPORTS //
module.exports = bind;
|
Check for onchange before try executing to avoid errors | import m from 'mithril';
import dropdown from './dropdown';
const filterDropdown = {
view(ctrl, args) {
const wrapper_c = args.wrapper_class || '.w-col.w-col-3.w-col-small-6';
return m(wrapper_c, [
m(`label.fontsize-smaller[for="${args.index}"]`,
(args.custom_label ? m.component(args.custom_label[0], args.custom_label[1]) : args.label)),
m.component(dropdown, {
id: args.index,
onchange: _.isFunction(args.onchange) ? args.onchange : () => {},
classes: '.w-select.text-field.positive',
valueProp: args.vm,
options: args.options
})
]);
}
};
export default filterDropdown;
| import m from 'mithril';
import dropdown from './dropdown';
const filterDropdown = {
view(ctrl, args) {
const wrapper_c = args.wrapper_class || '.w-col.w-col-3.w-col-small-6';
return m(wrapper_c, [
m(`label.fontsize-smaller[for="${args.index}"]`,
(args.custom_label ? m.component(args.custom_label[0], args.custom_label[1]) : args.label)),
m.component(dropdown, {
id: args.index,
onchange: args.onchange,
classes: '.w-select.text-field.positive',
valueProp: args.vm,
options: args.options
})
]);
}
};
export default filterDropdown;
|
Use shed.networkFirst() for /api/ traffic even if there is no X-Cache-Only header set. | function serveFromCacheOrNetwork(request) {
if (request.headers.get('X-Cache-Only') == 'true') {
return shed.cacheOnly(request).then(function(response) {
if (response) {
return response;
} else {
return new Response('', {
status: 204,
statusText: 'No cached content available.'
});
}
});
} else {
// If this is a request with either 'X-Cache-Only: false' or just a normal request without
// it set, then perform a HTTP fetch and cache the result.
return shed.networkFirst(request);
}
}
// TODO: /temporary_api/ can be removed once /api/ is available.
shed.router.get('/(.+)temporary_api/(.+)', serveFromCacheOrNetwork);
shed.router.get('/(.+)api/(.+)', serveFromCacheOrNetwork);
| function serveFromCacheOrNetwork(request) {
if (request.headers.get('X-Cache-Only') == 'true') {
return shed.cacheOnly(request).then(function(response) {
if (response) {
return response;
} else {
return new Response('', {
status: 204,
statusText: 'No cached content available.'
});
}
});
}
if (request.headers.get('X-Cache-Only') == 'false') {
return shed.networkFirst(request);
}
return fetch(request);
}
// TODO: /temporary_api/ can be removed once /api/ is available.
shed.router.get('/(.+)temporary_api/(.+)', serveFromCacheOrNetwork);
shed.router.get('/(.+)api/(.+)', serveFromCacheOrNetwork);
|
Rename command queue:worker -> queue:work | <?php
namespace Spark\Core\Command;
use Silex\Application;
use Spark\Core\ApplicationAware;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Kue\Worker;
use Kue\Queue;
class QueueWorker extends \Kue\Command\WorkCommand
{
protected $silexApplication;
function setSilexApplication(Application $app)
{
$this->silexApplication = $app;
}
protected function configure()
{
parent::configure();
$this->setName('queue:work');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->silexApplication->boot();
return parent::execute($input, $output);
}
protected function setupWorker(Worker $worker)
{
parent::setupWorker($worker);
$app = $this->silexApplication;
$worker->on('init', function($job) use ($app) {
if ($job instanceof ApplicationAware) {
$job->setApplication($app);
}
});
}
}
| <?php
namespace Spark\Core\Command;
use Silex\Application;
use Spark\Core\ApplicationAware;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Kue\Worker;
use Kue\Queue;
class QueueWorker extends \Kue\Command\Worker
{
protected $silexApplication;
function setSilexApplication(Application $app)
{
$this->silexApplication = $app;
}
protected function configure()
{
parent::configure();
$this->setName('queue:worker');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->silexApplication->boot();
return parent::execute($input, $output);
}
protected function setupWorker(Worker $worker)
{
parent::setupWorker($worker);
$app = $this->silexApplication;
$worker->on('init', function($job) use ($app) {
if ($job instanceof ApplicationAware) {
$job->setApplication($app);
}
});
}
}
|
Fix bug where global defer stats object was being overwritten | package web
import (
"errors"
"fmt"
"log"
"os"
"github.com/deferpanic/deferclient/deferstats"
)
var (
dfs *deferstats.Client
)
// NewLogger configures defer panic error and starts capturing stats.
// It looks for DEFERPANIC_KEY,
// DEVERPANIC_ENVIRONMENT and DEFERPANIC_APPGROUP environment vars
func NewLogger() {
dfs = deferstats.NewClient(os.Getenv("DEFERPANIC_API_KEY"))
dfs.Setenvironment(os.Getenv("DEFERPANIC_ENVIRONMENT"))
dfs.SetappGroup(os.Getenv("DEFERPANIC_APPGROUP"))
go dfs.CaptureStats()
}
func logError(msg string) {
err := errors.New(msg)
if err != nil {
dfs.Wrap(err)
log.Println(err)
}
}
// LogError passes the error to deferpanic
// and prints the error message to stdout
func LogError(e error) {
logError(e.Error())
}
// LogErrorf accepts a format string and arguments
// It creates a new error, logs with deferpanic and
// prints the error to stdout
func LogErrorf(format string, a ...interface{}) {
LogError(fmt.Errorf(format, a...))
}
| package web
import (
"errors"
"fmt"
"log"
"os"
"github.com/deferpanic/deferclient/deferstats"
)
var (
dfs *deferstats.Client
)
// NewLogger configures defer panic error and starts capturing stats.
// It looks for DEFERPANIC_KEY,
// DEVERPANIC_ENVIRONMENT and DEFERPANIC_APPGROUP environment vars
func NewLogger() {
dfs := deferstats.NewClient(os.Getenv("DEFERPANIC_KEY"))
dfs.Setenvironment(os.Getenv("DEFERPANIC_ENVIRONMENT"))
dfs.SetappGroup(os.Getenv("DEFERPANIC_APPGROUP"))
go dfs.CaptureStats()
}
func logError(msg string) {
err := errors.New(msg)
if err != nil {
dfs.Wrap(err)
log.Println(err)
}
}
// LogError passes the error to deferpanic
// and prints the error message to stdout
func LogError(e error) {
logError(e.Error())
}
// LogErrorf accepts a format string and arguments
// It creates a new error, logs with deferpanic and
// prints the error to stdout
func LogErrorf(format string, a ...interface{}) {
LogError(fmt.Errorf(format, a...))
}
|
Set Live page as a webpack chunk | import Vue from "vue";
import Router from "vue-router";
import Search from "./views/Search.vue";
// import Live from "@/views/Live.vue";
// import Stats from '@/views/Stats.vue';
Vue.use(Router);
export default new Router({
mode: "history",
base: process.env.BASE_URL,
linkActiveClass: "is-active",
routes: [
{
path: "/",
name: "search",
component: Search,
},
{
path: "/live",
name: "live",
component: () =>
import(/* webpackChunkName: "live" */ "./views/Live.vue"),
},
{
path: "/stats",
name: "stats",
component: () =>
import(/* webpackChunkName: "stats" */ "./views/Stats.vue"),
},
],
});
| import Vue from "vue";
import Router from "vue-router";
import Search from "./views/Search.vue";
import Live from "@/views/Live.vue";
// import Stats from '@/views/Stats.vue'
Vue.use(Router);
export default new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "search",
component: Search,
},
{
path: "/live",
name: "live",
component: Live,
},
{
path: "/stats",
name: "stats",
component: () =>
import(/* webpackChunkName: "stats" */ "./views/Stats.vue"),
},
],
});
|
Fix the mistaken use of attend in the UNIQUE clause. | <?php
$DATABASE_UNINSTALL = array(
"drop table if exists {$CFG->dbprefix}context_map"
);
$DATABASE_INSTALL = array(
array( "{$CFG->dbprefix}context_map",
"create table {$CFG->dbprefix}context_map (
context_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
lat FLOAT,
lng FLOAT,
color INTEGER,
updated_at DATETIME NOT NULL,
CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE(context_id, user_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8")
);
| <?php
$DATABASE_UNINSTALL = array(
"drop table if exists {$CFG->dbprefix}context_map"
);
$DATABASE_INSTALL = array(
array( "{$CFG->dbprefix}context_map",
"create table {$CFG->dbprefix}context_map (
context_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
lat FLOAT,
lng FLOAT,
color INTEGER,
updated_at DATETIME NOT NULL,
CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE(context_id, user_id, attend)
) ENGINE = InnoDB DEFAULT CHARSET=utf8")
);
|
Fix decomposition of camera quaternions | import { quat_create, quat_copy, quat_set, quat_normalize, quat_multiply } from './quat';
var pitchQuat = quat_create();
var yawQuat = quat_create();
export function controls_create(object) {
var controls = {
object: object,
speed: 1,
turnRate: Math.PI / 4,
sensitivity: 0.002,
enabled: false,
onMouseMove: function(event) {
if (!controls.enabled) {
return;
}
var movementX = event.movementX || event.mozMovementX || 0;
var movementY = event.movementY || event.mozMovementY || 0;
var pitch = -movementY * controls.sensitivity;
var yaw = -movementX * controls.sensitivity;
quat_normalize(quat_set(pitchQuat, pitch, 0, 0, 1));
quat_normalize(quat_set(yawQuat, 0, yaw, 0, 1));
// pitch * object * yaw
quat_multiply(object.quaternion, pitchQuat);
quat_multiply(yawQuat, object.quaternion);
quat_copy(object.quaternion, yawQuat);
},
};
document.addEventListener('mousemove', controls.onMouseMove);
return controls;
}
export function controls_dispose(controls) {
document.removeEventListener('mousemove', controls.onMouseMove);
}
| import { quat_create, quat_set, quat_normalize, quat_multiply } from './quat';
var quat = quat_create();
export function controls_create(object) {
var controls = {
object: object,
speed: 1,
turnRate: Math.PI / 4,
sensitivity: 0.002,
enabled: false,
onMouseMove: function(event) {
if (!controls.enabled) {
return;
}
var movementX = event.movementX || event.mozMovementX || 0;
var movementY = event.movementY || event.mozMovementY || 0;
var pitch = -movementY * controls.sensitivity;
var yaw = -movementX * controls.sensitivity;
quat_normalize(quat_set(quat, pitch, yaw, 0, 1));
quat_multiply(object.quaternion, quat);
},
};
document.addEventListener('mousemove', controls.onMouseMove);
return controls;
}
export function controls_dispose(controls) {
document.removeEventListener('mousemove', controls.onMouseMove);
}
|
Change version number to reflect recent changes
Bumping a major version to reflect the interface and extension
changes which have occurred.
Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com> | from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
with open('requirements.txt') as f:
requirements = f.readlines()
setup(
name='pycc',
version='2.0.0',
url='https://github.com/kevinconway/pycc',
license=license,
description='Python code optimizer.',
author='Kevin Conway',
author_email='kevinjacobconway@gmail.com',
long_description=readme,
classifiers=[],
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
requires=requirements,
entry_points={
'console_scripts': [
'pycc-transform = pycc.cli.transform:main',
'pycc-compile = pycc.cli.compile:main',
],
'pycc.optimizers': [
'pycc_constant_inliner = pycc.cli.extensions.constants:ConstantInlineExtension',
],
},
)
| from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
with open('requirements.txt') as f:
requirements = f.readlines()
setup(
name='pycc',
version='1.0.0',
url='https://github.com/kevinconway/pycc',
license=license,
description='Python code optimizer.',
author='Kevin Conway',
author_email='kevinjacobconway@gmail.com',
long_description=readme,
classifiers=[],
packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
requires=requirements,
entry_points={
'console_scripts': [
'pycc-transform = pycc.cli.transform:main',
'pycc-compile = pycc.cli.compile:main',
],
'pycc.optimizers': [
'pycc_constant_inliner = pycc.cli.extensions.constants:ConstantInlineExtension',
],
},
)
|
Use smaller data sets for Kittydar. | import sys, socket, time, logging
import shlex, subprocess
from hdfs import *
logging.basicConfig()
if len(sys.argv) < 4:
print "usage: napper_kittydar <job name> <worker ID> <executable>"
sys.exit(1)
job_name = sys.argv[1]
worker_id = int(sys.argv[2])
kittydar_path = " ".join(sys.argv[3:])
# fetch inputs from HDFS if necessary
hdfs_fetch_file("/input/kittydar_splits30/CAT_%02d" % (worker_id), os.environ['FLAGS_task_data_dir'])
# execute program
command = "nodejs %s --dir %s/CAT_%02d/" % (kittydar_path, os.environ['FLAGS_task_data_dir'], worker_id)
print "RUNNING: %s" % (command)
subprocess.call(shlex.split(command))
print "Deleting scratch data..."
del_command = "rm -rf %s" % (os.environ['FLAGS_task_data_dir'])
subprocess.call(shlex.split(del_command))
print "All done -- goodbye from Napper!"
sys.exit(0)
| import sys, socket, time, logging
import shlex, subprocess
from hdfs import *
logging.basicConfig()
if len(sys.argv) < 4:
print "usage: napper_kittydar <job name> <worker ID> <executable>"
sys.exit(1)
job_name = sys.argv[1]
worker_id = int(sys.argv[2])
kittydar_path = " ".join(sys.argv[3:])
# fetch inputs from HDFS if necessary
hdfs_fetch_file("/input/kittys/CAT_0%d" % (worker_id), os.environ['FLAGS_task_data_dir'])
# execute program
command = "nodejs %s --dir %s/CAT_0%d/" % (kittydar_path, os.environ['FLAGS_task_data_dir'], worker_id)
print "RUNNING: %s" % (command)
subprocess.call(shlex.split(command))
print "Deleting scratch data..."
del_command = "rm -rf %s" % (os.environ['FLAGS_task_data_dir'])
subprocess.call(shlex.split(del_command))
print "All done -- goodbye from Napper!"
sys.exit(0)
|
Document 3.6+ support in classifiers and python_requires | #!/usr/bin/env python
from setuptools import setup
import argparse_addons
setup(name='argparse_addons',
version=argparse_addons.__version__,
description=('Additional argparse types and actions.'),
long_description=open('README.rst', 'r').read(),
author='Erik Moqvist',
author_email='erik.moqvist@gmail.com',
license='MIT',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
keywords=['argparse'],
url='https://github.com/eerimoq/argparse_addons',
py_modules=['argparse_addons'],
python_requires=['>=3.6'],
install_requires=[
],
test_suite="tests")
| #!/usr/bin/env python
from setuptools import setup
import argparse_addons
setup(name='argparse_addons',
version=argparse_addons.__version__,
description=('Additional argparse types and actions.'),
long_description=open('README.rst', 'r').read(),
author='Erik Moqvist',
author_email='erik.moqvist@gmail.com',
license='MIT',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
keywords=['argparse'],
url='https://github.com/eerimoq/argparse_addons',
py_modules=['argparse_addons'],
install_requires=[
],
test_suite="tests")
|
Fix formatting of invitation e-mail slightly. | <?php
require_once("database.php");
require_once("templating.php");
if(!$logged_in) {
$smarty->display("login.tpl");
die();
}
if(isset($_POST['invite'])) {
$errors = "";
$email = $_POST['email'];
if(empty($email)) {
$errors .= "You must enter an e-mail address.<br />";
}
if(empty($errors)) {
$code = md5(md5($username) . time());
$mdb2->query("INSERT INTO Invitations (inviter, code) VALUES ("
. $mdb2->quote($username, "text") . ", "
. $mdb2->quote($code, "text") . ")");
$url = $base_url . "/register.php?authcode=" . $code;
$headers = "From: Libre.fm Invitations <invitations@libre.fm>";
mail($email, "Libre.fm Invitation", "Hi!\n\nClearly " . $username . " really likes you, because they've sent you an inivitation to join http://libre.fm\n\nJust visit " . $url . " to sign up, all the cool kids are doing it.\n", $headers);
$smarty->assign("sent", true);
} else {
$smarty->assign("errors", $errors);
}
}
$smarty->display("invite.tpl");
?>
| <?php
require_once("database.php");
require_once("templating.php");
if(!$logged_in) {
$smarty->display("login.tpl");
die();
}
if(isset($_POST['invite'])) {
$errors = "";
$email = $_POST['email'];
if(empty($email)) {
$errors .= "You must enter an e-mail address.<br />";
}
if(empty($errors)) {
$code = md5(md5($username) . time());
$mdb2->query("INSERT INTO Invitations (inviter, code) VALUES ("
. $mdb2->quote($username, "text") . ", "
. $mdb2->quote($code, "text") . ")");
$url = $base_url . "/register.php?authcode=" . $code;
$headers = "From: Libre.fm Invitations <invitations@libre.fm>";
mail($email, "Libre.fm Invitation", "Hi!\n\nClearly " . $username . " really likes you, because they've sent you an inivitation to join http://libre.fm\n Just visit " . $url . " to sign up, all the cool kids are doing it.\n", $headers);
$smarty->assign("sent", true);
} else {
$smarty->assign("errors", $errors);
}
}
$smarty->display("invite.tpl");
?>
|
Remove completed lines evaluator since it lowers overall performance | package com.srs.tetris.bob.evaluator;
/**
* The best known combination of evaluators.
*/
public class SapientEvaluator extends CompositeEvaluator {
private static final double HEIGHT_WEIGHT = -1.0;
private static final double AVERAGE_HEIGHT_WEIGHT = -1.0;
//private static final double COMPLETED_LINES_WEIGHT = 2.0;
private static final double HOLE_WEIGHT = -10.0;
private static final double HOLE_COVER_WEIGHT = -2.0;
private static final double NARROW_GAP_WEIGHT = -1.0;
public SapientEvaluator() {
super(
new WeightedEvaluator(new HeightEvaluator(), HEIGHT_WEIGHT),
new WeightedEvaluator(new AverageHeightEvaluator(), AVERAGE_HEIGHT_WEIGHT),
//new WeightedEvaluator(new CompletedLinesEvaluator(), COMPLETED_LINES_WEIGHT),
new HolesEvaluator(HOLE_WEIGHT, HOLE_COVER_WEIGHT),
new WeightedEvaluator(new NarrowGapEvaluator(), NARROW_GAP_WEIGHT)
);
}
}
| package com.srs.tetris.bob.evaluator;
/**
* The best known combination of evaluators.
*/
public class SapientEvaluator extends CompositeEvaluator {
private static final double HEIGHT_WEIGHT = -1.0;
private static final double AVERAGE_HEIGHT_WEIGHT = -1.0;
private static final double COMPLETED_LINES_WEIGHT = 2.0;
private static final double HOLE_WEIGHT = -10.0;
private static final double HOLE_COVER_WEIGHT = -2.0;
private static final double NARROW_GAP_WEIGHT = -1.0;
public SapientEvaluator() {
super(
new WeightedEvaluator(new HeightEvaluator(), HEIGHT_WEIGHT),
new WeightedEvaluator(new AverageHeightEvaluator(), AVERAGE_HEIGHT_WEIGHT),
new WeightedEvaluator(new CompletedLinesEvaluator(), COMPLETED_LINES_WEIGHT),
new HolesEvaluator(HOLE_WEIGHT, HOLE_COVER_WEIGHT),
new WeightedEvaluator(new NarrowGapEvaluator(), NARROW_GAP_WEIGHT)
);
}
}
|
Add issue button on issues page added | @extends('layouts.project')
@section('styles')
<link rel="stylesheet" href="{{ asset('css/bugtracker/issue.css') }}" />
@endsection
@section('scripts')
<script src="{{ asset('js/bugtracker/issues.js') }}"></script>
@endsection
@section('project-content')
{!! Breadcrumbs::render('issues', $project) !!}
<div class="issue-controls pull-right">
@if(!app('request')->input('closed_visible'))
<a class="btn btn-success" href="{{ route('project.issues', ['project' => $project, 'closed_visible'=>true]) }}"><span class="glyphicon glyphicon-eye-open"></span> Show closed</a>
@else
<a class="btn btn-danger" href="{{ route('project.issues', ['project' => $project, 'closed_visible'=>false]) }}"><span class="glyphicon glyphicon-eye-close"></span> Hide closed</a>
@endif
</div>
@if(!$issues->isEmpty())
<div class="issues-block">
@include('bugtracker.project.partials.issues-block')
</div>
@else
<div class="alert alert-info">There is no issues yet, add one!</div>
@endif
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#create-issue-modal">@lang('projects.issue_create')</button>
<div>
{!! View::make('bugtracker.project.partials.issue_create_modal', ['project'=>$project])->render() !!}
</div>
@endsection
| @extends('layouts.project')
@section('styles')
<link rel="stylesheet" href="{{ asset('css/bugtracker/issue.css') }}" />
@endsection
@section('scripts')
<script src="{{ asset('js/bugtracker/issues.js') }}"></script>
@endsection
@section('project-content')
{!! Breadcrumbs::render('issues', $project) !!}
<div class="issue-controls pull-right">
@if(!app('request')->input('closed_visible'))
<a class="btn btn-success" href="{{ route('project.issues', ['project' => $project, 'closed_visible'=>true]) }}"><span class="glyphicon glyphicon-eye-open"></span> Show closed</a>
@else
<a class="btn btn-danger" href="{{ route('project.issues', ['project' => $project, 'closed_visible'=>false]) }}"><span class="glyphicon glyphicon-eye-close"></span> Hide closed</a>
@endif
</div>
@if(!$issues->isEmpty())
<div class="issues-block">
@include('bugtracker.project.partials.issues-block')
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#create-issue-modal">@lang('projects.issue_create')</button>
</div>
@else
<div class="alert alert-info">There is no issues yet, add one!</div>
@endif
<div>
{!! View::make('bugtracker.project.partials.issue_create_modal', ['project'=>$project])->render() !!}
</div>
@endsection
|
Add currency to cash register selectors | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { createSelector } from 'reselect';
import { pageStateSelector } from './pageSelectors';
import currency from '../localization/currency';
/**
* Derives current balance from cash register transactions.
* @return {Number}
*/
export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data);
export const selectReceipts = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'receipt')
);
export const selectPayments = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'payment')
);
export const selectReceiptsTotal = createSelector([selectReceipts], receipts =>
receipts.reduce((acc, { total }) => acc.add(total), currency(0))
);
export const selectPaymentsTotal = createSelector([selectPayments], payments =>
payments.reduce((acc, { total }) => acc.add(total), currency(0))
);
export const selectBalance = createSelector(
[selectReceiptsTotal, selectPaymentsTotal],
(receiptsTotal, paymentsTotal) => receiptsTotal.subtract(paymentsTotal).format()
);
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { createSelector } from 'reselect';
import { pageStateSelector } from './pageSelectors';
import currency from '../localization/currency';
/**
* Derives current balance from cash register transactions.
* @return {Number}
*/
export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data);
export const selectReceipts = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'receipt')
);
export const selectPayments = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'payment')
);
export const selectReceiptsTotal = createSelector([selectReceipts], receipts =>
receipts.reduce((acc, { total }) => acc + total, 0)
);
export const selectPaymentsTotal = createSelector([selectPayments], payments =>
payments.reduce((acc, { total }) => acc + total, 0)
);
export const selectBalance = createSelector(
[selectReceiptsTotal, selectPaymentsTotal],
(receiptsTotal, paymentsTotal) => currency(receiptsTotal - paymentsTotal).format(false)
);
|
Remove waiting from PDF page component test | import Vue from 'vue';
import pdfjsLib from 'vendor/pdf';
import workerSrc from 'vendor/pdf.worker.min';
import PageComponent from '~/pdf/page/index.vue';
import mountComponent from 'spec/helpers/vue_mount_component_helper';
import testPDF from 'spec/fixtures/blob/pdf/test.pdf';
describe('Page component', () => {
const Component = Vue.extend(PageComponent);
let vm;
let testPage;
beforeEach(done => {
pdfjsLib.PDFJS.workerSrc = workerSrc;
pdfjsLib
.getDocument(testPDF)
.then(pdf => pdf.getPage(1))
.then(page => {
testPage = page;
})
.then(done)
.catch(done.fail);
});
afterEach(() => {
vm.$destroy();
});
it('renders the page when mounting', done => {
const promise = Promise.resolve();
spyOn(testPage, 'render').and.callFake(() => promise);
vm = mountComponent(Component, {
page: testPage,
number: 1,
});
expect(vm.rendering).toBe(true);
promise
.then(() => {
expect(testPage.render).toHaveBeenCalledWith(vm.renderContext);
expect(vm.rendering).toBe(false);
})
.then(done)
.catch(done.fail);
});
});
| import Vue from 'vue';
import pdfjsLib from 'vendor/pdf';
import workerSrc from 'vendor/pdf.worker.min';
import PageComponent from '~/pdf/page/index.vue';
import testPDF from '../fixtures/blob/pdf/test.pdf';
const Component = Vue.extend(PageComponent);
describe('Page component', () => {
let vm;
let testPage;
pdfjsLib.PDFJS.workerSrc = workerSrc;
const checkRendered = (done) => {
if (vm.rendering) {
setTimeout(() => {
checkRendered(done);
}, 100);
} else {
done();
}
};
beforeEach((done) => {
pdfjsLib.getDocument(testPDF)
.then(pdf => pdf.getPage(1))
.then((page) => {
testPage = page;
done();
})
.catch((error) => {
done.fail(error);
});
});
describe('render', () => {
beforeEach((done) => {
vm = new Component({
propsData: {
page: testPage,
number: 1,
},
});
vm.$mount();
checkRendered(done);
});
it('renders first page', () => {
expect(vm.$el.tagName).toBeDefined();
});
});
});
|
Add fingerprint consistency for Complexity issues | <?php
namespace PHPMD;
class Fingerprint
{
const OVERRIDE_RULES = [
"CyclomaticComplexity",
"Design/LongClass",
"Design/LongMethod",
"Design/LongParameterList",
"Design/NpathComplexity",
"Design/NumberOfChildren",
"Design/TooManyFields",
"Design/TooManyMethods",
"Design/TooManyPublicMethods",
"Design/WeightedMethodCount",
"ExcessivePublicCount",
];
private $name;
private $path;
private $rule;
public function __construct($path, $rule, $name)
{
$this->path = $path;
$this->rule = $rule;
$this->name = $name;
}
public function compute()
{
$fingerprint = null;
if (in_array($this->rule, self::OVERRIDE_RULES)) {
$fingerprint = md5($this->path . $this->rule . $this->name);
}
return $fingerprint;
}
}
| <?php
namespace PHPMD;
class Fingerprint
{
const OVERRIDE_RULES = [
"CyclomaticComplexity",
"Design/LongClass",
"Design/LongMethod",
];
private $name;
private $path;
private $rule;
public function __construct($path, $rule, $name)
{
$this->path = $path;
$this->rule = $rule;
$this->name = $name;
}
public function compute()
{
$fingerprint = null;
if (in_array($this->rule, self::OVERRIDE_RULES)) {
$fingerprint = md5($this->path . $this->rule . $this->name);
}
return $fingerprint;
}
}
|
Add first trip details as well | import emission.core.get_database as edb
for ue in edb.get_uuid_db().find():
trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"})
location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "background/location"})
first_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", 1).limit(1))
first_trip_time = first_trip[0]["data"]["end_fmt_time"] if len(first_trip) > 0 else None
last_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", -1).limit(1))
last_trip_time = last_trip[0]["data"]["end_fmt_time"] if len(last_trip) > 0 else None
print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, first trip = {first_trip_time}, last trip = {last_trip_time}")
| import emission.core.get_database as edb
for ue in edb.get_uuid_db().find():
trip_count = edb.get_analysis_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"})
location_count = edb.get_timeseries_db().count_documents({"user_id": ue["uuid"], "metadata.key": "background/location"})
last_trip = list(edb.get_analysis_timeseries_db().find({"user_id": ue["uuid"], "metadata.key": "analysis/confirmed_trip"}).sort("data.end_ts", -1).limit(1))
last_trip_time = last_trip[0]["data"]["end_fmt_time"] if len(last_trip) > 0 else None
print(f"For {ue['user_email']}: Trip count = {trip_count}, location count = {location_count}, last trip = {last_trip_time}")
|
refactor: Add service to retrieve list of team for a user | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.repository.api;
import io.gravitee.repository.model.Member;
import io.gravitee.repository.model.Team;
import io.gravitee.repository.model.TeamRole;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface TeamMembershipRepository {
void addMember(String teamName, String username, TeamRole role);
void updateMember(String teamName, String username, TeamRole role);
void deleteMember(String teamName, String username);
Set<Member> listMembers(String teamName);
/**
* List {@link Team} where the user is a member.
*
* @param username The name used to identify a user.
* @return List of {@link Team}
*/
Set<Team> findByUser(String username);
}
| /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.repository.api;
import io.gravitee.repository.model.Member;
import io.gravitee.repository.model.Team;
import io.gravitee.repository.model.TeamRole;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface TeamMembershipRepository {
void addMember(String teamName, String username, TeamRole role);
void updateMember(String teamName, String username, TeamRole role);
void deleteMember(String teamName, String username);
Set<Member> listMembers(String teamName);
/**
* List {@link Team} where the user is a member.
*
* @param username The name used to identify a user.
* @return List of {@link Team}
*/
Set<Team> findByUser(String username);
}
|
Add new event type for INVOICE_NOTIFICATION | /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning 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.killbill.billing.notification.plugin.api;
/**
* The enum {@code ExtBusEventType} represents the user visible bus event types.
*/
public enum ExtBusEventType {
ACCOUNT_CREATION,
ACCOUNT_CHANGE,
SUBSCRIPTION_CREATION,
SUBSCRIPTION_PHASE,
SUBSCRIPTION_CHANGE,
SUBSCRIPTION_CANCEL,
SUBSCRIPTION_UNCANCEL,
BUNDLE_PAUSE,
BUNDLE_RESUME,
OVERDUE_CHANGE,
INVOICE_CREATION,
INVOICE_ADJUSTMENT,
INVOICE_NOTIFICATION,
PAYMENT_SUCCESS,
PAYMENT_FAILED,
TAG_CREATION,
TAG_DELETION,
CUSTOM_FIELD_CREATION,
CUSTOM_FIELD_DELETION,
TENANT_CONFIG_CHANGE,
TENANT_CONFIG_DELETION;
}
| /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning 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.killbill.billing.notification.plugin.api;
/**
* The enum {@code ExtBusEventType} represents the user visible bus event types.
*/
public enum ExtBusEventType {
ACCOUNT_CREATION,
ACCOUNT_CHANGE,
SUBSCRIPTION_CREATION,
SUBSCRIPTION_PHASE,
SUBSCRIPTION_CHANGE,
SUBSCRIPTION_CANCEL,
SUBSCRIPTION_UNCANCEL,
BUNDLE_PAUSE,
BUNDLE_RESUME,
OVERDUE_CHANGE,
INVOICE_CREATION,
INVOICE_ADJUSTMENT,
PAYMENT_SUCCESS,
PAYMENT_FAILED,
TAG_CREATION,
TAG_DELETION,
CUSTOM_FIELD_CREATION,
CUSTOM_FIELD_DELETION,
TENANT_CONFIG_CHANGE,
TENANT_CONFIG_DELETION;
}
|
Test suite should pass even if example dependencies are not present | import glob
from libmproxy import utils, script
from libmproxy.proxy import config
import tservers
def test_load_scripts():
example_dir = utils.Data("libmproxy").path("../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
if "har_extractor" in f:
f += " -"
if "iframe_injector" in f:
f += " foo" # one argument required
if "modify_response_body" in f:
f += " foo bar" # two arguments required
try:
s = script.Script(f, tmaster) # Loads the script file.
except Exception, v:
if not "ImportError" in str(v):
raise
else:
s.unload()
| import glob
from libmproxy import utils, script
from libmproxy.proxy import config
import tservers
def test_load_scripts():
example_dir = utils.Data("libmproxy").path("../examples")
scripts = glob.glob("%s/*.py" % example_dir)
tmaster = tservers.TestMaster(config.ProxyConfig())
for f in scripts:
if "har_extractor" in f:
f += " -"
if "iframe_injector" in f:
f += " foo" # one argument required
if "modify_response_body" in f:
f += " foo bar" # two arguments required
s = script.Script(f, tmaster) # Loads the script file.
s.unload() |
Add capitalize-first function to String | /* FILE string.js */
(function () {
this.sparks.string = {};
var str = sparks.string;
str.strip = function (s) {
s = s.replace(/\s*([^\s]*)\s*/, '$1');
return s;
};
// Remove a dot in the string, and then remove 0's on both sides
// e.g. '20100' => '201', '0.0020440' => '2044'
str.stripZerosAndDots = function (s) {
s = s.replace('.', '');
s = s.replace(/0*([^0].*)/, '$1');
s = s.replace(/(.*[^0])0*/, '$1');
return s;
};
str.stripZeros = function (s) {
s = s.replace(/0*([^0].*)/, '$1');
s = s.replace(/(.*[^0])0*/, '$1');
return s;
};
String.prototype.capFirst = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
})();
| /* FILE string.js */
(function () {
this.sparks.string = {};
var str = sparks.string;
str.strip = function (s) {
s = s.replace(/\s*([^\s]*)\s*/, '$1');
return s;
};
// Remove a dot in the string, and then remove 0's on both sides
// e.g. '20100' => '201', '0.0020440' => '2044'
str.stripZerosAndDots = function (s) {
s = s.replace('.', '');
s = s.replace(/0*([^0].*)/, '$1');
s = s.replace(/(.*[^0])0*/, '$1');
return s;
};
str.stripZeros = function (s) {
s = s.replace(/0*([^0].*)/, '$1');
s = s.replace(/(.*[^0])0*/, '$1');
return s;
};
})();
|
Clean bower js files now since we will be copying these from the main repo | var del = require('del');
var _ = require('lodash');
function clean(target, done) {
var dir = './' + target;
var deleteList = [dir + '/*'];
deleteList = deleteList.concat(getPreservedFiles(dir));
return del(deleteList, done);
}
var preservedFiles = [
'web.config',
];
function getPreservedFiles(directory) {
return _.map(preservedFiles, function(file) {
return '!' + directory + '/' + file;
});
}
module.exports = clean;
var defaults = require('./defaults');
module.exports.config = function(gulp) {
gulp.task('clean', ['clean.debug']);
gulp.task('clean.debug', function (done) {
return clean(defaults.debugFolder, done);
});
gulp.task('clean.release', function (done) {
return clean(defaults.releaseFolder, done);
});
};
| var del = require('del');
var _ = require('lodash');
function clean(target, done) {
var dir = './' + target;
var deleteList = [dir + '/*'];
deleteList = deleteList.concat(getPreservedFiles(dir));
return del(deleteList, done);
}
var preservedFiles = [
'web.config',
'bower.json',
];
function getPreservedFiles(directory) {
return _.map(preservedFiles, function(file) {
return '!' + directory + '/' + file;
});
}
module.exports = clean;
var defaults = require('./defaults');
module.exports.config = function(gulp) {
gulp.task('clean', ['clean.debug']);
gulp.task('clean.debug', function (done) {
return clean(defaults.debugFolder, done);
});
gulp.task('clean.release', function (done) {
return clean(defaults.releaseFolder, done);
});
};
|
Add match references {1}, {2} in messages | /**
* Terminal Module for the Cloud9
*
* @copyright 2013, Ajax.org B.V.
*/
define(function(require, exports, module) {
"use strict";
var MessageHandler = function(messageMatchers, messageView) {
this.messageMatchers = messageMatchers;
this.messageView = messageView;
};
var proto = MessageHandler.prototype;
proto.handleMessage = function(data, tab) {
this.messageMatchers.forEach(function(trigger) {
var matches = trigger.pattern.exec(data);
if (matches !== null) {
var message = trigger.message;
matches.map(function(value, key) {
message = message.replace("{" + key + "}", value);
});
this.messageView.show(message, trigger.action, tab);
}
}, this);
};
proto.reposition = function(tab) {
this.messageView.repositionMessages(tab);
};
proto.hide = function(message) {
this.messageView.hide(message);
}
module.exports = MessageHandler;
});
| /**
* Terminal Module for the Cloud9
*
* @copyright 2013, Ajax.org B.V.
*/
define(function(require, exports, module) {
"use strict";
var MessageHandler = function(messageMatchers, messageView) {
this.messageMatchers = messageMatchers;
this.messageView = messageView;
};
var proto = MessageHandler.prototype;
proto.handleMessage = function(data, tab) {
this.messageMatchers.forEach(function(trigger) {
trigger.pattern.test(data) && this.messageView.show(trigger.message, trigger.action, tab);
}, this);
};
proto.reposition = function(tab) {
this.messageView.repositionMessages(tab);
};
proto.hide = function(message) {
this.messageView.hide(message);
}
module.exports = MessageHandler;
});
|
Remove `os.EOL` and just use `'\n'` | 'use strict';
const debug = require('debug')('asset-resolver');
const resolver = require('./lib/resolver');
function any(promises) {
return Promise.all(
promises.map(promise =>
promise.then(
val => {
throw val;
},
reason => reason
)
)
).then(
reasons => {
throw reasons;
},
firstResolved => firstResolved
);
}
module.exports.getResource = (file, options = {}) => {
const opts = {
base: [process.cwd()],
filter: () => true,
...options
};
if (!Array.isArray(opts.base)) {
opts.base = [opts.base];
}
opts.base = resolver.glob([...opts.base]);
const promises = (opts.base || []).map(base => {
return resolver.getResource(base, file, opts);
});
return any(promises).catch(error => {
const msg = [`The file "${file}" could not be resolved because of:`].concat(
error.map(err => err.message)
);
debug(msg);
return Promise.reject(new Error(msg.join('\n')));
});
};
| 'use strict';
const os = require('os');
const debug = require('debug')('asset-resolver');
const resolver = require('./lib/resolver');
function any(promises) {
return Promise.all(
promises.map(promise =>
promise.then(
val => {
throw val;
},
reason => reason
)
)
).then(
reasons => {
throw reasons;
},
firstResolved => firstResolved
);
}
module.exports.getResource = (file, options = {}) => {
const opts = {
base: [process.cwd()],
filter: () => true,
...options
};
if (!Array.isArray(opts.base)) {
opts.base = [opts.base];
}
opts.base = resolver.glob([...opts.base]);
const promises = (opts.base || []).map(base => {
return resolver.getResource(base, file, opts);
});
return any(promises).catch(error => {
const msg = [`The file "${file}" could not be resolved because of:`].concat(
error.map(err => err.message)
);
debug(msg);
return Promise.reject(new Error(msg.join(os.EOL)));
});
};
|
Update test_render_PUT_valid_parameters to be an approximate first draft. | import json
import urllib
from twisted.trial import unittest
import mock
from mlabsim import update
class UpdateResourceTests (unittest.TestCase):
def test_render_PUT_valid_parameters(self):
# Test data:
fqdn = 'mlab01.ooni-tests.not-real.except-it-actually-could-be.example.com'
tool_extra = {
'collector_onion': 'testfakenotreal.onion',
}
tool_extra_param = urllib.quote(json.dumps(tool_extra))
# Mocks / components:
db = {}
# Mocks:
m_request = mock.MagicMock()
# Fake a request with sufficient parameters:
m_request.params = {
'fqdn': fqdn,
'tool_extra': tool_extra_param,
}
# Execute the code under test:
ur = update.UpdateResource(db)
ur.render_PUT(m_request)
# Verify that m_db now stores fqdn: tool_extra:
self.assertEqual({fqdn: {"tool_extra": tool_extra}}, db)
| import json
import urllib
from twisted.trial import unittest
import mock
from mlabsim import update
class UpdateResourceTests (unittest.TestCase):
def test_render_PUT_valid_parameters(self):
# Test data:
tool_extra = {
'collector_onion': 'testfakenotreal.onion',
}
tool_extra_param = urllib.quote(json.dumps(tool_extra))
# Mocks:
m_db = mock.MagicMock()
m_request = mock.MagicMock()
# Fake a request with sufficient parameters:
m_request.params = {
'tool_extra': tool_extra_param,
}
# Execute the code under test:
ur = update.UpdateResource(m_db)
ur.render_PUT(m_request)
# Verify that m_db now stores tool_extra:
raise NotImplementedError('verification of m_db storage for tool_extra')
|
Remove rootURL so netlify can deploy it | 'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'dummy',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
EXTEND_PROTOTYPES: true,
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
ENV.locationType = 'hash';
}
return ENV;
};
| 'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'dummy',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
EXTEND_PROTOTYPES: true,
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
// Allow ember-cli-addon-docs to update the rootURL in compiled assets
ENV.rootURL = 'ADDON_DOCS_ROOT_URL';
ENV.locationType = 'hash';
}
return ENV;
};
|
Revert 5505 - introduced numerous regressions into the test suite | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
from sine import sipserver, sinetheme
sineproxy = provisioning.BenefactorFactory(
name = u'sineproxy',
description = u'Sine SIP Proxy',
benefactorClass = sipserver.SineBenefactor)
plugin = offering.Offering(
name = u"Sine",
description = u"""
The Sine SIP proxy and registrar.
""",
siteRequirements = (
(userbase.IRealm, userbase.LoginSystem),
(None, website.WebSite),
(None, sipserver.SIPServer)),
appPowerups = (sipserver.SinePublicPage,
),
benefactorFactories = (sineproxy,),
themes = (sinetheme.XHTMLDirectoryTheme('base'),)
)
| from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
from sine import sipserver, sinetheme
sineproxy = provisioning.BenefactorFactory(
name = u'sineproxy',
description = u'Sine SIP Proxy',
benefactorClass = sipserver.SineBenefactor)
plugin = offering.Offering(
name = u"Sine",
description = u"""
The Sine SIP proxy and registrar.
""",
siteRequirements = (
(userbase.IRealm, userbase.LoginSystem),
(None, website.WebSite),
(None, sipserver.SIPServer)),
appPowerups = (sipserver.SinePublicPage,
),
benefactorFactories = (sineproxy,),
loginInterfaces=(),
themes = (sinetheme.XHTMLDirectoryTheme('base'),)
)
|
Add preference to not load user's default database. | package org.reldb.dbrowser.ui.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.util.Util;
/**
* This class creates a preference page
*/
public class PreferencePageGeneral extends FieldEditorPreferencePage {
public static final String LARGE_ICONS = "general.double_icons";
public static final String DEFAULT_CMD_MODE = "general.default_cmd_mode";
public static final String SKIP_DEFAULT_DB_LOAD = "general.skip_default_db_load";
/**
* Constructor
*/
public PreferencePageGeneral() {
setTitle("General");
setDescription("General settings.");
}
protected void createFieldEditors() {
String reloadPrompt = "";
if (!Util.isMac())
reloadPrompt = " Restart after changing to see the full effect.";
addField(new BooleanFieldEditor(LARGE_ICONS, "&Larger icons." + reloadPrompt, getFieldEditorParent()));
addField(new BooleanFieldEditor(DEFAULT_CMD_MODE, "Default to command-line mode.", getFieldEditorParent()));
addField(new BooleanFieldEditor(SKIP_DEFAULT_DB_LOAD, "Do not automatically load user's default database.", getFieldEditorParent()));
}
}
| package org.reldb.dbrowser.ui.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.util.Util;
/**
* This class creates a preference page
*/
public class PreferencePageGeneral extends FieldEditorPreferencePage {
public static final String LARGE_ICONS = "general.double_icons";
public static final String DEFAULT_CMD_MODE = "general.default_cmd_mode";
/**
* Constructor
*/
public PreferencePageGeneral() {
setTitle("General");
setDescription("General settings.");
}
protected void createFieldEditors() {
String reloadPrompt = "";
if (!Util.isMac())
reloadPrompt = " Restart after changing to see the full effect.";
addField(new BooleanFieldEditor(LARGE_ICONS, "&Larger icons." + reloadPrompt, getFieldEditorParent()));
addField(new BooleanFieldEditor(DEFAULT_CMD_MODE, "Default to command-line mode.", getFieldEditorParent()));
}
}
|
Add test for package commit | from matador.commands import CreateTicket, CreatePackage
from dulwich.repo import Repo
from pathlib import Path
def test_add_to_git(project_repo):
pass
def test_create_ticket(session, project_repo):
test_ticket = 'test-ticket'
CreateTicket(ticket=test_ticket)
ticket_folder = Path(project_repo, 'deploy', 'tickets', test_ticket)
deploy_file = Path(ticket_folder, 'deploy.py')
assert ticket_folder.exists()
assert deploy_file.exists()
repo = Repo(str(project_repo))
last_commit = repo.get_object(repo.head())
commit_message = last_commit.message
expected_message = bytes(
'Create ticket %s\n' % test_ticket, encoding='UTF-8')
assert commit_message == expected_message
def test_create_package(session, project_repo):
test_package = 'test-package'
CreatePackage(package=test_package)
package_folder = Path(project_repo, 'deploy', 'packages', test_package)
package_file = Path(package_folder, 'tickets.yml')
remove_file = Path(package_folder, 'remove.py')
assert package_folder.exists()
assert package_file.exists()
assert remove_file.exists()
repo = Repo(str(project_repo))
last_commit = repo.get_object(repo.head())
commit_message = last_commit.message
expected_message = bytes(
'Create package %s\n' % test_package, encoding='UTF-8')
assert commit_message == expected_message
| from matador.commands import CreateTicket, CreatePackage
from dulwich.repo import Repo
from pathlib import Path
def test_add_to_git(project_repo):
pass
def test_create_ticket(session, project_repo):
test_ticket = 'test-ticket'
CreateTicket(ticket=test_ticket)
ticket_folder = Path(project_repo, 'deploy', 'tickets', test_ticket)
deploy_file = Path(ticket_folder, 'deploy.py')
repo = Repo(str(project_repo))
last_commit = repo.get_object(repo.head())
commit_message = last_commit.message
assert ticket_folder.exists()
assert deploy_file.exists()
expected_message = bytes(
'Create ticket %s\n' % test_ticket, encoding='UTF-8')
assert commit_message == expected_message
def test_create_package(session, project_repo):
test_package = 'test-package'
CreatePackage(package=test_package)
package_folder = Path(project_repo, 'deploy', 'packages', test_package)
package_file = Path(package_folder, 'tickets.yml')
remove_file = Path(package_folder, 'remove.py')
assert package_folder.exists()
assert package_file.exists()
assert remove_file.exists()
|
Fix issue identified by Psalm
Co-authored-by: Andreas Möller <96e8155732e8324ae26f64d4516eb6fe696ac84f@localheinz.com>
Co-authored-by: Arne Blankerts <2d7739f42ebd62662a710577d3d9078342a69dee@Blankerts.de>
Co-authored-by: Sebastian Bergmann <b70482a9c35b236639019cd8b2ecb03a9ee7db09@sebastian-bergmann.de> | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util;
use const E_WARNING;
use function restore_error_handler;
use function set_error_handler;
use function var_export;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class VariableExporter
{
public function export(mixed $variable): ExportedVariable
{
$warningWasTriggered = false;
set_error_handler(
static function (int $errorNumber, string $errorString) use (&$warningWasTriggered): ?bool {
$warningWasTriggered = true;
return null;
},
E_WARNING
);
$exportedVariable = var_export($variable, true);
restore_error_handler();
return ExportedVariable::from($exportedVariable, $warningWasTriggered);
}
}
| <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util;
use const E_WARNING;
use function restore_error_handler;
use function set_error_handler;
use function var_export;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class VariableExporter
{
public function export(mixed $variable): ExportedVariable
{
$warningWasTriggered = false;
set_error_handler(
static function (int $errorNumber, string $errorString) use (&$warningWasTriggered): void {
$warningWasTriggered = true;
},
E_WARNING
);
$exportedVariable = var_export($variable, true);
restore_error_handler();
return ExportedVariable::from($exportedVariable, $warningWasTriggered);
}
}
|
Change UNSET to so bool(UNSET) is False. | # The MIT License
#
# Copyright (c) 2010 Jeffrey Jenkins
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def classproperty(fun):
class Descriptor(property):
def __get__(self, instance, owner):
return fun(owner)
return Descriptor()
class UNSET(object):
def __repr__(self):
return 'UNSET'
def __eq__(self, other):
return other.__class__ == self.__class__
def __nonzero__(self):
return False
UNSET = UNSET()
| # The MIT License
#
# Copyright (c) 2010 Jeffrey Jenkins
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def classproperty(fun):
class Descriptor(property):
def __get__(self, instance, owner):
return fun(owner)
return Descriptor()
class UNSET(object):
def __repr__(self):
return 'UNSET'
def __eq__(self, other):
return other.__class__ == self.__class__
UNSET = UNSET()
|
Move QR Code cache to /tmp | from hashlib import sha1
from pathlib import Path
import qrcode as qr
from django_jinja import library
from jinja2 import Markup
from qrcode.image.svg import SvgPathImage
QR_CACHE_PATH = Path('/tmp/qrcode_cache')
QR_CACHE_PATH.mkdir(exist_ok=True)
@library.global_function
def qrcode(data, box_size=20):
name = sha1(f'{data}-{box_size}'.encode('utf-8')).hexdigest()
filename = f'{name}.svg'
filepath = QR_CACHE_PATH.joinpath(filename)
if not filepath.exists():
img = qr.make(data,
image_factory=SvgPathImage,
box_size=box_size)
img.save(str(filepath))
with filepath.open() as fp:
return Markup(fp.read())
| from hashlib import sha1
from django.conf import settings
import qrcode as qr
from django_jinja import library
from jinja2 import Markup
from qrcode.image.svg import SvgPathImage
QR_CACHE_PATH = settings.DATA_PATH.joinpath('qrcode_cache')
QR_CACHE_PATH.mkdir(exist_ok=True)
@library.global_function
def qrcode(data, box_size=20):
name = sha1(f'{data}-{box_size}'.encode('utf-8')).hexdigest()
filename = f'{name}.svg'
filepath = QR_CACHE_PATH.joinpath(filename)
if not filepath.exists():
img = qr.make(data,
image_factory=SvgPathImage,
box_size=box_size)
img.save(str(filepath))
with filepath.open() as fp:
return Markup(fp.read())
|
Test zip data for path() | import io
import os.path
import pathlib
import sys
import unittest
import importlib_resources as resources
from . import data
from . import util
class CommonTests(util.CommonTests, unittest.TestCase):
def execute(self, package, path):
with resources.path(package, path):
pass
class PathTests:
def test_reading(self):
# Path should be readable.
# Test also implicitly verifies the returned object is a pathlib.Path
# instance.
with resources.path(self.data, 'utf-8.file') as path:
# pathlib.Path.read_text() was introduced in Python 3.5.
with path.open('r', encoding='utf-8') as file:
text = file.read()
self.assertEqual('Hello, UTF-8 world!\n', text)
class PathDiskTests(PathTests, unittest.TestCase):
data = data
class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
pass
| import io
import os.path
import pathlib
import sys
import unittest
import importlib_resources as resources
from . import data
from . import util
class CommonTests(util.CommonTests, unittest.TestCase):
def execute(self, package, path):
with resources.path(package, path):
pass
class PathTests(unittest.TestCase):
def test_reading(self):
# Path should be readable.
# Test also implicitly verifies the returned object is a pathlib.Path
# instance.
with resources.path(data, 'utf-8.file') as path:
# pathlib.Path.read_text() was introduced in Python 3.5.
with path.open('r', encoding='utf-8') as file:
text = file.read()
self.assertEqual('Hello, UTF-8 world!\n', text)
|
Set NBT tree view with correct proxy model (oops) | """
nbttreewidget
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from PySide import QtGui
from PySide.QtCore import Qt
from mcedit2.widgets.nbttree.nbttreemodel import NBTFilterProxyModel
from mcedit2.util.load_ui import registerCustomWidget
from mcedit2.widgets.layout import Row
log = logging.getLogger(__name__)
@registerCustomWidget
class NBTTreeView(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(NBTTreeView, self).__init__(*args, **kwargs)
self.treeView = QtGui.QTreeView()
self.setLayout(Row(self.treeView))
def setModel(self, model):
self.model = model
proxyModel = NBTFilterProxyModel(self)
proxyModel.setSourceModel(model)
proxyModel.setDynamicSortFilter(True)
self.treeView.setModel(proxyModel)
self.treeView.sortByColumn(0, Qt.AscendingOrder)
self.treeView.expandToDepth(0)
self.treeView.resizeColumnToContents(0)
self.treeView.resizeColumnToContents(1)
| """
nbttreewidget
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from PySide import QtGui
from PySide.QtCore import Qt
from mcedit2.widgets.nbttree.nbttreemodel import NBTFilterProxyModel
from mcedit2.util.load_ui import registerCustomWidget
from mcedit2.widgets.layout import Row
log = logging.getLogger(__name__)
@registerCustomWidget
class NBTTreeView(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(NBTTreeView, self).__init__(*args, **kwargs)
self.treeView = QtGui.QTreeView()
self.setLayout(Row(self.treeView))
def setModel(self, model):
self.model = model
proxyModel = NBTFilterProxyModel(self)
proxyModel.setSourceModel(model)
proxyModel.setDynamicSortFilter(True)
self.treeView.setModel(model)
self.treeView.sortByColumn(0, Qt.AscendingOrder)
self.treeView.expandToDepth(0)
self.treeView.resizeColumnToContents(0)
self.treeView.resizeColumnToContents(1)
|
Fix unit test for older version of phpunit. | <?php
class ParserTests extends PHPUnit_Framework_TestCase
{
public function testInitBasicMarkdownParser()
{
$parser = new \Mybb\Parser\Parser(new \s9e\TextFormatter\Configurator(), [
'formatter_type' => 'markdown',
]);
$markdown = <<<EOT
# This is a simple test
* This is a list.
* It's only two items long.
EOT;
$expected = <<<EOT
<h1>This is a simple test</h1>
<ul><li>This is a list.</li>
<li>It's only two items long.</li></ul>
EOT;
$actual = $parser->parse($markdown);
$this->assertEquals($expected, $actual);
}
}
| <?php
class ParserTests extends \phpunit\framework\TestCase
{
public function testInitBasicMarkdownParser()
{
$parser = new \Mybb\Parser\Parser(new \s9e\TextFormatter\Configurator(), [
'formatter_type' => 'markdown',
]);
$markdown = <<<EOT
# This is a simple test
* This is a list.
* It's only two items long.
EOT;
$expected = <<<EOT
<h1>This is a simple test</h1>
<ul><li>This is a list.</li>
<li>It's only two items long.</li></ul>
EOT;
$actual = $parser->parse($markdown);
$this->assertEquals($expected, $actual);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.