text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Delete both pending bases and translations
|
# Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_bases(apps, schema_editor):
"""
Delete all pending bases
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Base = apps.get_model("exercises", "ExerciseBase")
Base.objects.filter(status='1').delete()
def delete_pending_translations(apps, schema_editor):
"""
Delete all pending translations
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Exercise = apps.get_model("exercises", "Exercise")
Exercise.objects.filter(status='1').delete()
class Migration(migrations.Migration):
dependencies = [
('core', '0014_merge_20210818_1735'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('exercises', '0017_muscle_name_en'),
]
operations = [
migrations.RunPython(delete_pending_bases),
migrations.RunPython(delete_pending_translations),
]
|
# Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_exercises(apps, schema_editor):
"""
Delete all pending exercises
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Exercise = apps.get_model("exercises", "ExerciseBase")
Exercise.objects.filter(status='1').delete()
class Migration(migrations.Migration):
dependencies = [
('core', '0014_merge_20210818_1735'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('exercises', '0017_muscle_name_en'),
]
operations = [migrations.RunPython(delete_pending_exercises)]
|
Revert "Change method 'alias' to 'bind' for provide facade"
This reverts commit a65d340
|
<?php
namespace AndrewNovikof\Objects;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
], 'config');
$this->publishes([
__DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
__DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
], 'objects');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../resources/config/objects.php',
'config'
);
$this->app->alias('objects', ObjectsService::class);
}
}
|
<?php
namespace AndrewNovikof\Objects;
use Illuminate\Support\ServiceProvider;
/**
* Class ObjectsServiceProvider
* @package Objects
*/
class ObjectsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
], 'config');
$this->publishes([
__DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
__DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
], 'objects');
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../resources/config/objects.php',
'config'
);
$this->app->bind('objects', ObjectsService::class);
}
}
|
[DoctrineBridge] Fix log of non utf8 data
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Logger;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Doctrine\DBAL\Logging\DebugStack;
/**
* DbalLogger.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DbalLogger extends DebugStack
{
protected $logger;
/**
* Constructor.
*
* @param LoggerInterface $logger A LoggerInterface instance
*/
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function startQuery($sql, array $params = null, array $types = null)
{
parent::startQuery($sql, $params, $types);
if (null !== $this->logger) {
$this->log($sql.' ('.@json_encode($params).')');
}
}
/**
* Logs a message.
*
* @param string $message A message to log
*/
public function log($message)
{
$this->logger->debug($message);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Logger;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Doctrine\DBAL\Logging\DebugStack;
/**
* DbalLogger.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DbalLogger extends DebugStack
{
protected $logger;
/**
* Constructor.
*
* @param LoggerInterface $logger A LoggerInterface instance
*/
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function startQuery($sql, array $params = null, array $types = null)
{
parent::startQuery($sql, $params, $types);
if (null !== $this->logger) {
$this->log($sql.' ('.json_encode($params).')');
}
}
/**
* Logs a message.
*
* @param string $message A message to log
*/
public function log($message)
{
$this->logger->debug($message);
}
}
|
Add points for capital locations>
|
"""
U.S. state capitals overlayed on a map of the U.S
================================================
This is a layered geographic visualization that shows US capitals
overlayed on a map.
"""
import altair as alt
from vega_datasets import data
states = alt.UrlData(data.us_10m.url,
format=alt.TopoDataFormat(type='topojson',
feature='states'))
capitals = data.us_state_capitals.url
# US states background
background = alt.Chart(states).mark_geoshape(
fill='lightgray',
stroke='white'
).properties(
projection={'type': 'albersUsa'},
width=800,
height=500
)
# State capitals labeled on background
points = alt.Chart(capitals).mark_text(dy=-5, align='right').encode(
alt.Text('city', type='nominal'),
alt.X('lon', type='longitude'),
alt.Y('lat', type='latitude'),
)
chart = background + points + points.mark_point(color='black')
|
"""
U.S. state capitals overlayed on a map of the U.S
================================================-
This is a geographic visualization that shows US capitals
overlayed on a map.
"""
import altair as alt
from vega_datasets import data
states = alt.UrlData(data.us_10m.url,
format=alt.TopoDataFormat(type='topojson',
feature='states'))
capitals = data.us_state_capitals.url
# US states background
background = alt.Chart(states).mark_geoshape(
fill='lightgray',
stroke='white'
).properties(
projection={'type': 'albersUsa'},
width=800,
height=500
)
# State capitals labeled on background
points = alt.Chart(capitals).mark_text().encode(
alt.Text('city', type='nominal'),
alt.X('lon', type='longitude'),
alt.Y('lat', type='latitude'),
)
chart = background + points
|
Update requests requirement from <2.20,>=2.4.2 to >=2.4.2,<2.21
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.20.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.21',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.20',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
Test for tree equivalence now checks hashCode
|
package see.integration;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import see.See;
import see.tree.Node;
import static org.junit.Assert.assertEquals;
@RunWith(Theories.class)
public class TreeEquivalenceTest {
See see = new See();
@DataPoints
public static final String[] data = {"a", "1+2", "sum(2,3)", "9+42+100500.0", "a = 5", "isDefined(crn)"};
@Theory
public void testEquivalence(String example) throws Exception {
Node<Object> run1 = see.parseExpression(example);
Node<Object> run2 = see.parseExpression(example);
assertEquals(run1, run2);
assertEquals(run1.hashCode(), run2.hashCode());
}
}
|
package see.integration;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import see.See;
import see.tree.Node;
import static org.junit.Assert.assertEquals;
@RunWith(Theories.class)
public class TreeEquivalenceTest {
See see = new See();
@DataPoints
public static final String[] data = {"a", "1+2", "sum(2,3)", "9+42+100500.0", "a = 5", "isDefined(crn)"};
@Theory
public void testEquivalence(String example) throws Exception {
Node<Object> run1 = see.parseExpression(example);
Node<Object> run2 = see.parseExpression(example);
assertEquals(run1, run2);
}
}
|
Make the application check working
Not so good because I don't find any way to know how to know the
application is loaded (the event $viewContentLoaded is never emmited ...)
|
//
// A PhantomJS script used to check that the hosted examples load
// without errors. This script is executed by the Makefile's
// check-examples target.
//
var args = require('system').args;
if (args.length != 2) {
phantom.exit(1);
}
var examplePath = args[1];
var page = require('webpage').create();
var exitCode = 0;
page.onError = function(msg, trace) {
var msgStack = ['JavaScript ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
exitCode = 2;
};
page.onConsoleMessage = function(msg) {
console.log('console:', msg);
exitCode = 2;
};
page.open(examplePath, function(s) {
if (s != 'success') {
console.error('PAGE LOAD ERROR');
phantom.exit(2);
}
setTimeout(function() {
console.log("EXIT", exitCode)
phantom.exit(exitCode);
}, 3000)
});
|
//
// A PhantomJS script used to check that the hosted examples load
// without errors. This script is executed by the Makefile's
// check-examples target.
//
var args = require('system').args;
if (args.length != 2) {
phantom.exit(2);
}
var examplePath = args[1];
var page = require('webpage').create();
page.onError = function(msg, trace) {
var msgStack = ['JavaScript ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
phantom.exit(1);
};
page.open(examplePath, function(s) {
var exitCode = 0;
if (s != 'success') {
exitCode = 1;
console.error('PAGE LOAD ERROR');
}
phantom.exit(exitCode);
});
page.onConsoleMessage = function(msg) {
console.log('console:', msg);
phantom.exit(msg.match(/error/i) ? 1 : 0);
};
|
Update KNEX setup file to point to the correct location of test seed data.
|
// Update with your config settings.
module.exports = {
development: {
client: 'pg',
connection: 'postgres://localhost/happyhourpower',
useNullAsDefault: true,
migrations: {
directory: './db/migrations',
},
seeds: {
directory: './db/seeds/dev',
},
},
test: {
client: 'pg',
connection: process.env.DATABASE_URL || 'postgres://localhost/happyhourpowertest',
useNullAsDefault: true,
migrations: {
directory: './db/migrations',
},
seeds: {
directory: './db/seeds/test',
},
},
production: {
client: 'pg',
connection: `${process.env.DATABASE_URL}?ssl=true`,
migrations: {
directory: './db/migrations',
},
useNullAsDefault: true,
},
};
|
// Update with your config settings.
module.exports = {
development: {
client: 'pg',
connection: 'postgres://localhost/happyhourpower',
useNullAsDefault: true,
migrations: {
directory: './db/migrations',
},
seeds: {
directory: './db/seeds/dev',
},
},
test: {
client: 'pg',
connection: process.env.DATABASE_URL || 'postgres://localhost/happyhourpowertest',
useNullAsDefault: true,
migrations: {
directory: './db/migrations',
},
seeds: {
directory: './db/test/seeds',
},
},
production: {
client: 'pg',
connection: `${process.env.DATABASE_URL}?ssl=true`,
migrations: {
directory: './db/migrations',
},
useNullAsDefault: true,
},
};
|
Add describing text to mismatchDescription in case on mismatch
|
package retromock.matchers;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import java.util.regex.Pattern;
public class IsRegex extends TypeSafeDiagnosingMatcher<String> {
private final Pattern pattern;
public static IsRegex matchesRegex(String regex) {
return new IsRegex(Pattern.compile(regex));
}
public IsRegex(Pattern pattern) {
this.pattern = pattern;
}
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
final boolean matches = pattern.matcher(item).matches();
if (!matches) {
mismatchDescription
.appendText("Item ")
.appendValue(item)
.appendText(" did not match pattern ")
.appendValue(pattern);
}
return matches;
}
@Override
public void describeTo(Description description) {
description
.appendText("a string matching the pattern '")
.appendValue(pattern)
.appendText("'");
}
}
|
package retromock.matchers;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import java.util.regex.Pattern;
public class IsRegex extends TypeSafeDiagnosingMatcher<String> {
private final Pattern pattern;
public static IsRegex matchesRegex(String regex) {
return new IsRegex(Pattern.compile(regex));
}
public IsRegex(Pattern pattern) {
this.pattern = pattern;
}
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
return pattern.matcher(item).matches();
}
@Override
public void describeTo(Description description) {
description
.appendText("a string matching the pattern '")
.appendValue(pattern)
.appendText("'");
}
}
|
Add test to ensure talons.helpers.import_function returns a callable
|
# -*- encoding: utf-8 -*-
#
# Copyright 2013 Jay Pipes
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
def test_return_function(self):
fn = helpers.import_function('os.path.join')
self.assertEqual(callable(fn), True)
|
# -*- encoding: utf-8 -*-
#
# Copyright 2013 Jay Pipes
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
|
Fix webpack dev server port
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
'./example/index.js'
],
output: {
path: __dirname + '/example/',
filename: 'all.js',
publicPath: '/example'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/,
include: __dirname
}]
}
};
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./example/index.js'
],
output: {
path: __dirname + '/example/',
filename: 'all.js',
publicPath: '/example'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/,
include: __dirname
}]
}
};
|
UCLALIB-198: Use prod for stage_file_proxy_origin on local dev.
|
<?php
// Setup DB
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'uclalib',
'username' => 'uclalib',
'password' => 'uclalib',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
// Tell Drupal that we are behind a reverse proxy server
//$conf['reverse_proxy'] = TRUE;
// List of trusted IPs (IP numbers of our reverse proxies)
//$conf['reverse_proxy_addresses'] = array(
// '127.0.0.1',
//);
// Solr settings
$conf['search_api_solr_overrides'] = array(
'uclalib_solr_server' => array(
'name' => t('Solr (dev)'),
'options' => array(
'host' => 'localhost',
'port' => '8080',
'path' => '/solr/uclalibdev',
),
),
);
$conf['stage_file_proxy_origin'] = 'http://library.ucla.edu';
|
<?php
// Setup DB
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'uclalib',
'username' => 'uclalib',
'password' => 'uclalib',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
// Tell Drupal that we are behind a reverse proxy server
//$conf['reverse_proxy'] = TRUE;
// List of trusted IPs (IP numbers of our reverse proxies)
//$conf['reverse_proxy_addresses'] = array(
// '127.0.0.1',
//);
// Solr settings
$conf['search_api_solr_overrides'] = array(
'uclalib_solr_server' => array(
'name' => t('Solr (dev)'),
'options' => array(
'host' => 'localhost',
'port' => '8080',
'path' => '/solr/uclalibdev',
),
),
);
$conf['stage_file_proxy_origin'] = 'http://uclalib:BDts_qP5Ewa2@uclalib.dev.gobsp.com';
|
Add a wrapper to handle content size
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getTheme } from '../Theme';
import ContentBody from './ContentBody';
import ContentHeader from './ContentHeader';
const Content = ({ sidebar, style, children }) => {
const stylesWrapper = {
...styles.wrapper,
...style,
};
if (!sidebar.visible) {
stylesWrapper.paddingLeft = 0;
}
return (
<div style={stylesWrapper}>
<div style={styles.content}>
{children}
</div>
</div>
);
};
Content.Body = ContentBody;
Content.Header = ContentHeader;
const styles = {
wrapper: {
boxSizing: 'border-box',
display: 'flex',
flexDirection: 'column',
minHeight: '100%',
paddingTop: getTheme().appBar.height,
paddingLeft: getTheme().drawer.width,
transitionProperty: 'padding',
transitionDuration: '300ms',
},
content: {
position: 'relative',
boxSizing: 'border-box',
width: '100%',
minHeight: '100%',
flexGrow: 1,
},
};
Content.defaultProps = {
style: {},
};
Content.propTypes = {
style: PropTypes.object,
};
const mapStateToProps = state => ({
sidebar: state.sidebar,
});
export default connect(mapStateToProps)(Content);
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getTheme } from '../Theme';
import ContentBody from './ContentBody';
import ContentHeader from './ContentHeader';
const Content = ({ sidebar, style, children }) => {
const stylesWrapper = {
...styles.wrapper,
...style,
};
if (!sidebar.visible) {
stylesWrapper.paddingLeft = 0;
}
return (
<div style={stylesWrapper}>
{children}
</div>
);
};
Content.Body = ContentBody;
Content.Header = ContentHeader;
const styles = {
wrapper: {
minHeight: '100%',
paddingTop: getTheme().appBar.height,
paddingLeft: getTheme().drawer.width,
transitionProperty: 'padding',
transitionDuration: '300ms',
boxSizing: 'border-box',
},
};
Content.defaultProps = {
style: {},
};
Content.propTypes = {
style: PropTypes.object,
};
const mapStateToProps = state => ({
sidebar: state.sidebar,
});
export default connect(mapStateToProps)(Content);
|
Introduce a helper to cast errors to a CellError
|
export class CellError extends Error {
constructor(msg, details) {
super(msg)
this.details = details
}
static cast(err) {
if (err instanceof CellError) {
return err
} else {
return new RuntimeError(err.message, err)
}
}
}
export class SyntaxError extends CellError {
get type() { return 'engine' }
get name() { return 'syntax' }
}
export class ContextError extends CellError {
get type() { return 'engine' }
get name() { return 'context' }
}
export class GraphError extends CellError {
get type() { return 'graph' }
}
export class UnresolvedInputError extends GraphError {
get name() { return 'unresolved' }
}
export class CyclicDependencyError extends GraphError {
get trace() {
return this.details.trace
}
get name() { return 'cyclic'}
}
export class OutputCollisionError extends GraphError {
get name() { return 'collision'}
}
export class RuntimeError extends CellError {
get type() { return 'runtime' }
get name() { return 'runtime' }
}
export class ValidationError extends CellError {
get type() { return 'runtime' }
get name() { return 'validation' }
}
|
export class CellError extends Error {
constructor(msg, details) {
super(msg)
this.details = details
}
}
export class SyntaxError extends CellError {
get type() { return 'engine' }
get name() { return 'syntax' }
}
export class ContextError extends CellError {
get type() { return 'engine' }
get name() { return 'context' }
}
export class GraphError extends CellError {
get type() { return 'graph' }
}
export class UnresolvedInputError extends GraphError {
get name() { return 'unresolved' }
}
export class CyclicDependencyError extends GraphError {
get trace() {
return this.details.trace
}
get name() { return 'cyclic'}
}
export class OutputCollisionError extends GraphError {
get name() { return 'collision'}
}
export class RuntimeError extends CellError {
get type() { return 'runtime' }
get name() { return 'runtime' }
}
export class ValidationError extends CellError {
get type() { return 'runtime' }
get name() { return 'validation' }
}
|
Fix PE backend file offset of section
|
from ..region import Section
class PESection(Section):
"""
Represents a section for the PE format.
"""
def __init__(self, pe_section, remap_offset=0):
super().__init__(
pe_section.Name.decode(),
pe_section.PointerToRawData,
pe_section.VirtualAddress + remap_offset,
pe_section.Misc_VirtualSize,
)
self.characteristics = pe_section.Characteristics
self.size_of_raw_data = pe_section.SizeOfRawData
#
# Public properties
#
@property
def is_readable(self):
return self.characteristics & 0x40000000 != 0
@property
def is_writable(self):
return self.characteristics & 0x80000000 != 0
@property
def is_executable(self):
return self.characteristics & 0x20000000 != 0
@property
def only_contains_uninitialized_data(self):
return self.size_of_raw_data == 0
|
from ..region import Section
class PESection(Section):
"""
Represents a section for the PE format.
"""
def __init__(self, pe_section, remap_offset=0):
super().__init__(
pe_section.Name.decode(),
pe_section.Misc_PhysicalAddress,
pe_section.VirtualAddress + remap_offset,
pe_section.Misc_VirtualSize,
)
self.characteristics = pe_section.Characteristics
self.size_of_raw_data = pe_section.SizeOfRawData
#
# Public properties
#
@property
def is_readable(self):
return self.characteristics & 0x40000000 != 0
@property
def is_writable(self):
return self.characteristics & 0x80000000 != 0
@property
def is_executable(self):
return self.characteristics & 0x20000000 != 0
@property
def only_contains_uninitialized_data(self):
return self.size_of_raw_data == 0
|
Increase driving time during autonomous
|
package com.saintsrobotics.frc.commands.autonomous;
import com.saintsrobotics.frc.commands.ResetShootBall;
import com.saintsrobotics.frc.commands.ShootBall;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
* The basic autonomous command.
* @author Saints Robotics
*/
public class BasicAutonomous extends CommandGroup {
private static final double DRIVE_SECONDS = 2.0;
public BasicAutonomous() {
// Move forward to lower pickup
addSequential(new MoveIntoZone(DRIVE_SECONDS));
// Shoot the preloaded ball!
addSequential(new ShootBall());
// Reset the shooter
addSequential(new ResetShootBall());
}
}
|
package com.saintsrobotics.frc.commands.autonomous;
import com.saintsrobotics.frc.commands.ResetShootBall;
import com.saintsrobotics.frc.commands.ShootBall;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
* The basic autonomous command.
* @author Saints Robotics
*/
public class BasicAutonomous extends CommandGroup {
private static final double DRIVE_SECONDS = 1.0;
public BasicAutonomous() {
// Move forward to lower pickup
addSequential(new MoveIntoZone(DRIVE_SECONDS));
// Shoot the preloaded ball!
addSequential(new ShootBall());
// Reset the shooter
addSequential(new ResetShootBall());
}
}
|
:art: Use package name in protocol to avoid conflicts
|
/** @babel */
import { CompositeDisposable } from 'atom';
import TerminalView from './terminal-view';
export default {
disposables: null,
terminalViews: [],
activate(state) {
this.disposables = new CompositeDisposable();
// Register Opener for the Terminal URI (`terminal://`)
this.disposables.add(atom.workspace.addOpener((uri) => {
if (uri.indexOf('atom-terminal-tab:') == 0) {
const terminalView = new TerminalView();
this.terminalViews.push(terminalView);
return terminalView;
}
}));
this.disposables.add(atom.commands.add('atom-workspace', {
'terminal:open': this.open.bind(this),
'terminal:copy': this.handleCopy.bind(this),
'terminal:paste': this.handlePaste.bind(this),
'terminal:clear': this.handleClear.bind(this)
}));
},
deactivate() {
this.disposables.dispose();
},
open() {
atom.workspace.open('atom-terminal-tab://');
},
handleCopy(event) {
let activeTerminalView = atom.workspace.getActivePaneItem();
activeTerminalView.copySelection();
},
handlePaste(event) {
let activeTerminalView = atom.workspace.getActivePaneItem();
activeTerminalView.pasteFromClipboard();
},
handleClear(event) {
let activeTerminalView = atom.workspace.getActivePaneItem();
activeTerminalView.clear();
}
};
|
/** @babel */
import { CompositeDisposable } from 'atom';
import TerminalView from './terminal-view';
export default {
disposables: null,
terminalViews: [],
activate(state) {
this.disposables = new CompositeDisposable();
// Register Opener for the Terminal URI (`terminal://`)
this.disposables.add(atom.workspace.addOpener((uri) => {
if (uri.indexOf('terminal:') == 0) {
const terminalView = new TerminalView();
this.terminalViews.push(terminalView);
return terminalView;
}
}));
this.disposables.add(atom.commands.add('atom-workspace', {
'terminal:open': this.open.bind(this),
'terminal:copy': this.handleCopy.bind(this),
'terminal:paste': this.handlePaste.bind(this),
'terminal:clear': this.handleClear.bind(this)
}));
},
deactivate() {
this.disposables.dispose();
},
open() {
atom.workspace.open('terminal://');
},
handleCopy(event) {
let activeTerminalView = atom.workspace.getActivePaneItem();
activeTerminalView.copySelection();
},
handlePaste(event) {
let activeTerminalView = atom.workspace.getActivePaneItem();
activeTerminalView.pasteFromClipboard();
},
handleClear(event) {
let activeTerminalView = atom.workspace.getActivePaneItem();
activeTerminalView.clear();
}
};
|
Update latency calculating mechanism to return latency is half of rtt
|
function Player (name, roomId, playerId, color, socket, socketId) {
this.name = name;
this.roomId = roomId;
this.playerId = playerId;
this.color = color;
this.socket = socket;
this.socketId = socketId;
this.startMeasuringLatency();
}
Player.prototype.startMeasuringLatency = function () {
var that = this;
var lastSentTime;
var lastSentRttResponseReceived = true;
that.socket.on('connection.rtt.fromclient', function (data) {
lastSentRttResponseReceived = true;
var currentTime = new Date().getTime();
that.latency = currentTime - lastSentTime / 2; // Latency is half rtt
});
var rttMeasure = setInterval(function () {
if (lastSentRttResponseReceived) {
that.socket.emit('connection.rtt.toclient');
lastSentTime = new Date().getTime();
lastSentRttResponseReceived = false;
}
}, 1000);
}
Player.prototype.getState = function () {
return {
name: this.name,
playerId: this.playerId,
socketId: this.socketId,
color: this.color
};
}
module.exports = Player;
|
function Player (name, roomId, playerId, color, socket, socketId) {
this.name = name;
this.roomId = roomId;
this.playerId = playerId;
this.color = color;
this.socket = socket;
this.socketId = socketId;
this.startMeasuringLatency();
}
Player.prototype.startMeasuringLatency = function () {
var that = this;
var lastSentTime;
var lastSentRttResponseReceived = true;
that.socket.on('connection.rtt.fromclient', function (data) {
lastSentRttResponseReceived = true;
var currentTime = new Date().getTime();
that.latency = currentTime - lastSentTime;
});
var rttMeasure = setInterval(function () {
if (lastSentRttResponseReceived) {
that.socket.emit('connection.rtt.toclient');
lastSentTime = new Date().getTime();
lastSentRttResponseReceived = false;
}
}, 1000);
}
Player.prototype.getState = function () {
return {
name: this.name,
playerId: this.playerId,
socketId: this.socketId,
color: this.color
};
}
module.exports = Player;
|
Refactor fs call to use only read file sync
|
const test = require('tape');
const api = require('../../src/helpers/api');
const { readFileSync } = require('fs');
const globalModulesPath = require('global-modules');
const { config } = require('dotenv');
test('is API key being correctly set?', (assert) => {
const testPath = `${globalModulesPath}/tinyme`;
const testEnvFile = 'variables_test.env';
const testEnvVarName = 'TINYME_TEST_API_KEY';
const testApiKey = 'TEST_API_KEY';
const testEnvApiKey = `${testEnvVarName}="${testApiKey}"`;
api.save(testApiKey, testPath, testEnvFile, testEnvVarName);
const settedEnvApiKey = readFileSync(`${testPath}/${testEnvFile}`).toString();
assert.equal(testEnvApiKey, settedEnvApiKey, 'API has been set correctly');
assert.end();
});
test('is API key being correctly read?', (assert) => {
const testPath = `${globalModulesPath}/tinyme`;
const testEnvFile = 'variables_test.env';
const testEnvVarName = 'TINYME_TEST_API_KEY';
config({ path: `${testPath}/${testEnvFile}` });
const envApiKey = process.env[testEnvVarName];
const apiKey = api.retrieve(testPath, testEnvFile, testEnvVarName);
assert.equal(apiKey, envApiKey, 'API key is being correctly returned');
assert.end();
});
|
const test = require('tape');
const api = require('../../src/helpers/api');
const fs = require('fs');
const globalModulesPath = require('global-modules');
const { config } = require('dotenv');
test('is API key being correctly set?', (assert) => {
const testPath = `${globalModulesPath}/tinyme`;
const testEnvFile = 'variables_test.env';
const testEnvVarName = 'TINYME_TEST_API_KEY';
const testApiKey = 'TEST_API_KEY';
const testEnvApiKey = `${testEnvVarName}="${testApiKey}"`;
api.save(testApiKey, testPath, testEnvFile, testEnvVarName);
const settedEnvApiKey = fs.readFileSync(`${testPath}/${testEnvFile}`).toString();
assert.equal(testEnvApiKey, settedEnvApiKey, 'API has been set correctly');
assert.end();
});
test('is API key being correctly read?', (assert) => {
const testPath = `${globalModulesPath}/tinyme`;
const testEnvFile = 'variables_test.env';
const testEnvVarName = 'TINYME_TEST_API_KEY';
config({ path: `${testPath}/${testEnvFile}` });
const envApiKey = process.env[testEnvVarName];
const apiKey = api.retrieve(testPath, testEnvFile, testEnvVarName);
assert.equal(apiKey, envApiKey, 'API key is being correctly returned');
assert.end();
});
|
Replace usages of 'bindShared' with 'singleton'
|
<?php namespace Bosnadev\Database;
use Bosnadev\Database\Connectors\ConnectionFactory;
use Illuminate\Database\DatabaseManager;
/**
* Class DatabaseServiceProvider
* @package Bosnadev\Database
*/
class DatabaseServiceProvider extends \Illuminate\Database\DatabaseServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// The connection factory is used to create the actual connection instances on
// the database. We will inject the factory into the manager so that it may
// make the connections while they are actually needed and not of before.
$this->app->singleton('db.factory', function ($app) {
return new ConnectionFactory($app);
});
// The database manager is used to resolve various connections, since multiple
// connections might be managed. It also implements the connection resolver
// interface which may be used by other components requiring connections.
$this->app->singleton('db', function ($app) {
return new DatabaseManager($app, $app['db.factory']);
});
}
}
|
<?php namespace Bosnadev\Database;
use Bosnadev\Database\Connectors\ConnectionFactory;
use Illuminate\Database\DatabaseManager;
/**
* Class DatabaseServiceProvider
* @package Bosnadev\Database
*/
class DatabaseServiceProvider extends \Illuminate\Database\DatabaseServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// The connection factory is used to create the actual connection instances on
// the database. We will inject the factory into the manager so that it may
// make the connections while they are actually needed and not of before.
$this->app->bindShared('db.factory', function ($app) {
return new ConnectionFactory($app);
});
// The database manager is used to resolve various connections, since multiple
// connections might be managed. It also implements the connection resolver
// interface which may be used by other components requiring connections.
$this->app->bindShared('db', function ($app) {
return new DatabaseManager($app, $app['db.factory']);
});
}
}
|
Make createApiUrl easier to use
|
var _ = require('underscore');
module.exports = function(robot){
robot.slack = {
baseApiUrl: 'https://slack.com/api/',
createApiUrl: function (suffix, queryString){
if (!!queryString){
if (_.isObject(queryString))
queryString = robot.util.toQueryString(queryString);
return robot.slack.baseApiUrl + suffix + queryString;
}
return robot.slack.baseApiUrl + suffix;
}
};
robot.respond(/channel list/i, function(res){
if (robot.auth.isAdmin(res.message.user)){
var data = {
token: process.env.HUBOT_SLACK_TOKEN,
exclude_archived: 1
};
robot.http(robot.slack.createApiUrl('channels.list', data))
.get()(function(err, response, body){
if (!!err){
res.reply('There was an error processing your request');
return;
}
var bodyJson = JSON.parse(body);
res.send(robot.util.formatJson(bodyJson));
});
}
});
}
|
module.exports = function(robot){
robot.slack = {
baseApiUrl: 'https://slack.com/api/',
createApiUrl: function (suffix){
return robot.slack.baseApiUrl + suffix;
}
};
robot.respond(/slack token/i, function(res){
if (robot.auth.isAdmin(res.message.user)){
res.reply(process.env.HUBOT_SLACK_TOKEN);
}
});
robot.respond(/channel list/i, function(res){
if (robot.auth.isAdmin(res.message.user)){
var data = {
token: process.env.HUBOT_SLACK_TOKEN,
exclude_archived: 1
};
robot.http(robot.slack.createApiUrl('channels.list' + robot.util.toQueryString(data)))
.get()(function(err, response, body){
if (!!err){
res.reply('There was an error processing your request');
return;
}
var bodyJson = JSON.parse(body);
res.send(robot.util.formatJson(bodyJson));
});
}
});
}
|
Remove last vestige of Ember-Data
|
export default {
name: 'preloadData',
initialize: function (container, application) {
var head = document.head;
var attributes = [
{
target: 'route:groups',
type: 'group',
content: $('meta[name="preload-groups"]', head).attr('content')
}
].filterBy('content');
var hasData = !Em.isEmpty(attributes);
if (hasData) {
attributes.forEach(function (obj) {
var data = JSON.parse(obj.content);
container.lookup(obj.target).set('preload', data);
// this would be useful for sending the data to the route
// application.register('preload:groups', data, { instantiate: false });
// application.inject(obj.target, 'preloadData', 'preload:groups');
});
}
}
};
|
export default {
name: 'preloadData',
initialize: function (container, application) {
var head = document.head;
var attributes = [
{
target: 'route:groups',
type: 'group',
content: $('meta[name="preload-groups"]', head).attr('content')
}
].filterBy('content');
var hasData = !Em.isEmpty(attributes);
if (hasData) {
var store = container.lookup('store:main');
attributes.forEach(function (obj) {
var data = JSON.parse(obj.content);
container.lookup(obj.target).set('preload', data);
// this would be useful for sending the data to the route
// application.register('preload:groups', data, { instantiate: false });
// application.inject(obj.target, 'preloadData', 'preload:groups');
});
}
}
};
|
Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtools.skipTest
Part of blueprint grizzly-testtools.
Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import testtools
from openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
class GettextTest(testtools.TestCase):
def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import unittest
from openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
class GettextTest(unittest.TestCase):
def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
|
Update gradient labels to use signal directive.
|
import {Perc, Label} from './constants';
import guideMark from './guide-mark';
import {TextMark} from '../marks/marktypes';
import {LegendLabelRole} from '../marks/roles';
var alignExpr = 'datum.' + Perc + '<=0?"left"'
+ ':datum.' + Perc + '>=1?"right":"center"';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter, update;
encode.enter = enter = {
opacity: zero,
text: {field: Label},
fill: {value: config.labelColor},
font: {value: config.labelFont},
fontSize: {value: config.labelFontSize},
baseline: {value: config.gradientLabelBaseline}
};
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1}
};
enter.x = update.x = {
field: Perc,
mult: config.gradientWidth
};
enter.y = update.y = {
value: config.gradientHeight,
offset: config.gradientLabelOffset
};
enter.align = update.align = {signal: alignExpr};
return guideMark(TextMark, LegendLabelRole, Label, dataRef, encode, userEncode);
}
|
import {Perc, Label} from './constants';
import guideMark from './guide-mark';
import {TextMark} from '../marks/marktypes';
import {LegendLabelRole} from '../marks/roles';
var alignExpr = 'datum.' + Perc + '<=0?"left"'
+ ':datum.' + Perc + '>=1?"right":"center"';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter, update;
encode.enter = enter = {
opacity: zero,
text: {field: Label},
fill: {value: config.labelColor},
font: {value: config.labelFont},
fontSize: {value: config.labelFontSize},
baseline: {value: config.gradientLabelBaseline}
};
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1}
};
enter.x = update.x = {
field: Perc,
mult: config.gradientWidth
};
enter.y = update.y = {
value: config.gradientHeight,
offset: config.gradientLabelOffset
};
enter.align = update.align = {expr: alignExpr};
return guideMark(TextMark, LegendLabelRole, Label, dataRef, encode, userEncode);
}
|
Return promise from version command
|
import promiseProps from 'promise-props-recursive'
import getLocalVersion from '../../npm-bridge/getLocalVersion'
import getGlobalSanityCliVersion from '../../util/getGlobalSanityCliVersion'
import pkg from '../../../package.json'
export default {
name: 'version',
signature: 'version',
description: 'Shows the installed versions of core Sanity components',
action: ({print}) =>
promiseProps({
local: getLocalVersion(pkg.name),
global: getGlobalSanityCliVersion()
}).then(versions => {
if (versions.global) {
print(`${pkg.name} (global): ${versions.global}`)
}
if (versions.local) {
print(`${pkg.name} (local): ${versions.local}`)
}
})
}
|
import promiseProps from 'promise-props-recursive'
import getLocalVersion from '../../npm-bridge/getLocalVersion'
import getGlobalSanityCliVersion from '../../util/getGlobalSanityCliVersion'
import pkg from '../../../package.json'
export default {
name: 'version',
signature: 'version',
description: 'Shows the installed versions of core Sanity components',
action: ({print}) => {
promiseProps({
local: getLocalVersion(pkg.name),
global: getGlobalSanityCliVersion()
}).then(versions => {
if (versions.global) {
print(`${pkg.name} (global): ${versions.global}`)
}
if (versions.local) {
print(`${pkg.name} (local): ${versions.local}`)
}
})
}
}
|
Update description to describe a more general case
|
#!/usr/bin/python
from setuptools import setup, find_packages
setup(
name="sandsnake",
license='Apache License 2.0',
version="0.1.0",
description="Sorted indexes backed by redis.",
long_description=open('README.rst', 'r').read(),
author="Numan Sachwani",
author_email="numan856@gmail.com",
url="https://github.com/numan/sandsnake",
packages=find_packages(exclude=['tests']),
test_suite='nose.collector',
install_requires=[
'nydus>=0.10.5',
'redis>=2.7.2',
'python-dateutil==1.5',
],
tests_require=[
'nose>=1.0',
],
classifiers=[
"Intended Audience :: Developers",
'Intended Audience :: System Administrators',
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Utilities",
],
)
|
#!/usr/bin/python
from setuptools import setup, find_packages
setup(
name="sandsnake",
license='Apache License 2.0',
version="0.1.0",
description="Manage activity indexes for objects.",
long_description=open('README.rst', 'r').read(),
author="Numan Sachwani",
author_email="numan856@gmail.com",
url="https://github.com/numan/sandsnake",
packages=find_packages(exclude=['tests']),
test_suite='nose.collector',
install_requires=[
'nydus>=0.10.5',
'redis>=2.7.2',
'python-dateutil==1.5',
],
tests_require=[
'nose>=1.0',
],
classifiers=[
"Intended Audience :: Developers",
'Intended Audience :: System Administrators',
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Utilities",
],
)
|
Stop passing radiumConfig prop to div
|
/* @flow */
import React, {Component, PropTypes} from 'react';
import Enhancer from '../enhancer';
import StyleKeeper from '../style-keeper';
import StyleSheet from './style-sheet';
function _getStyleKeeper(instance): StyleKeeper {
if (!instance._radiumStyleKeeper) {
const userAgent = (
instance.props.radiumConfig && instance.props.radiumConfig.userAgent
) || (
instance.context._radiumConfig && instance.context._radiumConfig.userAgent
);
instance._radiumStyleKeeper = new StyleKeeper(userAgent);
}
return instance._radiumStyleKeeper;
}
class StyleRoot extends Component {
constructor() {
super(...arguments);
_getStyleKeeper(this);
}
getChildContext() {
return {_radiumStyleKeeper: _getStyleKeeper(this)};
}
render() {
/* eslint-disable no-unused-vars */
// Pass down all props except config to the rendered div.
const {radiumConfig, ...otherProps} = this.props;
/* eslint-enable no-unused-vars */
return (
<div {...otherProps}>
{this.props.children}
<StyleSheet />
</div>
);
}
}
StyleRoot.contextTypes = {
_radiumConfig: PropTypes.object,
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot.childContextTypes = {
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot = Enhancer(StyleRoot);
export default StyleRoot;
|
/* @flow */
import React, {Component, PropTypes} from 'react';
import Enhancer from '../enhancer';
import StyleKeeper from '../style-keeper';
import StyleSheet from './style-sheet';
function _getStyleKeeper(instance): StyleKeeper {
if (!instance._radiumStyleKeeper) {
const userAgent = (
instance.props.radiumConfig && instance.props.radiumConfig.userAgent
) || (
instance.context._radiumConfig && instance.context._radiumConfig.userAgent
);
instance._radiumStyleKeeper = new StyleKeeper(userAgent);
}
return instance._radiumStyleKeeper;
}
class StyleRoot extends Component {
constructor() {
super(...arguments);
_getStyleKeeper(this);
}
getChildContext() {
return {_radiumStyleKeeper: _getStyleKeeper(this)};
}
render() {
return (
<div {...this.props}>
{this.props.children}
<StyleSheet />
</div>
);
}
}
StyleRoot.contextTypes = {
_radiumConfig: PropTypes.object,
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot.childContextTypes = {
_radiumStyleKeeper: PropTypes.instanceOf(StyleKeeper)
};
StyleRoot = Enhancer(StyleRoot);
export default StyleRoot;
|
Return via REST 'All-Projects' as parent name for projects under root
At the moment asking for the parent name of projects directly under the
'All-Projects' root project may return an empty string. Instead make
sure that in this case always 'All-Projects' is returned as name of the
parent project.
Change-Id: Ie65361dc512ca328b9b29fa250090c3cfc004126
Signed-off-by: Edwin Kempin <b444e279ad95fdef4fbdd82c813b624595df204a@sap.com>
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.project;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.inject.Inject;
class GetParent implements RestReadView<ProjectResource> {
private final AllProjectsName allProjectsName;
@Inject
GetParent(AllProjectsName allProjectsName) {
this.allProjectsName = allProjectsName;
}
@Override
public Object apply(ProjectResource resource) {
Project project = resource.getControl().getProject();
Project.NameKey parentName = project.getParent(allProjectsName);
return parentName != null ? parentName.get() : "";
}
}
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.project;
import com.google.common.base.Strings;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.Project;
class GetParent implements RestReadView<ProjectResource> {
@Override
public Object apply(ProjectResource resource) {
Project project = resource.getControl().getProject();
return Strings.nullToEmpty(project.getParentName());
}
}
|
Define trans_model only if it is not defined in project itself
|
<?php
use Netcore\Translator\Models\Language;
// In order to stay backwards compatible, we should define this
// helper function only if it is not defined in project itself
if (!function_exists('trans_model')) {
/**
* @param $row
* @param Language $language
* @param String $attribute
* @return String
*/
function trans_model($row, Language $language, $attribute = null): String
{
if (object_get($row, 'id')) {
if (is_null($attribute)) {
$model = $row->translateOrNew($language->iso_code);
if (is_object($model)) {
return $model;
}
}
if ($row) {
return (string)$row->translateOrNew($language->iso_code)->$attribute;
}
}
return '';
}
}
|
<?php
use Netcore\Translator\Models\Language;
/**
* @param $row
* @param Language $language
* @param String $attribute
* @return String
*/
function trans_model($row, Language $language, $attribute = null): String
{
if (object_get($row, 'id')) {
if (is_null($attribute)) {
$model = $row->translateOrNew($language->iso_code);
if (is_object($model)) {
return $model;
}
}
if ($row) {
return (string)$row->translateOrNew($language->iso_code)->$attribute;
}
}
return '';
}
|
Fix issue when content is not initialized
|
<?php
class sfAlohaBackendDoctrine extends sfAlohaBackendAbstract
{
/**
* {@inheritdoc}
*/
public function getContentByName($name)
{
$doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($name);
if (!$doctrineAlohaContent)
{
return null;
}
$alohaContent = new sfAlohaContent();
$alohaContent->setName($doctrineAlohaContent->getName())
->setBody($doctrineAlohaContent->getBody());
return $alohaContent;
}
/**
* {@inheritdoc}
*/
public function saveContent(sfAlohaContent $alohaContent)
{
// Get the existing content or create a new one
$doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($alohaContent->getName());
if (!$doctrineAlohaContent)
{
$doctrineAlohaContent = new AlohaContent();
$doctrineAlohaContent->setName($alohaContent->getName());
}
$doctrineAlohaContent->setBody($alohaContent->getBody());
$doctrineAlohaContent->save();
}
}
|
<?php
class sfAlohaBackendDoctrine extends sfAlohaBackendAbstract
{
/**
* {@inheritdoc}
*/
public function getContentByName($name)
{
$doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($name);
if (!$doctrineAlohaContent)
{
return null;
}
$alohaContent = new sfAlohaContent();
$alohaContent->setName($doctrineAlohaContent->getName())
->setBody($doctrineAlohaContent->getBody());
return $alohaContent;
}
/**
* {@inheritdoc}
*/
public function saveContent(sfAlohaContent $alohaContent)
{
// Get the existing content or create a new one
$doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($alohaContent->getName());
if (!$alohaContent)
{
$doctrineAlohaContent = new AlohaContent();
$doctrineAlohaContent->setName($alohaContent->getName());
}
$doctrineAlohaContent->setBody($alohaContent->getBody());
$doctrineAlohaContent->save();
}
}
|
Call getText() instead of toString().trim().
|
package mjc.analysis;
import org.apache.log4j.Logger;
import mjc.node.AMainClassDeclaration;
import mjc.node.Start;
public class BasicAnalyzer extends DepthFirstAdapter {
private static final Logger log = Logger.getLogger(BasicAnalyzer.class);
private boolean success = true;
public boolean analyze(Start tree) {
success = true;
tree.apply(this);
return success;
}
@Override
public void caseAMainClassDeclaration(AMainClassDeclaration node) {
final String className = node.getName().getText();
final String methodName = node.getMainMethodName().getText();
// The single method on the main class must be called "main".
if (methodName.compareTo("main") != 0) {
log.error("missing main method in class `" + className + "` (found `" + methodName + "`)");
success = false;
}
}
}
|
package mjc.analysis;
import org.apache.log4j.Logger;
import mjc.node.AMainClassDeclaration;
import mjc.node.Start;
public class BasicAnalyzer extends DepthFirstAdapter {
private static final Logger log = Logger.getLogger(BasicAnalyzer.class);
private boolean success = true;
public boolean analyze(Start tree) {
success = true;
tree.apply(this);
return success;
}
@Override
public void caseAMainClassDeclaration(AMainClassDeclaration node) {
final String className = node.getName().getText();
final String methodName = node.getMainMethodName().toString().trim();
// The single method on the main class must be called "main".
if (methodName.compareTo("main") != 0) {
log.error("missing main method in class `" + className + "` (found `" + methodName + "`)");
success = false;
}
}
}
|
Clean up an error message.
|
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package utils
import (
"github.com/juju/errors"
"github.com/juju/juju/instance"
provcommon "github.com/juju/juju/provider/common"
"github.com/juju/juju/state"
)
// AvailabilityZone returns the availability zone associated with
// an instance ID.
func AvailabilityZone(st *state.State, instID instance.Id) (string, error) {
// Get the provider.
env, err := GetEnvironment(st)
if err != nil {
return "", errors.Trace(err)
}
zenv, ok := env.(provcommon.ZonedEnviron)
if !ok {
return "", errors.NotSupportedf(`zones for provider "%T"`, env)
}
// Request the zone.
zones, err := zenv.InstanceAvailabilityZoneNames([]instance.Id{instID})
if err != nil {
return "", errors.Trace(err)
}
if len(zones) != 1 {
return "", errors.Errorf("received invalid zones: expected 1, got %d", len(zones))
}
return zones[0], nil
}
|
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package utils
import (
"github.com/juju/errors"
"github.com/juju/juju/instance"
provcommon "github.com/juju/juju/provider/common"
"github.com/juju/juju/state"
)
// AvailabilityZone returns the availability zone associated with
// an instance ID.
func AvailabilityZone(st *state.State, instID instance.Id) (string, error) {
// Get the provider.
env, err := GetEnvironment(st)
if err != nil {
return "", errors.Trace(err)
}
zenv, ok := env.(provcommon.ZonedEnviron)
if !ok {
return "", errors.NotSupportedf("zones for provider %v", env)
}
// Request the zone.
zones, err := zenv.InstanceAvailabilityZoneNames([]instance.Id{instID})
if err != nil {
return "", errors.Trace(err)
}
if len(zones) != 1 {
return "", errors.Errorf("received invalid zones: expected 1, got %d", len(zones))
}
return zones[0], nil
}
|
Add error return to action function signature
Not having an error return is deprecated
Signed-off-by: Mrunal Patel <d389837b018b67489df74a2c5f0aca13aaed44b6@gmail.com>
|
// +build linux
package main
import (
"os"
"runtime"
"github.com/opencontainers/runc/libcontainer"
_ "github.com/opencontainers/runc/libcontainer/nsenter"
"github.com/urfave/cli"
)
func init() {
if len(os.Args) > 1 && os.Args[1] == "init" {
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
}
}
var initCommand = cli.Command{
Name: "init",
Usage: `initialize the namespaces and launch the process (do not call it outside of runc)`,
Action: func(context *cli.Context) error {
factory, _ := libcontainer.New("")
if err := factory.StartInitialization(); err != nil {
// as the error is sent back to the parent there is no need to log
// or write it to stderr because the parent process will handle this
os.Exit(1)
}
panic("libcontainer: container init failed to exec")
},
}
|
// +build linux
package main
import (
"os"
"runtime"
"github.com/opencontainers/runc/libcontainer"
_ "github.com/opencontainers/runc/libcontainer/nsenter"
"github.com/urfave/cli"
)
func init() {
if len(os.Args) > 1 && os.Args[1] == "init" {
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
}
}
var initCommand = cli.Command{
Name: "init",
Usage: `initialize the namespaces and launch the process (do not call it outside of runc)`,
Action: func(context *cli.Context) {
factory, _ := libcontainer.New("")
if err := factory.StartInitialization(); err != nil {
// as the error is sent back to the parent there is no need to log
// or write it to stderr because the parent process will handle this
os.Exit(1)
}
panic("libcontainer: container init failed to exec")
},
}
|
Use env vars to config twilio sms plugin
|
import os
from twilio.rest import TwilioRestClient
from alerta.app import app
from alerta.plugins import PluginBase
LOG = app.logger
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN')
TWILIO_TO_NUMBER = os.environ.get('TWILIO_TO_NUMBER')
TWILIO_FROM_NUMBER = os.environ.get('TWILIO_FROM_NUMBER')
class SendSMSMessage(PluginBase):
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
if alert.repeat:
return
message = "%s: %s alert for %s - %s is %s" % (
alert.environment, alert.severity.capitalize(),
','.join(alert.service), alert.resource, alert.event
)
client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER)
LOG.info("Twilio SMS Message ID: %s", message.sid)
|
from twilio.rest import TwilioRestClient
from alerta.app import app
from alerta.plugins import PluginBase
LOG = app.logger
TWILIO_ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
TWILIO_AUTH_TOKEN = ''
TWILIO_TO_NUMBER = ''
TWILIO_FROM_NUMBER = ''
class SendSMSMessage(PluginBase):
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
if alert.repeat:
return
message = "%s: %s alert for %s - %s is %s" % (
alert.environment, alert.severity.capitalize(),
','.join(alert.service), alert.resource, alert.event
)
client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER)
LOG.info("Twilio SMS Message ID: %s", message.sid)
|
Check that output is just `{}` json
|
<?php
declare(strict_types = 1);
/**
* /tests/Integration/Controller/IndexControllerTest.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Tests\Integration\Controller;
use App\Controller\IndexController;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Class IndexControllerTest
*
* @package App\Tests\Integration\Controller
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
class IndexControllerTest extends KernelTestCase
{
/**
* @testdox Test that `__invoke` method returns proper response
*/
public function testThatInvokeMethodReturnsExpectedResponse(): void
{
$response = (new IndexController())();
$content = $response->getContent();
self::assertSame(200, $response->getStatusCode());
self::assertNotFalse($content);
self::assertJson($content);
self::assertJsonStringEqualsJsonString('{}', $content);
}
}
|
<?php
declare(strict_types = 1);
/**
* /tests/Integration/Controller/IndexControllerTest.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Tests\Integration\Controller;
use App\Controller\IndexController;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Class IndexControllerTest
*
* @package App\Tests\Integration\Controller
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
class IndexControllerTest extends KernelTestCase
{
/**
* @testdox Test that `__invoke` method returns proper response
*/
public function testThatInvokeMethodReturnsExpectedResponse(): void
{
$response = (new IndexController())();
$content = $response->getContent();
self::assertSame(200, $response->getStatusCode());
self::assertNotFalse($content);
self::assertJson($content);
}
}
|
Add gotoday link in date if it is not today
|
import React from 'react'
import moment from 'moment'
const Date = (props) => {
const styles = {
section: {
padding: '20px 0',
},
}
const today = moment().format('YYYY-MM-DD')
const displayDate = () => {
if (props.store.date !== today) {
return <p><a onClick={() => { props.actions.gotoToday() }}>{props.store.date}</a></p>
} else {
return <p>{props.store.date}</p>
}
}
return (
<section style={styles.section}>
<div className="container content is-large">
<div className="columns">
<div className="column is-4 has-text-right">
<button onClick={() => { props.actions.prevDate() }}>◀</button>
</div>
<div className="column is-4 has-text-centered">
{displayDate()}
</div>
<div className="column is-4 has-text-left">
<button onClick={() => { props.actions.nextDate() }}>▶</button>
</div>
</div>
</div>
</section>
)
}
export default Date
|
import React from 'react'
const Date = (props) => {
const styles = {
section: {
padding: '20px 0',
},
}
return (
<section style={styles.section}>
<div className="container content is-large">
<div className="columns">
<div className="column is-4 has-text-right">
<button onClick={() => { props.actions.prevDate() }}>◀</button>
</div>
<div className="column is-4 has-text-centered">
{props.store.date}
<button onClick={() => { props.actions.gotoToday() }}>today</button>
</div>
<div className="column is-4 has-text-left">
<button onClick={() => { props.actions.nextDate() }}>▶</button>
</div>
</div>
</div>
</section>
)
}
export default Date
|
Java: Move away from deprecated HTTP client API after libraries update.
|
package org.certificatetransparency.ctlog.comm;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
/**
* Simple delegator to HttpClient, so it can be mocked
*/
public class HttpPostInvoker {
/**
* Make an HTTP POST method call to the given URL with the provided JSON payload.
* @param url URL for POST method
* @param jsonPayload Serialized JSON payload.
* @return Server's response body.
*/
public String makePostRequest(String url, String jsonPayload) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(jsonPayload, "utf-8"));
post.addHeader("Content-Type", "application/json; charset=utf-8");
return httpClient.execute(post, new BasicResponseHandler());
} catch (IOException e) {
throw new LogCommunicationException("Error making POST request to " + url, e);
}
}
}
|
package org.certificatetransparency.ctlog.comm;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
/**
* Simple delegator to HttpClient, so it can be mocked
*/
public class HttpPostInvoker {
/**
* Make an HTTP POST method call to the given URL with the provided JSON payload.
* @param url URL for POST method
* @param jsonPayload Serialized JSON payload.
* @return Server's response body.
*/
public String makePostRequest(String url, String jsonPayload) {
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(jsonPayload, "utf-8"));
post.addHeader("Content-Type", "application/json; charset=utf-8");
return httpClient.execute(post, new BasicResponseHandler());
} catch (IOException e) {
throw new LogCommunicationException("Error making POST request to " + url, e);
} finally {
httpClient.getConnectionManager().shutdown();
}
}
}
|
Set up url for index page
|
"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from social_website_django_angular.views import IndexView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^.*$', IndexView.as_view(), name='index')
]
|
"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
Split URL and File comment attachment endpoints.
|
var utils = require('../utils/httpUtils.js');
var _ = require('underscore');
var constants = require('../utils/constants.js');
exports.create = function(options) {
var optionsToSend = {
accessToken : options.accessToken
};
var getComment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions);
return utils.get(_.extend(optionsToSend, getOptions), callback);
};
var deleteComment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions);
return utils.delete(_.extend(optionsToSend, getOptions), callback);
};
var addCommentUrlAttachment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions) + '/attachments';
return utils.post(_.extend(optionsToSend, getOptions), callback);
};
var addCommentFileAttachment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions) + '/attachments';
return utils.postFile(_.extend(optionsToSend, getOptions), callback);
};
var editComment = function(putOptions, callback) {
optionsToSend.url = buildUrl(putOptions);
return utils.put(_.extend(optionsToSend, putOptions), callback);
};
var buildUrl = function(urlOptions) {
return options.apiUrls.sheets + urlOptions.sheetId + '/comments/' + (urlOptions.commentId || '');
};
return {
getComment : getComment,
deleteComment : deleteComment,
addCommentUrlAttachment : addCommentUrlAttachment,
addCommentFileAttachment : addCommentFileAttachment,
editComment : editComment
};
};
|
var utils = require('../utils/httpUtils.js');
var _ = require('underscore');
var constants = require('../utils/constants.js');
exports.create = function(options) {
var optionsToSend = {
accessToken : options.accessToken
};
var getComment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions);
return utils.get(_.extend(optionsToSend, getOptions), callback);
};
var deleteComment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions);
return utils.delete(_.extend(optionsToSend, getOptions), callback);
};
var addCommentAttachment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions) + '/attachments';
return utils.post(_.extend(optionsToSend, getOptions), callback);
};
var editComment = function(putOptions, callback) {
optionsToSend.url = buildUrl(putOptions);
return utils.put(_.extend(optionsToSend, putOptions), callback);
};
var buildUrl = function(urlOptions) {
return options.apiUrls.sheets + urlOptions.sheetId + '/comments/' + (urlOptions.commentId || '');
};
return {
getComment : getComment,
deleteComment : deleteComment,
addCommentAttachment : addCommentAttachment,
editComment : editComment
};
};
|
[tests] Test logger on ioutil.Discard (not stdout)
|
package qb
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"log"
"testing"
)
func TestLogger(t *testing.T) {
db, err := New("sqlite3", ":memory:")
actors := Table("actors",
Column("id", BigInt().NotNull()),
PrimaryKey("id"),
)
db.Metadata().AddTable(actors)
db.CreateAll()
defer db.DropAll()
db.Engine().SetLogger(DefaultLogger{LQuery | LBindings, log.New(ioutil.Discard, "", log.LstdFlags)})
db.Engine().Logger().SetLogFlags(LQuery)
_, err = db.Engine().Exec(actors.Insert().Values(map[string]interface{}{"id": 5}))
assert.Nil(t, err)
db.Engine().Logger().SetLogFlags(LBindings)
_, err = db.Engine().Exec(actors.Insert().Values(map[string]interface{}{"id": 10}))
assert.Nil(t, err)
assert.Equal(t, db.Engine().Logger().LogFlags(), LQuery|LBindings)
}
|
package qb
import (
"github.com/stretchr/testify/assert"
"log"
"os"
"testing"
)
func TestLogger(t *testing.T) {
db, err := New("sqlite3", ":memory:")
actors := Table("actors",
Column("id", BigInt().NotNull()),
PrimaryKey("id"),
)
db.Metadata().AddTable(actors)
db.CreateAll()
defer db.DropAll()
db.Engine().SetLogger(DefaultLogger{LQuery | LBindings, log.New(os.Stdout, "", log.LstdFlags)})
db.Engine().Logger().SetLogFlags(LQuery)
_, err = db.Engine().Exec(actors.Insert().Values(map[string]interface{}{"id": 5}))
assert.Nil(t, err)
db.Engine().Logger().SetLogFlags(LBindings)
_, err = db.Engine().Exec(actors.Insert().Values(map[string]interface{}{"id": 10}))
assert.Nil(t, err)
assert.Equal(t, db.Engine().Logger().LogFlags(), LQuery|LBindings)
}
|
fix(ListFilterCache): Fix to update Filename, ParentID if changed.
|
<?php
/**
* Write the cached file to the 'File' SS database. This allows the file to be hosted on
* external file locations (such as Amazon S3) when syncing on large projects.
*/
class ListFilterCacheFile extends ListFilterCache {
private static $folder_name = 'Uploads';
public function save($data, $cacheKey) {
$name = $cacheKey;
$folderName = Config::inst()->get(__CLASS__, 'folder_name');
$folder = Folder::find_or_make($folderName); // relative to assets
$filename = $folder->Filename.$name;
$file = File::get()->filter(array(
'Name' => $name,
))->first();
if (!$file || !$file->exists()) {
$file = File::create();
}
$file->Name = $name;
$file->Filename = $filename;
$file->ParentID = ($folder && $folder->exists()) ? $folder->ID : null;
file_put_contents($file->getFullPath(), $data);
$file->write();
// Upload to S3/CDNContent for 'silverstripe-australia/cdncontent' module
$file->onAfterUpload();
return $file;
}
public function load($cacheKey) {
$file = $this->loadFile($cacheKey);
$data = file_get_contents($file->getFullPath());
return $data;
}
public function loadFile($cacheKey) {
$file = File::get()->filter(array(
'Name' => $cacheKey,
))->first();
return $file;
}
}
|
<?php
/**
* Write the cached file to the 'File' SS database. This allows the file to be hosted on
* external file locations (such as Amazon S3) when syncing on large projects.
*/
class ListFilterCacheFile extends ListFilterCache {
public function save($data, $cacheKey) {
$name = $cacheKey;
$filename = ASSETS_DIR.'/'.$name;
$file = File::get()->filter(array(
'Name' => $name,
))->first();
if (!$file || !$file->exists()) {
$file = File::create();
$file->Name = $name;
$file->Filename = $filename;
}
file_put_contents($file->getFullPath(), $data);
$file->write();
// Upload to S3/CDNContent for 'silverstripe-australia/cdncontent' module
$file->onAfterUpload();
return $file;
}
public function load($cacheKey) {
$file = $this->loadFile($cacheKey);
$data = file_get_contents($file->getFullPath());
return $data;
}
public function loadFile($cacheKey) {
$file = File::get()->filter(array(
'Name' => $cacheKey,
))->first();
return $file;
}
}
|
Add viaRemember to authenticator contract.
|
<?php namespace Illuminate\Contracts\Auth;
interface Authenticator {
/**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check();
/**
* Get the currently authenticated user.
*
* @return \Illuminate\Contracts\Auth\User|null
*/
public function user();
/**
* Log a user into the application without sessions or cookies.
*
* @param array $credentials
* @return bool
*/
public function once(array $credentials = array());
/**
* Attempt to authenticate a user using the given credentials.
*
* @param array $credentials
* @param bool $remember
* @param bool $login
* @return bool
*/
public function attempt(array $credentials = array(), $remember = false, $login = true);
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = array());
/**
* Log a user into the application.
*
* @param \Illuminate\Contracts\Auth\User $user
* @param bool $remember
* @return void
*/
public function login(User $user, $remember = false);
/**
* Determine if the user was authenticated via "remember me" cookie.
*
* @return bool
*/
public function viaRemember();
/**
* Log the user out of the application.
*
* @return void
*/
public function logout();
}
|
<?php namespace Illuminate\Contracts\Auth;
interface Authenticator {
/**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check();
/**
* Get the currently authenticated user.
*
* @return \Illuminate\Contracts\Auth\User|null
*/
public function user();
/**
* Log a user into the application without sessions or cookies.
*
* @param array $credentials
* @return bool
*/
public function once(array $credentials = array());
/**
* Attempt to authenticate a user using the given credentials.
*
* @param array $credentials
* @param bool $remember
* @param bool $login
* @return bool
*/
public function attempt(array $credentials = array(), $remember = false, $login = true);
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = array());
/**
* Log a user into the application.
*
* @param \Illuminate\Contracts\Auth\User $user
* @param bool $remember
* @return void
*/
public function login(User $user, $remember = false);
/**
* Log the user out of the application.
*
* @return void
*/
public function logout();
}
|
Build with clang by default
|
import os
from setuptools import setup, find_packages
# Build with clang if not otherwise specified.
os.environ.setdefault('CC', 'clang')
setup(
name='symsynd',
version='0.1',
url='http://github.com/getsentry/symsynd',
description='Helps symbolicating crash dumps.',
license='BSD',
author='Sentry',
author_email='hello@getsentry.com',
packages=find_packages(),
cffi_modules=['demangler_build.py:ffi'],
include_package_data=True,
zip_safe=False,
platforms='any',
install_requires=[
'macholib',
'cffi>=1.0.0',
],
setup_requires=[
'cffi>=1.0.0'
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
|
from setuptools import setup, find_packages
setup(
name='symsynd',
version='0.1',
url='http://github.com/getsentry/symsynd',
description='Helps symbolicating crash dumps.',
license='BSD',
author='Sentry',
author_email='hello@getsentry.com',
packages=find_packages(),
cffi_modules=['demangler_build.py:ffi'],
include_package_data=True,
zip_safe=False,
platforms='any',
install_requires=[
'macholib',
'cffi>=1.0.0',
],
setup_requires=[
'cffi>=1.0.0'
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
|
[minor] Use the defaultExt setting in `ecstatic`.
|
var union = require('union'),
ecstatic = require('ecstatic');
var is2014 = /2014\./;
//
// ### redirect(res)
// World's simplest redirect function
//
function redirect(res) {
var url = 'http://2014.empirenode.org',
body = '<p>301. Redirecting to <a href="' + url + '">' + url + '</a></p>';
res.writeHead(301, { 'content-type': 'text/html', location: url });
res.end(body);
}
var server = union.createServer({
before: [
// function (req, res) {
// var host = req.headers.host;
// if (process.env.NODE_ENV === 'production' && !is2014.test(host)) {
// return redirect(res);
// }
// res.emit('next');
// },
ecstatic({
root: __dirname + '/public',
defaultExt: true
}),
function (req, res) {
return redirect(res);
}
]
});
server.listen(8080);
|
var union = require('union'),
ecstatic = require('ecstatic');
var is2014 = /2014\./;
//
// ### redirect(res)
// World's simplest redirect function
//
function redirect(res) {
var url = 'http://2014.empirenode.org',
body = '<p>301. Redirecting to <a href="' + url + '">' + url + '</a></p>';
res.writeHead(301, { 'content-type': 'text/html', location: url });
res.end(body);
}
var server = union.createServer({
before: [
// function (req, res) {
// var host = req.headers.host;
// if (process.env.NODE_ENV === 'production' && !is2014.test(host)) {
// return redirect(res);
// }
// res.emit('next');
// },
ecstatic(__dirname + '/public'),
function (req, res) {
return redirect(res);
}
]
});
server.listen(8080);
|
Use array index instead of Buffer.get
Buffer.get was depracted in 2013 [1] and removed entirely in
Node 6 [2].
Closes #13.
[1] https://github.com/nodejs/node/issues/4587
[2] https://github.com/nodejs/node/wiki/Breaking-changes-between-v5-and-v6#buffer
|
/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true eqeqeq:true immed:true latedef:true*/
(function () {
"use strict";
/**
* A naiive 'Buffer.indexOf' function. Requires both the
* needle and haystack to be Buffer instances.
*/
function indexOf(haystack, needle, i) {
if (!Buffer.isBuffer(needle)) needle = new Buffer(needle);
if (typeof i === 'undefined') i = 0;
var l = haystack.length - needle.length + 1;
while (i<l) {
var good = true;
for (var j=0, n=needle.length; j<n; j++) {
if (haystack[i+j] !== needle[j]) {
good = false;
break;
}
}
if (good) return i;
i++;
}
return -1;
}
if (!Buffer.indexOf) {
Buffer.indexOf = indexOf;
}
if (!Buffer.prototype.indexOf) {
Buffer.prototype.indexOf = function(needle, i) {
return Buffer.indexOf(this, needle, i);
};
}
})();
|
/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true eqeqeq:true immed:true latedef:true*/
(function () {
"use strict";
/**
* A naiive 'Buffer.indexOf' function. Requires both the
* needle and haystack to be Buffer instances.
*/
function indexOf(haystack, needle, i) {
if (!Buffer.isBuffer(needle)) needle = new Buffer(needle);
if (typeof i === 'undefined') i = 0;
var l = haystack.length - needle.length + 1;
while (i<l) {
var good = true;
for (var j=0, n=needle.length; j<n; j++) {
if (haystack.get(i+j) !== needle.get(j)) {
good = false;
break;
}
}
if (good) return i;
i++;
}
return -1;
}
if (!Buffer.indexOf) {
Buffer.indexOf = indexOf;
}
if (!Buffer.prototype.indexOf) {
Buffer.prototype.indexOf = function(needle, i) {
return Buffer.indexOf(this, needle, i);
};
}
})();
|
Make task async and only quit once process exits
|
/*
* grunt-appium
* https://github.com/hungrydavid/grunt-appium
*
* Copyright (c) 2015 David Adams
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('appium', 'Grunt plugin for running appium', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({});
var appiumPath = require.resolve('appium');
var spawn = require('child_process').spawn;
var done = this.async();
var child = spawn('node', [appiumPath], function (err) {
console.log(err);
});
process.on('exit', function(data) {
done();
child.kill("SIGTERM");
});
});
};
|
/*
* grunt-appium
* https://github.com/hungrydavid/grunt-appium
*
* Copyright (c) 2015 David Adams
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('appium', 'Grunt plugin for running appium', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({});
var appiumPath = require.resolve('appium');
var spawn = require('child_process').spawn;
var child = spawn('node', [appiumPath], function (err) {
console.log(err);
});
process.on('exit', function(data) {
console.log('exit');
child.kill("SIGTERM");
});
});
};
|
Add zen object for zendesk config
|
const axios = require('axios')
const { get } = require('lodash')
const config = require('../../../config')
function createZenDeskMessage ({
email,
title,
description = '',
browser,
feedbackType,
}) {
return {
requester: {
name: 'Data Hub user',
email,
},
subject: title,
comment: {
body: description,
},
custom_fields: [
{ id: get(config, 'zen.browser'), value: browser },
{ id: get(config, 'zen.service'), value: get(config, 'zen.serviceChannel') },
],
tags: [feedbackType],
}
}
function postToZenDesk (ticket) {
return axios.post(config.zen.url, { ticket },
{
auth: {
username: `${config.zen.email}/token`,
password: config.zen.token,
},
}
)
}
module.exports = {
createZenDeskMessage,
postToZenDesk,
}
|
const axios = require('axios')
const config = require('../../../config')
function createZenDeskMessage ({
email,
title,
description = '',
browser,
feedbackType,
}) {
return {
requester: {
name: 'Data Hub user',
email,
},
subject: title,
comment: {
body: description,
},
custom_fields: [
{ id: config.zenBrowser, value: browser },
{ id: config.zenService, value: config.zenServiceChannel },
],
tags: [feedbackType],
}
}
function postToZenDesk (ticket) {
return axios.post(config.zenUrl, { ticket },
{
auth: {
username: `${config.zenEmail}/token`,
password: config.zenToken,
},
}
)
}
module.exports = {
createZenDeskMessage,
postToZenDesk,
}
|
Fix status error not set in error responses
|
'use strict';
const { processError } = require('../../../error');
const { httpProcessError } = require('./http');
// Error handler adding protocol-related information to exceptions
const protocolErrorHandler = function () {
return async function protocolErrorHandler(input) {
try {
const response = await this.next(input);
return response;
} catch (error) {
const keyName = 'protocol';
const { protocol: key, requestUrl: instance = 'unknown' } = input;
const genericInfo = { instance };
error = processError({
error,
input,
keyName,
key,
processErrorMap,
genericInfo,
});
throw error;
}
};
};
const processErrorMap = {
http: httpProcessError,
};
module.exports = {
protocolErrorHandler,
};
|
'use strict';
const { processError } = require('../../../error');
const { httpProcessError } = require('./http');
// Error handler adding protocol-related information to exceptions
const protocolErrorHandler = function () {
return async function protocolErrorHandler(input) {
try {
const response = await this.next(input);
return response;
} catch (error) {
const keyName = 'protocol';
const { name: key, requestUrl: instance = 'unknown' } = input;
const genericInfo = { instance };
error = processError({
error,
input,
keyName,
key,
processErrorMap,
genericInfo,
});
throw error;
}
};
};
const processErrorMap = {
http: httpProcessError,
};
module.exports = {
protocolErrorHandler,
};
|
Fix variable access for less-loader
|
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const { buildDir } = require('../env')
const extractText = new ExtractTextPlugin({
filename: '[contenthash].css'
})
extractText.lessConfig = {
test: /\.less$/,
use: extractText.extract({
use: [
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
{
loader: 'less-loader',
options: {
sourceMap: true,
strictMath: true,
strictUnits: true,
noIeCompat: true,
compress: false,
outputSourceFiles: true,
sourceMapFileInline: true,
globalVars: {
'build-root': `'${buildDir}'`
}
}
}
]
})
}
module.exports = extractText
|
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const { buildDir } = require('../env')
const extractText = new ExtractTextPlugin({
filename: '[contenthash].css'
})
extractText.lessConfig = {
test: /\.less$/,
use: extractText.extract({
use: [
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
{
loader: 'less-loader',
options: {
sourceMap: true,
strictMath: true,
strictUnits: true,
noIeCompat: true,
compress: false,
outputSourceFiles: true,
sourceMapFileInline: true,
globalVars: {
'build-root': buildDir
}
}
}
]
})
}
module.exports = extractText
|
Fix ul list test; needs clean up for lists
|
<?php # -*- coding: utf-8 -*-
namespace Bueltge\Marksimple\Tests\Unit\Rule;
use Bueltge\Marksimple\Rule;
use Bueltge\Marksimple\Rule\ElementRuleInterface;
use Bueltge\Marksimple\Tests\Unit\AbstractRuleTestCase;
class UnorderedListTest extends AbstractRuleTestCase
{
public function returnRule(): ElementRuleInterface
{
return new Rule\UnorderedList();
}
public function provideList()
{
yield 'asterix' => ['* List Element', '<ul><li>List Element</li></ul>'];
$input = '- List Element';
$expected = '<ul><li>List Element</li></ul>';
$text = 'Lorum ipsum';
yield 'minus' => [$input, $expected];
yield 'text before' => ["$text\n$input", "$text\n$expected"];
yield 'text after' => ["$input\n$text", "$expected\n$text"];
yield 'text before and after' => ["$text\n$input\n$text", "$text\n$expected\n$text"];
$input = <<<Markdown
* item 1
* item 2
* item 3
Markdown;
$expected = '<ul><li>item 1</li></ul>
<ul><li>item 2</li></ul>
<ul><li>item 3</li></ul>';
yield 'multiple items' => [$input, $expected];
}
}
|
<?php # -*- coding: utf-8 -*-
namespace Bueltge\Marksimple\Tests\Unit\Rule;
use Bueltge\Marksimple\Rule;
use Bueltge\Marksimple\Rule\ElementRuleInterface;
use Bueltge\Marksimple\Tests\Unit\AbstractRuleTestCase;
class UnorderedListTest extends AbstractRuleTestCase
{
public function returnRule(): ElementRuleInterface
{
return new Rule\UnorderedList();
}
public function provideList()
{
yield 'asterix' => ['* List Element', '<ul><li>List Element</li></ul>'];
$input = '- List Element';
$expected = '<ul><li>List Element</li></ul>';
$text = 'Lorum ipsum';
yield 'minus' => [$input, $expected];
yield 'text before' => ["$text\n$input", "$text\n$expected"];
yield 'text after' => ["$input\n$text", "$expected\n$text"];
yield 'text before and after' => ["$text\n$input\n$text", "$text\n$expected\n$text"];
$input = <<<Markdown
* item 1
* item 2
* item 3
Markdown;
$expected = '<ul><li>item 1</li><li>item 2</li><li>item 3</li></ul>';
yield 'multiple items' => [$input, $expected];
}
}
|
[UPDATE] Add update-autoload on clear-all command
|
<?php
class commands_ClearAll extends commands_AbstractChangeCommand
{
/**
* @return String
*/
function getUsage()
{
return "";
}
/**
* @return String
*/
function getDescription()
{
return "clear all";
}
/**
* @param String[] $params
* @param array<String, String> $options where the option array key is the option name, the potential option value or true
* @see c_ChangescriptCommand::parseArgs($args)
*/
function _execute($params, $options)
{
$this->message("== Clear all ==");
$parent = $this->getParent();
$parent->executeCommand("updateAutoload");
$parent->executeCommand("clearLog");
$parent->executeCommand("clearCache");
$parent->executeCommand("clearWebappCache");
$parent->executeCommand("clearSimplecache");
$parent->executeCommand("clearDatacache");
$parent->executeCommand("clearDocumentscache");
$this->quitOk("All was cleared");
}
}
|
<?php
class commands_ClearAll extends commands_AbstractChangeCommand
{
/**
* @return String
*/
function getUsage()
{
return "";
}
/**
* @return String
*/
function getDescription()
{
return "clear all";
}
/**
* @param String[] $params
* @param array<String, String> $options where the option array key is the option name, the potential option value or true
* @see c_ChangescriptCommand::parseArgs($args)
*/
function _execute($params, $options)
{
$this->message("== Clear all ==");
$parent = $this->getParent();
$parent->executeCommand("clearLog");
$parent->executeCommand("clearCache");
$parent->executeCommand("clearWebappCache");
$parent->executeCommand("clearSimplecache");
$parent->executeCommand("clearDatacache");
$parent->executeCommand("clearDocumentscache");
$this->quitOk("All was cleared");
}
}
|
Fix it to honor the environment variable when set
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
import os
from . import get_hosts
from .file_rewriter import FileRewriter
g_etc_hosts = os.getenv('SD2_ETC_HOSTS', '/etc/hosts')
def get_our_config():
rr = ''
for host in get_hosts(enabled=False):
if not host.get('containers'):
continue
rr += '{}\t{}\n'.format(host['local-ip'], host['name'] + '-local')
for cont in host['containers']:
rr += '{}\t{}\n'.format(cont['ip'], cont['name'])
return rr
def gen_etc_hosts():
fr = FileRewriter(g_etc_hosts)
before, after = fr.read_config()
rr = get_our_config()
fr.write_config(
before,
rr.split('\n'),
after,
sudo=True
)
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
import os
from . import get_hosts
from .file_rewriter import FileRewriter
g_etc_hosts = os.getenv('SD2_ETC_HOSTS', '/etc/hosts')
def get_our_config():
rr = ''
for host in get_hosts(enabled=False):
if not host.get('containers'):
continue
rr += '{}\t{}\n'.format(host['local-ip'], host['name'] + '-local')
for cont in host['containers']:
rr += '{}\t{}\n'.format(cont['ip'], cont['name'])
return rr
def gen_etc_hosts():
fr = FileRewriter('/etc/hosts')
before, after = fr.read_config()
rr = get_our_config()
fr.write_config(
before,
rr.split('\n'),
after,
sudo=True
)
|
Allow render to take a template different from the default one.
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
if template is None:
template = self.template
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(self.template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
Add cases to test if a hash maps size becomes prime on different inputs.
|
import org.junit.*;
public class HashMapTest {
HashMap hm;
@Before
public void setUp() {
hm = new HashMap(7);
}
@After
public void tearDown() {
hm = null;
}
@Test
public void testMapSizeBecomesPrimeWhenInputEven() {
HashMap mapEvenSize = new HashMap(4);
Assert.assertEquals(mapEvenSize.size, 5);
}
@Test
public void testMapSizeBecomesPrimeWhenInputOdd() {
HashMap mapOddSize = new HashMap(15);
Assert.assertEquals(mapOddSize.size, 17);
}
@Test
public void testInsertSingleKey() {
hm.put("Toronto", 10);
Assert.assertEquals(hm.getKey("Toronto"), 10);
}
@Test
public void testInsertDuplicateKeyUpdates() {
hm.put("New York", 15);
hm.put("New York", 10);
Assert.assertEquals(hm.getKey("New York"), 10);
}
@Test
public void testGetInvalidKey() {
Assert.assertEquals(hm.getKey("Copenhagen"), -1);
}
@Test
public void testHashSizeGetsNextPrime() {
HashMap hmap = new HashMap(4);
Assert.assertEquals(hmap.size, 5);
}
@Test
public void testDeleteEntry() {
hm.put("Toronto", 10);
hm.delete("Toronto");
Assert.assertEquals(hm.getKey("Toronto") , -1);
}
}
|
import org.junit.*;
public class HashMapTest {
HashMap hm;
@Before
public void setUp() {
hm = new HashMap(7);
}
@After
public void tearDown() {
hm = null;
}
@Test
public void testInsertSingleKey() {
hm.put("Toronto", 10);
Assert.assertEquals(hm.getKey("Toronto"), 10);
}
@Test
public void testInsertDuplicateKeyUpdates() {
hm.put("New York", 15);
hm.put("New York", 10);
Assert.assertEquals(hm.getKey("New York"), 10);
}
@Test
public void testGetInvalidKey() {
Assert.assertEquals(hm.getKey("Copenhagen"), -1);
}
@Test
public void testHashSizeGetsNextPrime() {
HashMap hmap = new HashMap(4);
Assert.assertEquals(hmap.size, 5);
}
@Test
public void testDeleteEntry() {
hm.put("Toronto", 10);
hm.delete("Toronto");
Assert.assertEquals(hm.getKey("Toronto") , -1);
}
}
|
Use the more common type name T instead of L.
|
/*
* 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);
}
|
/*
* 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);
}
|
Remove `@Nullable` for backwards compatibility with Kotlin API
|
/*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api;
/**
* <p>A {@code Transformer} transforms objects of type.</p>
*
* <p>Implementations are free to return new objects or mutate the incoming value.</p>
*
* @param <OUT> The type the value is transformed to.
* @param <IN> The type of the value to be transformed.
*/
public interface Transformer<OUT, IN> {
/**
* Transforms the given object, and returns the transformed value.
*
* @param in The object to transform.
* @return The transformed object.
*/
OUT transform(IN in);
}
|
/*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api;
import javax.annotation.Nullable;
/**
* <p>A {@code Transformer} transforms objects of type.</p>
*
* <p>Implementations are free to return new objects or mutate the incoming value.</p>
*
* @param <OUT> The type the value is transformed to.
* @param <IN> The type of the value to be transformed.
*/
public interface Transformer<OUT, IN> {
/**
* Transforms the given object, and returns the transformed value.
*
* @param in The object to transform.
* @return The transformed object.
*/
OUT transform(@Nullable IN in);
}
|
Make Files nav item selected in file detail page
|
'use strict';
var $ = require('jquery');
var fileBrowser = require('../fileViewTreebeard');
var nodeApiUrl = window.contextVars.node.urls.api;
$(document).ready(function() {
// Treebeard Files view
$.ajax({
url: nodeApiUrl + 'files/grid/'
})
.done(function (data) {
new fileBrowser(data);
});
var panelToggle = $('.panel-toggle');
var panelExpand = $('.panel-expand');
var panelVisible = panelToggle.find('.osf-panel-hide');
var panelHidden = panelToggle.find('.osf-panel-show');
$('.panel-collapse').on('click', function () {
panelToggle.removeClass('col-sm-3').addClass('col-sm-1');
panelExpand.removeClass('col-sm-9').addClass('col-sm-11');
panelVisible.hide();
panelHidden.show();
});
$('.osf-panel-show .panel-heading').on('click', function () {
panelToggle.removeClass('col-sm-1').addClass('col-sm-3');
panelExpand.removeClass('col-sm-11').addClass('col-sm-9');
panelVisible.show();
panelHidden.hide();
});
$('.osf-project-navbar li:contains("Files")').addClass('active');
});
|
'use strict';
var $ = require('jquery');
var fileBrowser = require('../fileViewTreebeard');
var nodeApiUrl = window.contextVars.node.urls.api;
$(document).ready(function() {
// Treebeard Files view
$.ajax({
url: nodeApiUrl + 'files/grid/'
})
.done(function (data) {
new fileBrowser(data);
});
var panelToggle = $('.panel-toggle');
var panelExpand = $('.panel-expand');
var panelVisible = panelToggle.find('.osf-panel-hide');
var panelHidden = panelToggle.find('.osf-panel-show');
$('.panel-collapse').on('click', function () {
panelToggle.removeClass('col-sm-3').addClass('col-sm-1');
panelExpand.removeClass('col-sm-9').addClass('col-sm-11');
panelVisible.hide();
panelHidden.show();
});
$('.osf-panel-show .panel-heading').on('click', function () {
panelToggle.removeClass('col-sm-1').addClass('col-sm-3');
panelExpand.removeClass('col-sm-11').addClass('col-sm-9');
panelVisible.show();
panelHidden.hide();
});
});
|
Allow setting of postgres user via an environment variable
Touch #73
|
from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
os.environ["INBOXEN_ADMIN_ACCESS"] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB')
postgres_user = os.environ.get('PG_USER', 'postgres')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif db == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'inboxen',
'USER': postgres_user,
},
}
else:
raise NotImplementedError("Please check tests/settings.py for valid DB values")
|
from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
os.environ["INBOXEN_ADMIN_ACCESS"] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif db == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'inboxen',
'USER': 'postgres',
},
}
else:
raise NotImplementedError("Please check tests/settings.py for valid DB values")
|
[Cache] Fix wrong classname in deprecation message
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Simple;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Traits\ApcuTrait;
use Symfony\Contracts\Cache\CacheInterface;
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" and type-hint for "%s" instead.', ApcuCache::class, ApcuAdapter::class, CacheInterface::class), E_USER_DEPRECATED);
/**
* @deprecated since Symfony 4.3, use ApcuAdapter and type-hint for CacheInterface instead.
*/
class ApcuCache extends AbstractCache
{
use ApcuTrait;
public function __construct(string $namespace = '', int $defaultLifetime = 0, string $version = null)
{
$this->init($namespace, $defaultLifetime, $version);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Simple;
use Symfony\Component\Cache\Traits\ApcuTrait;
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "%s" and type-hint for "%s" instead.', ApcuCache::class, ApcuAdapter::class, CacheInterface::class), E_USER_DEPRECATED);
/**
* @deprecated since Symfony 4.3, use ApcuAdapter and type-hint for CacheInterface instead.
*/
class ApcuCache extends AbstractCache
{
use ApcuTrait;
public function __construct(string $namespace = '', int $defaultLifetime = 0, string $version = null)
{
$this->init($namespace, $defaultLifetime, $version);
}
}
|
Revert "Icon is a stateless component"
This reverts commit 8215c6c465c595d8814430a0bf5945a9f52ce06e.
|
import React from 'react';
class Icon extends React.Component {
render() {
if (this.props.url) {
return (
<span className={this.className()} style={{
backgroundImage: `url(${this.props.url})`
}}>
</span>
);
} else {
return (
<span className={this.className()}>
{this.props.children}
</span>
);
}
}
className() {
var className = 'icon';
if (this.props.className) {
className += ' ' + this.props.className;
}
return className;
}
}
Icon.propTypes = {
url: React.PropTypes.string
};
export default Icon;
|
import React from 'react';
function Icon(props) {
if (props.url) {
return (
<span className={className(props)} style={{
backgroundImage: `url(${props.url})`
}}>
</span>
);
} else {
return (
<span className={className(props)}>
{props.children}
</span>
);
}
}
function className(props) {
var className = 'icon';
if (props.className) {
className += ' ' + props.className;
}
return className;
}
Icon.propTypes = {
url: React.PropTypes.string
};
export default Icon;
|
Disable default Django authorization URLs
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
Add custom error class 'InvalidOutputType'
|
"""
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
class InvalidType(ValueError):
"""Exception class for invalid type in arguments."""
pass
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
pass
class InvalidOutputType(ValueError):
"""Exception class for invalid output_type in arguments."""
pass
def check_arguments(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise InvalidType("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise InvalidSelector("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise InvalidOutputType("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
if int(args['--levels']) < 1:
raise Exception("--levels should be greater than, or equal to 1")
return
|
"""
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
class InvalidType(ValueError):
"""Exception class for invalid type in arguments."""
pass
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
pass
def check_arguments(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise InvalidType("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise InvalidSelector("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
if int(args['--levels']) < 1:
raise Exception("--levels should be greater than, or equal to 1")
return
|
Put DI settings in a private attribute
|
<?php
namespace Cft;
/**
* Simple Singleton Plugin class for bare-bones dependency injection
*/
final class Plugin {
private static $instance;
private $attributes = [];
private $viewDirs = [
CFT_PLUGIN_DIR
];
public function getInstance() {
if( ! self::$instance ) {
self::$instance = new Plugin();
}
return self::$instance;
}
// singleton constructor!
private function __construct() { }
public function get( $key ) {
if( isset($this->attributes[$key]) ) {
return is_callable( $this->attributes[$key] )
? call_user_func( $this->attributes[$key] )
: $this->attributes[$key];
}
}
public function set( $key, $value ) {
$this->attributes[$key] = $value;
}
}
|
<?php
namespace Cft;
/**
* Simple Singleton Plugin class for bare-bones dependency injection
*/
final class Plugin {
private static $instance;
private $viewDirs = [
CFT_PLUGIN_DIR
];
public function getInstance() {
if( ! self::$instance ) {
self::$instance = new static();
}
return self::$instance;
}
// singleton constructor!
private function __construct() { }
public function get( $key ) {
if( isset($this->{$key}) ) {
return is_callable( $this->{$key} )
? call_user_func( $this->{$key} )
: $this->{$key};
}
}
public function set( $key, $value ) {
$this->{$key} = $value;
}
}
|
Fix unused variable in BubbpleSort class
|
package ru.job4j.array;
/**
* Class BubbpleSort ti sort some arrays.
* @author Eugene Lazarev mailto(helycopternicht@rambler.ru)
* @since 27.03.2017
*/
public class BubbleSort {
/**
* Method returns sorted array.
* @param source - source array
* @return sorded source array
*/
public int[] sort(int[] source) {
boolean sorted = false;
int intend = 0;
while (!sorted) {
sorted = true;
for (int i = 1; i < source.length - intend; i++) {
if (source[i - 1] > source[i]) {
int temp = source[i - 1];
source[i - 1] = source[i];
source[i] = temp;
sorted = false;
}
}
intend++;
}
return source;
}
}
|
package ru.job4j.array;
/**
* Class BubbpleSort ti sort some arrays.
* @author Eugene Lazarev mailto(helycopternicht@rambler.ru)
* @since 27.03.2017
*/
public class BubbleSort {
/**
* Method returns sorted array.
* @param source - source array
* @return sorded source array
*/
public int[] sort(int[] source) {
boolean sorted = false;
int intend = 0;
while (!sorted) {
sorted = true;
for (int i = 1; i < source.length; i++) {
if (source[i - 1] > source[i]) {
int temp = source[i - 1];
source[i - 1] = source[i];
source[i] = temp;
sorted = false;
}
}
intend++;
}
return source;
}
}
|
Add class_name property to Token model
|
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from .conf import PHASES, TOKEN_TYPES
class Token(models.Model):
public_name = models.CharField(max_length=200)
symbol = models.CharField(max_length=4)
decimals = models.IntegerField(
default=18,
validators=[MaxValueValidator(20), MinValueValidator(0)]
)
phase = models.CharField(
max_length=8,
choices=PHASES,
default=PHASES[0][0],
)
token_type = models.CharField(
max_length=12,
choices=TOKEN_TYPES,
default=TOKEN_TYPES[0][0],
)
@property
def class_name(self):
return ''.join(
map(lambda s: s.title(), self.public_name.split())
)
|
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from .conf import PHASES, TOKEN_TYPES
class Token(models.Model):
public_name = models.CharField(max_length=200)
symbol = models.CharField(max_length=4)
decimals = models.IntegerField(
default=18,
validators=[MaxValueValidator(20), MinValueValidator(0)]
)
phase = models.CharField(
max_length=8,
choices=PHASES,
default=PHASES[0][0],
)
token_type = models.CharField(
max_length=12,
choices=TOKEN_TYPES,
default=TOKEN_TYPES[0][0],
)
|
Remove - from assetMap file name
|
/* jshint node: true */
'use strict';
let fs = require('fs');
module.exports = {
name: 'ember-cli-ifa',
isDevelopingAddon: function() {
return false;
},
postBuild: function (build) {
let indexFilePath = build.directory + '/index.html';
let indexFileBuffer = fs.readFileSync(indexFilePath);
let indexFile = indexFileBuffer.toString('utf8');
let files = fs.readdirSync(build.directory + '/assets');
let totalFiles = files.length;
let assetFileName = null;
for (let i = 0; i < totalFiles; i++) {
if (files[i].match(/^assetMap/i)) {
assetFileName = files[i];
break;
}
}
if (assetFileName) {
fs.writeFileSync(
indexFilePath,
indexFile.replace(/__asset_map_placeholder__/, '/assets/' + assetFileName)
);
}
},
contentFor(type, config) {
if (type === 'head-footer' && config.ifa && config.ifa.enabled) {
return '<script>var __assetMapFilename__ = "__asset_map_placeholder__";</script>';
}
}
};
|
/* jshint node: true */
'use strict';
let fs = require('fs');
module.exports = {
name: 'ember-cli-ifa',
isDevelopingAddon: function() {
return false;
},
postBuild: function (build) {
let indexFilePath = build.directory + '/index.html';
let indexFileBuffer = fs.readFileSync(indexFilePath);
let indexFile = indexFileBuffer.toString('utf8');
let files = fs.readdirSync(build.directory + '/assets');
let totalFiles = files.length;
let assetFileName = null;
for (let i = 0; i < totalFiles; i++) {
if (files[i].match(/^assetMap-/i)) {
assetFileName = files[i];
break;
}
}
if (assetFileName) {
fs.writeFileSync(
indexFilePath,
indexFile.replace(/__asset_map_placeholder__/, '/assets/' + assetFileName)
);
}
},
contentFor(type, config) {
if (type === 'head-footer' && config.ifa && config.ifa.enabled) {
return '<script>var __assetMapFilename__ = "__asset_map_placeholder__";</script>';
}
}
};
|
Fix import SUPERUSER_ID in project_issue migration scripts
Found error:
2014-07-18 17:04:11,710 8772 ERROR v8mig openerp.modules.migration: module project_issue: Unable to load post-migration file project_issue/migrations/8.0.1.0/post-migration.py
Traceback (most recent call last):
File "/home/dr/work/openupg/OpenUpgrade/openerp/modules/migration.py", line 167, in migrate_module
mod = imp.load_module(name, fp, pathname, ('.py', 'r', imp.PY_SOURCE))
File "/home/dr/work/openupg/OpenUpgrade/addons/project_issue/migrations/8.0.1.0/post-migration.py", line 22, in <module>
from openerp import SUPERUSER_UID as uid
ImportError: cannot import name SUPERUSER_UID
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import SUPERUSER_ID as uid
from openerp.openupgrade import openupgrade, openupgrade_80
@openupgrade.migrate
def migrate(cr, version):
openupgrade.map_values(
cr,
openupgrade.get_legacy_name('priority'),
'priority',
[('5', '0'), ('4', '0'), ('3', '1'), ('2', '2'), ('1', '2')],
table='project_issue', write='sql')
openupgrade_80.set_message_last_post(cr, uid, ['project.issue'])
openupgrade.load_data(
cr, 'project_issue', 'migrations/8.0.1.0/noupdate_changes.xml')
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import SUPERUSER_UID as uid
from openerp.openupgrade import openupgrade, openupgrade_80
@openupgrade.migrate
def migrate(cr, version):
openupgrade.map_values(
cr,
openupgrade.get_legacy_name('priority'),
'priority',
[('5', '0'), ('4', '0'), ('3', '1'), ('2', '2'), ('1', '2')],
table='project_issue', write='sql')
openupgrade_80.set_message_last_post(cr, uid, ['project.issue'])
openupgrade.load_data(
cr, 'project_issue', 'migrations/8.0.1.0/noupdate_changes.xml')
|
Fix typo in CustomSignatureForm fields definition
|
from petition.forms import SignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
import swapper
Signature = swapper.load_model("petition", "Signature")
class CustomSignatureForm(SignatureForm):
def __init__(self, *args, **kwargs):
super(CustomSignatureForm, self).__init__(*args, **kwargs)
self.helper.layout = Layout(
'first_name',
'second_name',
PrependedText('email', '@'),
PrependedText('city', '<i class="fa fa-globe"></i>'),
PrependedText('telephone', '<i class="fa fa-phone"></i>'),
'giodo',
'newsletter',
)
class Meta:
model = Signature
fields = ['first_name', 'second_name', 'email', 'city', 'newsletter', 'telephone']
|
from petition.forms import SignatureForm
from crispy_forms.layout import Layout, Submit
from crispy_forms.bootstrap import PrependedText
from crispy_forms.helper import FormHelper
from django.utils.translation import ugettext as _
import swapper
Signature = swapper.load_model("petition", "Signature")
class CustomSignatureForm(SignatureForm):
def __init__(self, *args, **kwargs):
super(CustomSignatureForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Sign'), css_class="btn-sign btn-lg btn-block"))
self.helper.layout = Layout(
'first_name',
'second_name',
PrependedText('email', '@'),
PrependedText('city', '<i class="fa fa-globe"></i>'),
PrependedText('telephone', '<i class="fa fa-phone"></i>'),
'giodo',
'newsletter',
)
class Meta:
model = Signature
field = ['first_name', 'second_name', 'email', 'city', 'telephone']
|
Increment version for speedup release
|
# -*- coding: utf-8 -*-
"""
Copyright 2016 Randal S. Olson
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.
"""
__version__ = '1.3'
|
# -*- coding: utf-8 -*-
"""
Copyright 2016 Randal S. Olson
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.
"""
__version__ = '1.2'
|
Print out what will actually be executed.
|
package se.tla.mavenversionbumper.vcs;
import java.io.File;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
/**
* Common functionality for implementations of the VersionControl interface.
*/
public abstract class AbstractVersionControl implements VersionControl {
public static final String VERSIONCONTROL = "versioncontrol";
@Override
public void prepareSave(File file) {
// Default is to do nothing before saving.
}
/**
* Execute this command line, optionally in this working directory.
* @param cmdLine
* @param workDir
*/
protected void execute(CommandLine cmdLine, File workDir) {
DefaultExecutor exec = new DefaultExecutor();
exec.setWatchdog(new ExecuteWatchdog(60000));
if (workDir != null) {
exec.setWorkingDirectory(workDir);
}
System.out.println("Running command: " + cmdLine.toString());
try {
exec.execute(cmdLine);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
package se.tla.mavenversionbumper.vcs;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import java.io.File;
import java.io.IOException;
/**
* Common functionality for implementations of the VersionControl interface.
*/
public abstract class AbstractVersionControl implements VersionControl {
public static final String VERSIONCONTROL = "versioncontrol";
@Override
public void prepareSave(File file) {
// Default is to do nothing before saving.
}
/**
* Execute this command line, optionally in this working directory.
* @param cmdLine
* @param workDir
*/
protected void execute(CommandLine cmdLine, File workDir) {
DefaultExecutor exec = new DefaultExecutor();
exec.setWatchdog(new ExecuteWatchdog(60000));
if (workDir != null) {
exec.setWorkingDirectory(workDir);
}
try {
exec.execute(cmdLine);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
Set base URL for dummy app production
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
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.baseURL = '/';
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';
}
if (environment === 'production') {
ENV.baseURL = 'http://baptiste.meurant.io/ember-array-contains-helper'
}
return ENV;
};
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
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.baseURL = '/';
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';
}
if (environment === 'production') {
}
return ENV;
};
|
Fix system font dirs for *nix
|
// +build dragonfly freebsd linux nacl netbsd openbsd solaris
// Copyright 2016 Florian Pigorsch. All rights reserved.
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package findfont
import (
"os"
"path/filepath"
)
func getFontDirectories() (paths []string) {
directories := getUserFontDirs()
directories = append(directories, getSystemFontDirs()...)
return directories
}
func getUserFontDirs() (paths []string) {
if dataPath := os.Getenv("XDG_DATA_HOME"); dataPath != "" {
return []string{expandUser("~/.fonts/"), filepath.Join(expandUser(dataPath), "fonts")}
}
return []string{expandUser("~/.fonts/"), expandUser("~/.local/share/fonts/")}
}
func getSystemFontDirs() (paths []string) {
if dataPaths := os.Getenv("XDG_DATA_DIRS"); dataPaths != "" {
for _, dataPath := range filepath.SplitList(dataPaths) {
paths = append(paths, filepath.Join(expandUser(dataPath), "fonts"))
}
return paths
}
return []string{"/usr/local/share/fonts/", "/usr/share/fonts/"}
}
|
// +build dragonfly freebsd linux nacl netbsd openbsd solaris
// Copyright 2016 Florian Pigorsch. All rights reserved.
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package findfont
import (
"os"
"path/filepath"
)
func getFontDirectories() (paths []string) {
directories := getUserFontDirs()
directories = append(directories, getSystemFontDirs()...)
return directories
}
func getUserFontDirs() (paths []string) {
if dataPath := os.Getenv("XDG_DATA_HOME"); dataPath != "" {
return []string{expandUser("~/.fonts/"), filepath.Join(expandUser(dataPath), "fonts")}
}
return []string{expandUser("~/.fonts/"), expandUser("~/.local/share/fonts/")}
}
func getSystemFontDirs() (paths []string) {
if dataPaths := os.Getenv("XDG_DATA_DIRS"); dataPaths == "" {
for _, dataPath := range filepath.SplitList(dataPaths) {
paths = append(paths, filepath.Join(expandUser(dataPath), "fonts"))
}
return paths
}
return []string{"/usr/local/share/fonts/", "/usr/share/fonts/"}
}
|
Upgrade tangled.web from 0.1a5 to 0.1a9
|
from setuptools import setup
setup(
name='tangled.auth',
version='0.1a4.dev0',
description='Tangled auth integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.auth/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.auth',
'tangled.auth.tests',
],
install_requires=[
'tangled.web>=0.1a9',
],
extras_require={
'dev': [
'tangled.web[dev]>=0.1a9',
],
},
entry_points="""
[tangled.scripts]
auth = tangled.auth.command:Command
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
from setuptools import setup
setup(
name='tangled.auth',
version='0.1a4.dev0',
description='Tangled auth integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.auth/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.auth',
'tangled.auth.tests',
],
install_requires=[
'tangled.web>=0.1a5',
],
extras_require={
'dev': [
'tangled.web[dev]>=0.1a5',
],
},
entry_points="""
[tangled.scripts]
auth = tangled.auth.command:Command
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Add `a` to notTextable option in Canvas
|
module.exports = {
stylePrefix: 'cv-',
/*
* Append external scripts to the `<head>` of the iframe.
* Be aware that these scripts will not be printed in the export code
* @example
* scripts: [ 'https://...1.js', 'https://...2.js' ]
*/
scripts: [],
/*
* Append external styles to the `<head>` of the iframe
* Be aware that these styles will not be printed in the export code
* @example
* styles: [ 'https://...1.css', 'https://...2.css' ]
*/
styles: [],
/**
* Add custom badge naming strategy
* @example
* customBadgeLabel: function(component) {
* return component.getName();
* }
*/
customBadgeLabel: '',
/**
* Indicate when to start the auto scroll of the canvas on component/block dragging (value in px )
*/
autoscrollLimit: 50,
/**
* When some textable component is selected and focused (eg. input or text component) the editor
* stops some commands (eg. disables the copy/paste of components with CTRL+C/V to allow the copy/paste of the text).
* This option allows to customize, by a selector, which element should not be considered textable
*/
notTextable: ['button', 'a', 'input[type=checkbox]', 'input[type=radio]']
};
|
module.exports = {
stylePrefix: 'cv-',
/*
* Append external scripts to the `<head>` of the iframe.
* Be aware that these scripts will not be printed in the export code
* @example
* scripts: [ 'https://...1.js', 'https://...2.js' ]
*/
scripts: [],
/*
* Append external styles to the `<head>` of the iframe
* Be aware that these styles will not be printed in the export code
* @example
* styles: [ 'https://...1.css', 'https://...2.css' ]
*/
styles: [],
/**
* Add custom badge naming strategy
* @example
* customBadgeLabel: function(component) {
* return component.getName();
* }
*/
customBadgeLabel: '',
/**
* Indicate when to start the auto scroll of the canvas on component/block dragging (value in px )
*/
autoscrollLimit: 50,
/**
* When some textable component is selected and focused (eg. input or text component) the editor
* stops some commands (eg. disables the copy/paste of components with CTRL+C/V to allow the copy/paste of the text).
* This option allows to customize, by a selector, which element should not be considered textable
*/
notTextable: ['button', 'input[type=checkbox]', 'input[type=radio]']
};
|
Remove attribute value in textarea html
|
<div class="{{$config['divClass']}} {{$wrapperClass}} @if($errors){{$config['errorClass']}} @endif">
@if($label) <label for="{{$name}}">{!!$label!!} @if($required)<i class="{{$config['requiredClass']}}">*</i>@endif</label>@endif
<textarea
type="{{$type}}"
id="{{$name}}"
name="{{$name}}"
@if($required)required @endif
@if($placeholder)placeholder="{{$placeholder}}"@endif
@foreach($attr as $key => $val)
@if(is_int($key)){{$val}}@else{{$key}}="{{$val}}"@endif
@endforeach
>{{$value}}</textarea>
@if($errors)
<ul class="{{$config['errorMessageClass']}}">
@foreach ($errors as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
</div>
|
<div class="{{$config['divClass']}} {{$wrapperClass}} @if($errors){{$config['errorClass']}} @endif">
@if($label) <label for="{{$name}}">{!!$label!!} @if($required)<i class="{{$config['requiredClass']}}">*</i>@endif</label>@endif
<textarea
type="{{$type}}"
id="{{$name}}"
name="{{$name}}"
@if($value !== null)value="{{$value}}" @endif
@if($required)required @endif
@if($placeholder)placeholder="{{$placeholder}}"@endif
@foreach($attr as $key => $val)
@if(is_int($key)){{$val}}@else{{$key}}="{{$val}}"@endif
@endforeach
>{{$value}}</textarea>
@if($errors)
<ul class="{{$config['errorMessageClass']}}">
@foreach ($errors as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
</div>
|
FIX Use HTTPS protocol in Gravatar URL
|
<?php
/**
* An author who can be linked to several add-ons.
*/
class AddonAuthor extends DataObject
{
public static $db = array(
'Name' => 'Varchar(255)',
'Email' => 'Varchar(255)',
'Homepage' => 'Varchar(255)',
'Role' => 'Varchar(255)'
);
public static $belongs_many_many = array(
'Versions' => 'AddonVersion'
);
public static $default_sort = 'Name';
public function GravatarUrl($size, $default = 'mm')
{
return sprintf(
'https://www.gravatar.com/avatar/%s?s=%d&d=%s',
md5(strtolower(trim($this->Email))),
$size,
$default
);
}
public function Link()
{
return Controller::join_links(Director::baseURL(), 'authors', $this->ID);
}
public function Addons()
{
return Addon::get()->filter('ID', $this->Versions()->column('AddonID'));
}
}
|
<?php
/**
* An author who can be linked to several add-ons.
*/
class AddonAuthor extends DataObject
{
public static $db = array(
'Name' => 'Varchar(255)',
'Email' => 'Varchar(255)',
'Homepage' => 'Varchar(255)',
'Role' => 'Varchar(255)'
);
public static $belongs_many_many = array(
'Versions' => 'AddonVersion'
);
public static $default_sort = 'Name';
public function GravatarUrl($size, $default = 'mm')
{
return sprintf(
'http://www.gravatar.com/avatar/%s?s=%d&d=%s',
md5(strtolower(trim($this->Email))),
$size,
$default
);
}
public function Link()
{
return Controller::join_links(Director::baseURL(), 'authors', $this->ID);
}
public function Addons()
{
return Addon::get()->filter('ID', $this->Versions()->column('AddonID'));
}
}
|
Fix a bug where rez.cli.output() errors when called without args. should produce an empty line of output.
|
'''
Utilities for cli tools
'''
import sys
def error(msg):
'''
An error, formatted and printed to stderr
'''
sys.__stderr__.write("Error: %s\n" % msg)
def output(msg=''):
'''
A result, printed to stdout
'''
sys.__stdout__.write("%s\n" % msg)
def redirect_to_stderr(func):
'''
decorator to redirect output to stderr.
This is useful
'''
def wrapper(*args, **kwargs):
try:
# redirect all print statements to stderr
sys.stdout = sys.stderr
return func(*args, **kwargs)
finally:
sys.stdout = sys.__stdout__
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapper
|
'''
Utilities for cli tools
'''
import sys
def error(msg):
'''
An error, formatted and printed to stderr
'''
sys.__stderr__.write("Error: %s\n" % msg)
def output(msg):
'''
A result, printed to stdout
'''
sys.__stdout__.write("%s\n" % msg)
def redirect_to_stderr(func):
'''
decorator to redirect output to stderr.
This is useful
'''
def wrapper(*args, **kwargs):
try:
# redirect all print statements to stderr
sys.stdout = sys.stderr
return func(*args, **kwargs)
finally:
sys.stdout = sys.__stdout__
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapper
|
Discard 'Forwarded' & 'X-Forwarded-Host' headers.
|
<?php
namespace Rogue\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application,
* sourced from 'config/trustedproxy.php'.
*
* @var array
*/
protected $proxies;
/**
* The current proxy header mappings.
*
* @var array
*/
protected $headers = [
Request::HEADER_FORWARDED => null, // Not set on AWS or Heroku.
Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
Request::HEADER_X_FORWARDED_HOST => null, // Not set on AWS or Heroku.
Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
];
}
|
<?php
namespace Rogue\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application,
* sourced from 'config/trustedproxy.php'.
*
* @var array
*/
protected $proxies;
/**
* The current proxy header mappings.
*
* @var array
*/
protected $headers = [
Request::HEADER_FORWARDED => 'FORWARDED',
Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
];
}
|
Fix a test for class name inflector
|
<?php
namespace League\Tactician\Tests\Handler\MethodNameInflector;
use League\Tactician\Handler\MethodNameInflector\ClassNameInflector;
use League\Tactician\Tests\Fixtures\Command\CompleteTaskCommand;
use League\Tactician\Tests\Fixtures\Handler\ConcreteMethodsHandler;
use CommandWithoutNamespace;
use PHPUnit\Framework\TestCase;
class ClassNameInflectorTest extends TestCase
{
/**
* @var ClassNameInflector
*/
private $inflector;
/**
* @var object
*/
private $mockHandler;
protected function setUp()
{
$this->inflector = new ClassNameInflector();
$this->mockHandler = new ConcreteMethodsHandler();
}
public function testHandlesClassesWithoutNamespace()
{
$command = new CommandWithoutNamespace();
$this->assertEquals(
'commandWithoutNamespace',
$this->inflector->inflect($command, $this->mockHandler)
);
}
public function testHandlesNamespacedClasses()
{
$command = new CompleteTaskCommand();
$this->assertEquals(
'completeTaskCommand',
$this->inflector->inflect($command, $this->mockHandler)
);
}
}
|
<?php
namespace League\Tactician\Tests\Handler\MethodNameInflector;
use League\Tactician\Handler\MethodNameInflector\ClassNameInflector;
use League\Tactician\Tests\Fixtures\Command\CompleteTaskCommand;
use League\Tactician\Tests\Fixtures\Handler\ConcreteMethodsHandler;
use CommandWithoutNamespace;
use PHPUnit\Framework\TestCase;
class ClassNameInflectorTest extends TestCase
{
/**
* @var ClassNameInflector
*/
private $inflector;
/**
* @var object
*/
private $mockHandler;
protected function setUp()
{
$this->inflector = new ClassNameInflector();
$this->handler = new ConcreteMethodsHandler();
}
public function testHandlesClassesWithoutNamespace()
{
$command = new CommandWithoutNamespace();
$this->assertEquals(
'commandWithoutNamespace',
$this->inflector->inflect($command, $this->mockHandler)
);
}
public function testHandlesNamespacedClasses()
{
$command = new CompleteTaskCommand();
$this->assertEquals(
'completeTaskCommand',
$this->inflector->inflect($command, $this->mockHandler)
);
}
}
|
Update determine association type method
|
package uk.ac.ebi.spot.goci.service;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.ValidationError;
import java.util.Collection;
/**
* Created by emma on 01/04/2016.
*
* @author emma
* <p>
* Interface that defines method(s) to run error ckecking of an association and then return a collection of
* errors.
*/
public interface AssociationCheckingService {
Collection<ValidationError> runChecks(Association association, ValidationChecksBuilder validationChecksBuilder);
/**
* Check if association is an OR or BETA type association
*
* @param association Association to check
*/
default String determineIfAssociationIsOrType(Association association) {
String effectType = "none";
if (association.getOrPerCopyNum() != null) {
effectType = "or";
}
else {
if (association.getBetaNum() != null) {
effectType = "beta";
}
}
return effectType;
}
}
|
package uk.ac.ebi.spot.goci.service;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.ValidationError;
import java.util.Collection;
/**
* Created by emma on 01/04/2016.
*
* @author emma
* <p>
* Interface that defines method(s) to run error ckecking of an association and then return a collection of
* errors.
*/
public interface AssociationCheckingService {
Collection<ValidationError> runChecks(Association association, ValidationChecksBuilder validationChecksBuilder);
/**
* Check if association is an OR or BETA type association
*
* @param association Association to check
*/
default String determineIfAssociationIsOrType(Association association) {
String effectType = "none";
if (association.getBetaNum() != null) {
effectType = "beta";
}
else {
if (association.getOrPerCopyNum() != null) {
effectType = "or";
}
}
return effectType;
}
}
|
Add warning about mime types
|
<?php
return [
'name' => [
'name' => 'Name'
],
'slug' => [
'name' => 'Slug'
],
'size' => [
'name' => 'Size'
],
'disk' => [
'name' => 'Disk'
],
'folder' => [
'name' => 'Folder'
],
'adapter' => [
'name' => 'Adapter'
],
'keywords' => [
'name' => 'Keywords'
],
'mime_type' => [
'name' => 'Mime Type'
],
'preview' => [
'name' => 'Preview'
],
'description' => [
'name' => 'Description'
],
'allowed_types' => [
'name' => 'Allowed Types',
'instructions' => 'Specify the file type extensions that are allowed in this folder.',
'warning' => 'Note subtle differences between mime types like jpg and jpeg.',
'placeholder' => 'pdf, psd, jpg, jpeg'
]
];
|
<?php
return [
'name' => [
'name' => 'Name'
],
'slug' => [
'name' => 'Slug'
],
'size' => [
'name' => 'Size'
],
'disk' => [
'name' => 'Disk'
],
'folder' => [
'name' => 'Folder'
],
'adapter' => [
'name' => 'Adapter'
],
'keywords' => [
'name' => 'Keywords'
],
'mime_type' => [
'name' => 'Mime Type'
],
'preview' => [
'name' => 'Preview'
],
'description' => [
'name' => 'Description'
],
'allowed_types' => [
'name' => 'Allowed Types',
'instructions' => 'Specify the file type extensions that are allowed in this folder.',
'placeholder' => 'pdf, psd, jpg'
]
];
|
[ENHANCE] Add precision in generate-db-schema's messages.
|
<?php
namespace Change\Commands;
use Change\Commands\Events\Event;
/**
* @name \Change\Commands\GenerateDbSchema
*/
class GenerateDbSchema
{
/**
* @param Event $event
*/
public function execute(Event $event)
{
$application = $event->getApplication();
$applicationServices = new \Change\Application\ApplicationServices($application);
$generator = new \Change\Db\Schema\Generator($application->getWorkspace(), $applicationServices->getDbProvider());
try
{
if ($event->getParam('with-modules'))
{
$generator->generate();
$event->addInfoMessage('Change and Modules DB schema generated.');
}
else
{
$generator->generateSystemSchema();
$event->addInfoMessage('Change DB schema generated (to generate Modules DB schema, add -m option).');
}
}
catch (\Exception $e )
{
$applicationServices->getLogging()->exception($e);
$event->addErrorMessage($e->getMessage());
}
}
}
|
<?php
namespace Change\Commands;
use Change\Commands\Events\Event;
/**
* @name \Change\Commands\GenerateDbSchema
*/
class GenerateDbSchema
{
/**
* @param Event $event
*/
public function execute(Event $event)
{
$application = $event->getApplication();
$applicationServices = new \Change\Application\ApplicationServices($application);
$generator = new \Change\Db\Schema\Generator($application->getWorkspace(), $applicationServices->getDbProvider());
try
{
if ($event->getParam('with-modules'))
{
$generator->generate();
$event->addInfoMessage('Change and Modules Db schema generated.');
}
else
{
$generator->generateSystemSchema();
$event->addInfoMessage('Change Db schema generated.');
}
}
catch (\Exception $e )
{
$applicationServices->getLogging()->exception($e);
$event->addErrorMessage($e->getMessage());
}
}
}
|
Convert adsConversionID setting for GA4 to placeholder.
|
/**
* `modules/analytics-4` base data store
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import Modules from 'googlesitekit-modules';
import { STORE_NAME } from './constants';
const baseModuleStore = Modules.createModuleStore( 'analytics-4', {
storeName: STORE_NAME,
settingSlugs: [
// TODO: These can be uncommented when Analytics and Analytics 4 modules are officially separated.
// 'accountID',
// 'adsConversionID',
'propertyID',
'webDataStreamID',
'measurementID',
'useSnippet',
],
} );
export default baseModuleStore;
|
/**
* `modules/analytics-4` base data store
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* Internal dependencies
*/
import Modules from 'googlesitekit-modules';
import { STORE_NAME } from './constants';
const baseModuleStore = Modules.createModuleStore( 'analytics-4', {
storeName: STORE_NAME,
settingSlugs: [
// TODO: This can be uncommented when Analytics and Analytics 4 modules are officially separated.
// 'accountID',
'adsConversionID',
'propertyID',
'webDataStreamID',
'measurementID',
'useSnippet',
],
} );
export default baseModuleStore;
|
Make it a GET form, with a single simple param
|
<?php
include('lib/panda.php');
include('lib/config.inc.php');
include('lib/head.inc.html');
?>
<p>This is an example <strong>Panda</strong> client application, written in <strong>PHP</strong>.</p>
<form action="/player.php" method="get" id="upload-form">
<label>Upload a video<br/></label>
<span id="spanButtonPlaceholder"></span>
<input type="text" id="txtFileName" disabled="true" style="border: solid 1px; background-color: #FFFFFF;" />
<div class="flash" id="progress_bar_container"></div>
<input name="video_id" type="hidden" id="video_panda_id" />
<script type="text/javascript">
PandaUploader.init(<?php echo json_encode(@$panda->signed_params("POST", "/videos.json", array())); ?>, {"api_host": '<?php echo $panda->api_host; ?>', "final_file_field_id": "video_panda_id", "form_id": "upload-form"}, {"debug": true, "flash_url": "/flash/swfupload.swf"});
</script>
<p><input type="submit" value="Save" id="btnSubmit" /></p>
</form>
<?php include('lib/foot.inc.html'); ?>
|
<?php
include('lib/panda.php');
include('lib/config.inc.php');
include('lib/head.inc.html');
?>
<p>This is an example <strong>Panda</strong> client application, written in <strong>PHP</strong>.</p>
<form action="/" method="post" id="upload-form">
<label>Upload a video<br/></label>
<span id="spanButtonPlaceholder"></span>
<input type="text" id="txtFileName" disabled="true" style="border: solid 1px; background-color: #FFFFFF;" />
<div class="flash" id="progress_bar_container"></div>
<input name="video[panda_id]" type="hidden" id="video_panda_id" />
<script type="text/javascript">
PandaUploader.init(<?php echo json_encode(@$panda->signed_params("POST", "/videos.json", array())); ?>, {"api_host": '<?php echo $panda->api_host; ?>', "final_file_field_id": "video_panda_id", "form_id": "upload-form"}, {"debug": true, "flash_url": "/flash/swfupload.swf"});
</script>
<p><input type="submit" value="Save" id="btnSubmit" /></p>
</form>
<?php include('lib/foot.inc.html'); ?>
|
Fix Overscroll when we're using Mode.BOTH
|
package com.handmark.pulltorefresh.library;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
final class OverscrollHelper {
static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
final Mode mode = view.getMode();
if (mode != Mode.DISABLED && !isTouchEvent) {
final int newY = (deltaY + scrollY);
if (newY != 0) {
// Check the mode supports the overscroll direction, and
// then move scroll
if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
view.setHeaderScroll(view.getScrollY() + newY);
}
} else {
// Means we've stopped overscrolling, so scroll back to 0
view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
}
}
}
}
|
package com.handmark.pulltorefresh.library;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
final class OverscrollHelper {
static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
final Mode mode = view.getCurrentMode();
if (mode != Mode.DISABLED && !isTouchEvent) {
final int newY = (deltaY + scrollY);
if (newY != 0) {
// Check the mode supports the overscroll direction, and
// then move scroll
if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
view.setHeaderScroll(view.getScrollY() + newY);
}
} else {
// Means we've stopped overscrolling, so scroll back to 0
view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
}
}
}
}
|
Enable translations for Contact fields
Closes #387
|
<?php
/**
* Configuration
*
*/
Configure::write('Translate.models', array(
'Node' => array(
'fields' => array(
'title' => 'titleTranslation',
'excerpt' => 'excerptTranslation',
'body' => 'bodyTranslation',
),
'translateModel' => 'Nodes.Node',
),
'Block' => array(
'fields' => array(
'title' => 'titleTranslation',
'body' => 'bodyTranslation',
),
'translateModel' => 'Blocks.Block',
),
'Contact' => array(
'fields' => array(
'title' => 'titleTranslation',
'body' => 'bodyTranslation',
),
'translateModel' => 'Contacts.Contact',
),
'Link' => array(
'fields' => array(
'title' => 'titleTranslation',
'description' => 'descriptionTranslation',
),
'translateModel' => 'Menus.Link',
),
));
/**
* Do not edit below this line unless you know what you are doing.
*
*/
foreach (Configure::read('Translate.models') as $translateModel => $config) {
Croogo::hookBehavior($translateModel, 'Translate.CroogoTranslate', $config);
Croogo::hookAdminRowAction(Inflector::pluralize($translateModel) . '/admin_index', 'Translate', 'admin:true/plugin:translate/controller:translate/action:index/:id/' . $translateModel);
}
|
<?php
/**
* Configuration
*
*/
Configure::write('Translate.models', array(
'Node' => array(
'fields' => array(
'title' => 'titleTranslation',
'excerpt' => 'excerptTranslation',
'body' => 'bodyTranslation',
),
'translateModel' => 'Nodes.Node',
),
'Block' => array(
'fields' => array(
'title' => 'titleTranslation',
'body' => 'bodyTranslation',
),
'translateModel' => 'Blocks.Block',
),
'Link' => array(
'fields' => array(
'title' => 'titleTranslation',
'description' => 'descriptionTranslation',
),
'translateModel' => 'Menus.Link',
),
));
/**
* Do not edit below this line unless you know what you are doing.
*
*/
foreach (Configure::read('Translate.models') as $translateModel => $config) {
Croogo::hookBehavior($translateModel, 'Translate.CroogoTranslate', $config);
Croogo::hookAdminRowAction(Inflector::pluralize($translateModel) . '/admin_index', 'Translate', 'admin:true/plugin:translate/controller:translate/action:index/:id/' . $translateModel);
}
|
Increment version (to fix dependencies)
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.1.1',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'parserutils>=1.1', 'six>=1.9.0'
],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.1',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'parserutils>=1.1', 'six>=1.9.0'
],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
Add full body text to RSS
|
from django.contrib.syndication.views import Feed
from .models import Post
from .settings import (
SYNDICATION_FEED_TITLE, SYNDICATION_FEED_LINK,
SYNDICATION_FEED_DESCRIPTION, SYNDICATION_FEED_TYPE
)
class LatestPostFeed(Feed):
title = SYNDICATION_FEED_TITLE
link = SYNDICATION_FEED_LINK
description = SYNDICATION_FEED_DESCRIPTION
feed_type = SYNDICATION_FEED_TYPE
def items(self):
return Post.objects.recent()
def item_title(self, item):
return item.subject
def item_description(self, item):
return item.rendered
def item_pubdate(self, item):
return item.created_on
def item_updateddate(self, item):
return item.modified_on
def item_categories(self, item):
return [category.title for category in item.category.hierarchy()]
def item_author_name(self, item):
return "{first_name} {last_name}".format(
first_name=item.author.first_name,
last_name=item.author.last_name,
)
def item_author_email(self, item):
return item.author.email
|
from django.contrib.syndication.views import Feed
from .models import Post
from .settings import (
SYNDICATION_FEED_TITLE, SYNDICATION_FEED_LINK,
SYNDICATION_FEED_DESCRIPTION, SYNDICATION_FEED_TYPE
)
class LatestPostFeed(Feed):
title = SYNDICATION_FEED_TITLE
link = SYNDICATION_FEED_LINK
description = SYNDICATION_FEED_DESCRIPTION
feed_type = SYNDICATION_FEED_TYPE
def items(self):
return Post.objects.recent()
def item_title(self, item):
return item.subject
def item_description(self, item):
return item.short
def item_pubdate(self, item):
return item.created_on
def item_updateddate(self, item):
return item.modified_on
def item_categories(self, item):
return [category.title for category in item.category.hierarchy()]
def item_author_name(self, item):
return "{first_name} {last_name}".format(
first_name=item.author.first_name,
last_name=item.author.last_name,
)
def item_author_email(self, item):
return item.author.email
|
Use simpler test API for performing actions
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python;
import com.intellij.openapi.actionSystem.IdeActions;
import com.jetbrains.python.fixtures.PyTestCase;
/**
* @author yole
*/
public class PyCommenterTest extends PyTestCase {
public void testIndentedComment() {
doTest();
}
public void testUncommentWithoutSpace() {
doTest();
}
private void doTest() {
myFixture.configureByFile("commenter/" + getTestName(true) + ".py");
myFixture.performEditorAction(IdeActions.ACTION_COMMENT_LINE);
myFixture.checkResultByFile("commenter/" + getTestName(true) + "_after.py", true);
}
}
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python;
import com.intellij.codeInsight.actions.MultiCaretCodeInsightAction;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.jetbrains.python.fixtures.PyTestCase;
/**
* @author yole
*/
public class PyCommenterTest extends PyTestCase {
public void testIndentedComment() {
doTest();
}
public void testUncommentWithoutSpace() {
doTest();
}
private void doTest() {
myFixture.configureByFile("commenter/" + getTestName(true) + ".py");
MultiCaretCodeInsightAction action = (MultiCaretCodeInsightAction) ActionManager.getInstance().getAction(IdeActions.ACTION_COMMENT_LINE);
action.actionPerformedImpl(myFixture.getFile().getProject(), myFixture.getEditor());
myFixture.checkResultByFile("commenter/" + getTestName(true) + "_after.py", true);
}
}
|
Use get_or_create instead of just create
|
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address, __ = self.get_or_create(user=user, email=email, default=kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
|
from __future__ import unicode_literals
from django.db import models
class EmailAddressManager(models.Manager):
def add_email(self, user, email, **kwargs):
confirm = kwargs.pop("confirm", False)
email_address = self.create(user=user, email=email, **kwargs)
if confirm and not email_address.verified:
email_address.send_confirmation()
return email_address
def get_primary(self, user):
try:
return self.get(user=user, primary=True)
except self.model.DoesNotExist:
return None
def get_users_for(self, email):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True, email=email)]
class EmailConfirmationManager(models.Manager):
def delete_expired_confirmations(self):
for confirmation in self.all():
if confirmation.key_expired():
confirmation.delete()
|
Configure Freemarker to UTF-8 by default
|
package com.otogami.freemarker.config;
import javax.inject.Inject;
import javax.inject.Provider;
import com.otogami.freemarker.GlobalVariables;
import com.otogami.freemarker.MacroRegister;
import com.otogami.freemarker.viewlet.ViewletFactory;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
public class DefaultConfigurationProvider implements Provider<Configuration> {
@Inject
private GlobalVariables globalVariables;
@Inject
private ViewletFactory viewletFactory;
@Inject
private FunsteroidMacrosRegister funsteroidMacrosRegister;
@Inject
private MacroRegister macroRegister;
@Override
public Configuration get() {
FunsteroidFreemarkerConfiguration cfg = new FunsteroidFreemarkerConfiguration(globalVariables, funsteroidMacrosRegister, viewletFactory);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
cfg.setNumberFormat("0");
cfg.setDefaultEncoding("UTF-8");
cfg.setClassForTemplateLoading(getClass(), "/tpl");
if (macroRegister!=null) {
macroRegister.accept(cfg);
}
return cfg;
}
}
|
package com.otogami.freemarker.config;
import javax.inject.Inject;
import javax.inject.Provider;
import com.otogami.freemarker.GlobalVariables;
import com.otogami.freemarker.MacroRegister;
import com.otogami.freemarker.viewlet.ViewletFactory;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
public class DefaultConfigurationProvider implements Provider<Configuration> {
@Inject
private GlobalVariables globalVariables;
@Inject
private ViewletFactory viewletFactory;
@Inject
private FunsteroidMacrosRegister funsteroidMacrosRegister;
@Inject
private MacroRegister macroRegister;
@Override
public Configuration get() {
FunsteroidFreemarkerConfiguration cfg = new FunsteroidFreemarkerConfiguration(globalVariables, funsteroidMacrosRegister, viewletFactory);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
cfg.setNumberFormat("0");
cfg.setClassForTemplateLoading(getClass(), "/tpl");
if (macroRegister!=null) {
macroRegister.accept(cfg);
}
return cfg;
}
}
|
Check for errors in config
|
"""manages github repos"""
import os
import tempfile
from typing import Dict, Any
import pygit2 as git
from .webhook.handler import Handler
class Manager(object):
"""handles git repos"""
def __init__(self: Manager, handler: Handler) -> None:
self.webhook_handler: Handler = handler
self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory()
self.repo: git.Repository = git.clone_repository(
self.webhook_handler.git_url, path=self.temp_dir.name)
with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config:
import json
try:
self.config: Dict[str, Any] = json.loads(config.read())["css_updater"]
except KeyError as invalid_json:
print(invalid_json)
except IOError as io_error:
print(io_error)
def __del__(self: Manager) -> None:
self.temp_dir.cleanup()
|
"""manages github repos"""
import os
import tempfile
from typing import Dict, Any
import pygit2 as git
from .webhook.handler import Handler
class Manager(object):
"""handles git repos"""
def __init__(self: Manager, handler: Handler) -> None:
self.webhook_handler: Handler = handler
self.temp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory()
self.repo: git.Repository = git.clone_repository(
self.webhook_handler.git_url, path=self.temp_dir.name)
with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config:
import json
self.config: Dict[str, Any] = json.loads(config.read())
def __del__(self: Manager) -> None:
self.temp_dir.cleanup()
|
Prepend assets dict keys with './' to match filenames in XML
PiperOrigin-RevId: 189602660
|
# Copyright 2017 The dm_control 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.
# ============================================================================
"""Functions to manage the common assets for domains."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from dm_control.utils import io as resources
_SUITE_DIR = os.path.dirname(os.path.dirname(__file__))
_FILENAMES = [
"./common/materials.xml",
"./common/skybox.xml",
"./common/visual.xml",
]
ASSETS = {filename: resources.GetResource(os.path.join(_SUITE_DIR, filename))
for filename in _FILENAMES}
def read_model(model_filename):
"""Reads a model XML file and returns its contents as a string."""
return resources.GetResource(os.path.join(_SUITE_DIR, model_filename))
|
# Copyright 2017 The dm_control 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.
# ============================================================================
"""Functions to manage the common assets for domains."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from dm_control.utils import io as resources
_SUITE_DIR = os.path.dirname(os.path.dirname(__file__))
_FILENAMES = [
"common/materials.xml",
"common/skybox.xml",
"common/visual.xml",
]
ASSETS = {filename: resources.GetResource(os.path.join(_SUITE_DIR, filename))
for filename in _FILENAMES}
def read_model(model_filename):
"""Reads a model XML file and returns its contents as a string."""
return resources.GetResource(os.path.join(_SUITE_DIR, model_filename))
|
Add condition if XDebug is not loaded
|
<?php
declare(strict_types=1);
namespace Mihaeu\PhpDependencies\Cli;
use Symfony\Component\Console\Input\Input;
use Symfony\Component\Console\Output\Output;
/**
* @covers Mihaeu\PhpDependencies\Cli\Application
*/
class ApplicationTest extends \PHPUnit_Framework_TestCase
{
public function testSetMemoryLimit()
{
$app = new Application();
$input = $this->createMock(Input::class);
$input->method('hasOption')->willReturn(true);
$input->method('getOption')->willReturn('1234M');
$output = $this->createMock(Output::class);
$app->doRun($input, $output);
$this->assertEquals('1234M', ini_get('memory_limit'));
}
public function testWarningIfXDebugEnabled()
{
$app = new Application();
$input = $this->createMock(Input::class);
$output = $this->createMock(Output::class);
// not sure how to mock this, so we test only one case
if (!extension_loaded('xdebug')) {
$output->expects($this->never())->method('writeln');
} else {
$output->expects($this->once())->method('writeln');
}
$app->doRun($input, $output);
}
}
|
<?php
declare(strict_types=1);
namespace Mihaeu\PhpDependencies\Cli;
use Symfony\Component\Console\Input\Input;
use Symfony\Component\Console\Output\Output;
/**
* @covers Mihaeu\PhpDependencies\Cli\Application
*/
class ApplicationTest extends \PHPUnit_Framework_TestCase
{
public function testSetMemoryLimit()
{
$app = new Application();
$input = $this->createMock(Input::class);
$input->method('hasOption')->willReturn(true);
$input->method('getOption')->willReturn('1234M');
$output = $this->createMock(Output::class);
$app->doRun($input, $output);
$this->assertEquals('1234M', ini_get('memory_limit'));
}
public function testWarningIfXDebugEnabled()
{
$app = new Application();
$input = $this->createMock(Input::class);
$output = $this->createMock(Output::class);
$output->expects($this->once())->method('writeln');
$app->doRun($input, $output);
}
}
|
Fix resource factory to reflect ErrorCollection constructor
|
<?php
namespace Refinery29\ApiOutput\Resource;
use Refinery29\ApiOutput\Resource\Error\Error;
use Refinery29\ApiOutput\Resource\Error\ErrorCollection;
use Refinery29\ApiOutput\Resource\Link\LinkCollection;
abstract class ResourceFactory
{
/**
* @param array $data
*
* @return Result
*/
public static function result(array $data)
{
return new Result($data);
}
/**
* @param array $errors
* @return ErrorCollection
*/
public static function errorCollection(array $errors = [])
{
return new ErrorCollection($errors);
}
/**
* @param string $title
* @param string $code
*
* @return Error
*/
public static function error($title, $code)
{
return new Error($title, $code);
}
/**
* @return LinkCollection
*/
public static function linkCollection()
{
return new LinkCollection();
}
}
|
<?php
namespace Refinery29\ApiOutput\Resource;
use Refinery29\ApiOutput\Resource\Error\Error;
use Refinery29\ApiOutput\Resource\Error\ErrorCollection;
use Refinery29\ApiOutput\Resource\Link\LinkCollection;
abstract class ResourceFactory
{
/**
* @param array $data
*
* @return Result
*/
public static function result(array $data)
{
return new Result($data);
}
/**
* @return ErrorCollection
*/
public static function errorCollection()
{
return new ErrorCollection();
}
/**
* @param string $title
* @param string $code
*
* @return Error
*/
public static function error($title, $code)
{
return new Error($title, $code);
}
/**
* @return LinkCollection
*/
public static function linkCollection()
{
return new LinkCollection();
}
}
|
Remove --harmony_symbols, Symbol works without a flag
|
'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
// '--harmony_proxies', // `new Proxy({}, {})` throws
'--harmony_generators',
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
|
'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
'--harmony_symbols', // `Symbol('s')` throws
// '--harmony_proxies', // `new Proxy({}, {})` throws
'--harmony_generators',
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
|
Change log archive to none
Logs should be retained for 24 hours and deleted. Previous retention
setting of "zip" unintentionally retained logs in a zip file internal to
the container, causing increased CPU load, memory, and disk usage
related to hourly rotation.
|
// Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 logger
func loggerConfig() string {
config := `
<seelog type="asyncloop" minlevel="` + level + `">
<outputs formatid="main">
<console />`
if logfile != "" {
config += `<rollingfile filename="` + logfile + `" type="date"
datepattern="2006-01-02-15" archivetype="none" maxrolls="24" />`
}
config += `
</outputs>
<formats>
<format id="main" format="%UTCDate(2006-01-02T15:04:05Z07:00) [%LEVEL] %Msg%n" />
</formats>
</seelog>
`
return config
}
|
// Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 logger
func loggerConfig() string {
config := `
<seelog type="asyncloop" minlevel="` + level + `">
<outputs formatid="main">
<console />`
if logfile != "" {
config += `<rollingfile filename="` + logfile + `" type="date"
datepattern="2006-01-02-15" archivetype="zip" maxrolls="5" />`
}
config += `
</outputs>
<formats>
<format id="main" format="%UTCDate(2006-01-02T15:04:05Z07:00) [%LEVEL] %Msg%n" />
</formats>
</seelog>
`
return config
}
|
Add in the timestamp for each message, to enable tracking of how long problems take to resolve
|
import sys
import os
import inspect
import time
def __LINE__ ():
caller = inspect.stack()[1]
return int (caller[2])
def __FUNC__ ():
caller = inspect.stack()[1]
return caller[3]
def __BOTH__():
caller = inspect.stack()[1]
return int (caller[2]), caller[3], caller[1]
def Print(*args):
caller = inspect.stack()[1]
filename = str(os.path.basename(caller[1]))
sys.stdout.write(filename+ " : "+ str(int (caller[2])) + " : ")
sys.stdout.write(str(time.time()) + " : ")
for arg in args:
try:
x = str(arg)
except:
pass
try:
print x,
except:
try:
print unicode(x, errors="ignore"),
except:
try:
sys.stdout.write(arg.encode("ascii","ignore"))
except:
print "FAILED PRINT"
print
sys.stdout.flush()
|
import sys
import os
import inspect
def __LINE__ ():
caller = inspect.stack()[1]
return int (caller[2])
def __FUNC__ ():
caller = inspect.stack()[1]
return caller[3]
def __BOTH__():
caller = inspect.stack()[1]
return int (caller[2]), caller[3], caller[1]
def Print(*args):
caller = inspect.stack()[1]
filename = str(os.path.basename(caller[1]))
sys.stdout.write(filename+ " : "+ str(int (caller[2])) + " : ")
for arg in args:
try:
x = str(arg)
except:
pass
try:
print x,
except:
try:
print unicode(x, errors="ignore"),
except:
try:
sys.stdout.write(arg.encode("ascii","ignore"))
except:
print "FAILED PRINT"
print
sys.stdout.flush()
|
Remove invalid argument of channel.info method
|
.import "../applicationShared.js" as Globals
function workerOnMessage(messageObject) {
if(messageObject.apiMethod === 'channels.history') {
addMessagesToModel(messageObject.data);
} else if(messageObject.apiMethod === 'channels.info') {
addChannelInfoToPage(messageObject.data);
} else {
console.log("Unknown api method");
}
}
function loadChannelInfo() {
var arguments = {
channel: channelPage.channelID
}
slackWorker.sendMessage({'apiMethod': "channels.info", 'token': Globals.slackToken, 'arguments': arguments });
}
function loadChannelHistory() {
slackWorker.sendMessage({'apiMethod': "channels.history", 'token': Globals.slackToken});
}
// private
function addMessagesToModel(data) {
for(var i=0; i<data.messages.length; i++) {
channelList.append(data.messages[i]);
}
}
function addChannelInfoToPage(data) {
channelPage.channelPurpose = data.channel.purpose.value;
}
|
.import "../applicationShared.js" as Globals
function workerOnMessage(messageObject) {
if(messageObject.apiMethod === 'channels.history') {
addMessagesToModel(messageObject.data);
} else if(messageObject.apiMethod === 'channels.info') {
addChannelInfoToPage(messageObject.data);
} else {
console.log("Unknown api method");
}
}
function loadChannelInfo() {
var arguments = {
channel: channelPage.channelID,
count: 42
}
slackWorker.sendMessage({'apiMethod': "channels.info", 'token': Globals.slackToken, 'arguments': arguments });
}
function loadChannelHistory() {
slackWorker.sendMessage({'apiMethod': "channels.history", 'token': Globals.slackToken});
}
// private
function addMessagesToModel(data) {
for(var i=0; i<data.messages.length; i++) {
channelList.append(data.messages[i]);
}
}
function addChannelInfoToPage(data) {
channelPage.channelPurpose = data.channel.purpose.value;
}
|
Update UI init method to accept selector.
|
/*
* Mushpup-UI Module
*
* Requires jQuery, jQuery-UI
*
*/
var MushpupUI = (function() {
var VERSION = '2.0';
var init = function(selector) {
var $selectedElement = $(selector);
var $mushpupInterface = buildInterface();
$selectedElement.append($mushpupInterface);
enableHandlers($selectedElement);
};
var buildInterface = function() {
var $mushpupInterface = $('<div class="mushpup" />');
var $inputPanel = buildInputPanel();
var $actionPanel = buildActionPanel();
var $outputPanel = buildOutputPanel();
$mushpupInterface
.append($inputPanel)
.append($actionPanel)
.append($outputPanel);
return $mushpupInterface;
};
var enableHandlers = function() {
};
// DOM Builders
var buildInputPanel = function() {
};
var buildActionPanel = function() {
};
var buildOutputPanel = function() {
};
/*
* Public Interface
*/
var API = {
init: init,
version: function() { return VERSION; }
};
return API;
});
|
/*
* Mushpup-UI Module
*
* Requires jQuery, jQuery-UI
*
*/
var MushpupUI = (function() {
var VERSION = '2.0';
var init = function(parentId) {
var $parentElement = $('#' + parentId);
var $mushpupInterface = buildInterface();
$parentElement.append(mushpupInterface);
enableHandlers($parentElement);
};
var buildInterface = function() {
var $mushpupInterface = $('<div class="mushpup" />');
var $inputPanel = buildInputPanel();
var $actionPanel = buildActionPanel();
var $outputPanel = buildOutputPanel();
$mushpupInterface
.append($inputPanel)
.append($actionPanel)
.append($outputPanel);
return $mushpupInterface;
};
var enableHandlers = function() {
};
// DOM Builders
var buildInputPanel = function() {
};
var buildActionPanel = function() {
};
var buildOutputPanel = function() {
};
/*
* Public Interface
*/
var API = {
init: init,
version: function() { return VERSION; }
};
return API;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.