text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use destructuring instead of merge for childrenWithDefaults
|
import React, { Children } from "react";
import resolveCellDefaults from "./resolve-cell-defaults";
import resolveColumnCounts from "./resolve-column-counts";
import resolveCellStyles from "./resolve-cell-styles";
const resolveCells = (props) => {
// Resolve the final style defaults for each cell
const {children, style, ...childProps } = props; // eslint-disable-line no-unused-vars
const childrenWithDefaults = Children.map(
props.children, (child) => {
return React.cloneElement(child, resolveCellDefaults(
{...childProps, ...child.props})
);
}
);
// Add column counts to each cell's props
const childrenWithColumnCounts = resolveColumnCounts({
children: childrenWithDefaults,
breakpoints: props.breakpoints
});
// Resolve the final cell styles
return Children.map(childrenWithColumnCounts, (child) => {
return React.cloneElement(child, {
style: resolveCellStyles(child.props)
});
});
};
export default resolveCells;
|
import React, { Children } from "react";
import merge from "lodash.merge";
import resolveCellDefaults from "./resolve-cell-defaults";
import resolveColumnCounts from "./resolve-column-counts";
import resolveCellStyles from "./resolve-cell-styles";
const resolveCells = (props) => {
// Resolve the final style defaults for each cell
const {children, style, ...childProps } = props; // eslint-disable-line no-unused-vars
const childrenWithDefaults = Children.map(
props.children, (child) => {
return React.cloneElement(child, resolveCellDefaults(
merge({}, childProps, child.props)
));
}
);
// Add column counts to each cell's props
const childrenWithColumnCounts = resolveColumnCounts({
children: childrenWithDefaults,
breakpoints: props.breakpoints
});
// Resolve the final cell styles
return Children.map(childrenWithColumnCounts, (child) => {
return React.cloneElement(child, {
style: resolveCellStyles(child.props)
});
});
};
export default resolveCells;
|
Simplify description and MANIFEST.in suits me fine.
|
from setuptools import setup, find_packages
setup(name='django-forge',
version=__import__('forge').__version__,
author='Justin Bronn',
author_email='jbronn@gmail.com',
description='A Django implementation of the Puppet Forge API.',
url='https://github.com/jbronn/django-forge',
download_url='http://pypi.python.org/pypi/django-forge/',
install_requires=[
'Django>=1.4',
'requests>=2',
'semantic_version>=2.1.2',
],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
],
)
|
from setuptools import setup, find_packages
setup(name='django-forge',
version=__import__('forge').__version__,
author='Justin Bronn',
author_email='jbronn@gmail.com',
description='A Django implementation of the Puppet Forge web API.',
url='https://github.com/jbronn/django-forge',
download_url='http://pypi.python.org/pypi/django-forge/',
install_requires=[
'Django>=1.4',
'requests>=2',
'semantic_version>=2.1.2',
],
packages=find_packages(),
package_data={'apache': ['forge/apache'],
'templates': ['forge/templates']},
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
],
)
|
Order character listing by name
|
from django.shortcuts import get_object_or_404, redirect, render
from django.views import generic
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
class CharacterIndexView(generic.ListView):
template_name = 'characters/index.html'
context_object_name = 'all_characters' # better than 'object_list'
def get_queryset(self):
return Character.objects.all().order_by('name')
class CharacterDetailView(generic.DetailView):
model = Character
template_name = 'characters/view_character.html'
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race_id=1,
cclass_id=1
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
|
from django.shortcuts import get_object_or_404, redirect, render
from django.views import generic
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
class CharacterIndexView(generic.ListView):
template_name = 'characters/index.html'
context_object_name = 'all_characters' # better than 'object_list'
def get_queryset(self):
return Character.objects.all()
class CharacterDetailView(generic.DetailView):
model = Character
template_name = 'characters/view_character.html'
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race_id=1,
cclass_id=1
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
|
Add back models and data
|
from setuptools import setup, find_packages
install_requires = [
'dill==0.2.5',
'easydict==1.6',
'h5py==2.6.0',
'jsonpickle==0.9.3',
'Keras==1.2.0',
'nflgame==1.2.20',
'numpy==1.11.2',
'pandas==0.19.1',
'scikit-learn==0.18.1',
'scipy==0.18.1',
'tensorflow==0.12.0rc1',
'Theano==0.8.2',
]
with open('README.md', 'r') as f:
readme = f.read()
setup(
name="wincast",
version='0.0.1',
url='https://github.com/kahnjw/wincast',
author_email='thomas.welfley+djproxy@gmail.com',
long_description=readme,
license='MIT',
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=install_requires,
data_files=[
('models', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']),
('data', ['data/Xy.csv'])
]
)
|
from setuptools import setup, find_packages
install_requires = [
'dill==0.2.5',
'easydict==1.6',
'h5py==2.6.0',
'jsonpickle==0.9.3',
'Keras==1.2.0',
'nflgame==1.2.20',
'numpy==1.11.2',
'pandas==0.19.1',
'scikit-learn==0.18.1',
'scipy==0.18.1',
'tensorflow==0.12.0rc1',
'Theano==0.8.2',
]
with open('README.md', 'r') as f:
readme = f.read()
setup(
name="wincast",
version='0.0.1',
url='https://github.com/kahnjw/wincast',
author_email='thomas.welfley+djproxy@gmail.com',
long_description=readme,
license='MIT',
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=install_requires,
data_files=[
('', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']),
('', ['data/Xy.csv'])
]
)
|
Update list of dead trackers
|
package uploadService
import (
"strings"
)
func CheckTrackers(trackers []string) bool {
// TODO: move to runtime configuration
var deadTrackers = []string{ // substring matches!
"://open.nyaatorrents.info:6544",
"://tracker.openbittorrent.com:80",
"://tracker.publicbt.com:80",
"://stats.anisource.net:2710",
"://exodus.desync.com",
"://open.demonii.com:1337",
"://tracker.istole.it:80",
"://tracker.ccc.de:80",
"://bt2.careland.com.cn:6969",
"://announce.torrentsmd.com:8080",
"://open.demonii.com:1337",
"://tracker.btcake.com",
"://tracker.prq.to",
"://bt.rghost.net"}
var numGood int
for _, t := range trackers {
good := true
for _, check := range deadTrackers {
if strings.Contains(t, check) {
good = false
}
}
if good {
numGood++
}
}
return numGood > 0
}
|
package uploadService
import (
"strings"
)
func CheckTrackers(trackers []string) bool {
// TODO: move to runtime configuration
var deadTrackers = []string{ // substring matches!
"://open.nyaatorrents.info:6544",
"://tracker.openbittorrent.com:80",
"://tracker.publicbt.com:80",
"://stats.anisource.net:2710",
"://exodus.desync.com",
"://open.demonii.com:1337",
"://tracker.istole.it:80",
"://tracker.ccc.de:80",
"://bt2.careland.com.cn:6969",
"://announce.torrentsmd.com:8080"}
var numGood int
for _, t := range trackers {
good := true
for _, check := range deadTrackers {
if strings.Contains(t, check) {
good = false
}
}
if good {
numGood++
}
}
return numGood > 0
}
|
Update test for GWT 2.8
|
package ol.geom;
import ol.Coordinate;
import ol.GwtOL3BaseTestCase;
import ol.OLFactory;
/**
* A test case for {@link GeometryCollection}.
*
* @author sbaumhekel
*/
public class GeometryCollectionTest extends GwtOL3BaseTestCase {
public void test() {
Geometry[] geoms = new Geometry[] { OLFactory.createPoint(1, 2), OLFactory.createLineString(
new Coordinate[] { OLFactory.createCoordinate(1, 2), OLFactory.createCoordinate(2, 3) }) };
GeometryCollection col = OLFactory.createGeometryCollection(geoms);
assertNotNull(col);
Geometry[] geoms2 = col.getGeometries();
assertNotNull(geoms2);
assertEquals(2, geoms2.length);
Geometry g1 = geoms2[0];
Geometry g2 = geoms2[1];
assertNotNull(g1);
assertNotNull(g2);
assertEquals("Point", g1.getType());
assertEquals("LineString", g2.getType());
}
}
|
package ol.geom;
import ol.*;
/**
* A test case for {@link GeometryCollection}.
*
* @author sbaumhekel
*/
public class GeometryCollectionTest extends BaseTestCase {
public void test() {
Geometry[] geoms = new Geometry[] { OLFactory.createPoint(1, 2), OLFactory.createLineString(
new Coordinate[] { OLFactory.createCoordinate(1, 2), OLFactory.createCoordinate(2, 3) }) };
GeometryCollection col = OLFactory.createGeometryCollection(geoms);
assertNotNull(col);
Geometry[] geoms2 = col.getGeometries();
assertNotNull(geoms2);
assertEquals(2, geoms2.length);
Geometry g1 = geoms2[0];
Geometry g2 = geoms2[1];
assertNotNull(g1);
assertNotNull(g2);
assertEquals(Geometry.POINT, g1.getType());
assertEquals(Geometry.LINE_STRING, g2.getType());
}
}
|
Validate swagger spec in gulp task
|
'use strict';
const gulp=require('gulp');
const $=require('gulp-load-plugins')();
gulp.task('eslint',function(){
return gulp.src(['*.js','api/**/*.js'])
.pipe($.gitmodified('modified'))
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failOnError());
});
gulp.task('yamlValidate',function(){
return gulp.src(['api/*.yml','config/*.{yaml,yml}'])
.pipe($.yamlValidate());
});
gulp.task('lint',gulp.parallel([
'eslint',
'yamlValidate'
]));
gulp.task('hooks',function(){
return gulp.src(['.git-hooks/pre-commit','.git-hooks/post-merge'])
.pipe($.sym(
['.git/hooks/pre-commit','.git/hooks/post-merge'],
{relative: true,force: true}
));
});
|
'use strict';
const gulp=require('gulp');
const $=require('gulp-load-plugins')();
gulp.task('eslint',function(){
return gulp.src(['*.js','api/**/*.js'])
.pipe($.gitmodified('modified'))
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failOnError());
});
gulp.task('yamlValidate',function(){
return gulp.src(['./config/*.{yaml,yml}'])
.pipe($.yamlValidate());
});
gulp.task('lint',gulp.parallel([
'eslint',
'yamlValidate'
]));
gulp.task('hooks',function(){
return gulp.src(['.git-hooks/pre-commit','.git-hooks/post-merge'])
.pipe($.sym(
['.git/hooks/pre-commit','.git/hooks/post-merge'],
{relative: true,force: true}
));
});
|
Move configuration of the module locator to the pages component
|
<?php
/**
* Nooku Framework - http://www.nooku.org
*
* @copyright Copyright (C) 2011 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://github.com/nooku/nooku-platform for the canonical source repository
*/
return array(
'identifiers' => array(
'dispatcher' => array(
'behaviors' => 'com:pages.dispatcher.behavior.accessible'
),
'com:application.template.locator.component' => array(
'override_path' => APPLICATION_BASE.'/public/theme/bootstrap/templates/views'
),
'com:application.template.filter.asset' => array(
'schemes' => array('assets://application/' => '/theme/bootstrap/')
),
)
);
|
<?php
/**
* Nooku Framework - http://www.nooku.org
*
* @copyright Copyright (C) 2011 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://github.com/nooku/nooku-platform for the canonical source repository
*/
return array(
'identifiers' => array(
'dispatcher' => array(
'behaviors' => 'com:pages.dispatcher.behavior.accessible'
),
'com:application.template.locator.component' => array(
'override_path' => APPLICATION_BASE.'/public/theme/bootstrap/templates/views'
),
'com:application.template.locator.module' => array(
'override_path' => APPLICATION_BASE.'/public/theme/bootstrap/templates/modules'
),
'com:application.template.filter.asset' => array(
'schemes' => array('assets://application/' => '/theme/bootstrap/')
),
)
);
|
Add a utility for checking valid view types
|
package io.jasonsparc.chemistry.util;
import android.support.annotation.AnyRes;
import android.support.v7.widget.RecyclerView;
import io.jasonsparc.chemistry.ViewType;
/**
* Created by jason on 11/07/2016.
*/
@UtilityClass
public final class ViewTypes {
/**
* An invalid view type, disguised to be valid. The value is equivalent to
* {@link RecyclerView#INVALID_TYPE}.
* <p>
* This can be used in situations where an invalid view type is actually intended but is
* restricted to use only valid view types. This variable however disregards such restrictions.
*/
@ViewType
@AnyRes
public static final int INVALID = invalid();
public static boolean isValid(int viewType) {
return viewType >= ValidRes.MIN_RES_ID;
}
public static void validateArgument(int viewType) {
if (viewType < ValidRes.MIN_RES_ID) {
throw new IllegalArgumentException("Invalid view type! Must be a resource identifier.");
}
}
public static void validateForState(int viewType) {
if (viewType < ValidRes.MIN_RES_ID) {
throw new IllegalStateException("Invalid view type! Must be a resource identifier.");
}
}
// Internals
@SuppressWarnings("Range")
@ViewType
@AnyRes
private static int invalid() {
return RecyclerView.INVALID_TYPE;
}
}
|
package io.jasonsparc.chemistry.util;
import android.support.annotation.AnyRes;
import android.support.v7.widget.RecyclerView;
import io.jasonsparc.chemistry.ViewType;
/**
* Created by jason on 11/07/2016.
*/
@UtilityClass
public final class ViewTypes {
/**
* An invalid view type, disguised to be valid. The value is equivalent to
* {@link RecyclerView#INVALID_TYPE}.
* <p>
* This can be used in situations where an invalid view type is actually intended but is
* restricted to use only valid view types. This variable however disregards such restrictions.
*/
@ViewType
@AnyRes
public static final int INVALID = invalid();
public static void validateArgument(int viewType) {
if (viewType < ValidRes.MIN_RES_ID) {
throw new IllegalArgumentException("Invalid view type! Must be a resource identifier.");
}
}
public static void validateForState(int viewType) {
if (viewType < ValidRes.MIN_RES_ID) {
throw new IllegalStateException("Invalid view type! Must be a resource identifier.");
}
}
// Internals
@SuppressWarnings("Range")
@ViewType
@AnyRes
private static int invalid() {
return RecyclerView.INVALID_TYPE;
}
}
|
Fix critical issue when running phapp commands.
|
<?php
namespace drunomics\Phapp;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Robo\Tasks;
/**
* Base class for phapp command classes.
*/
abstract class PhappCommandBase extends Tasks implements LoggerAwareInterface {
use LoggerAwareTrait;
/**
* Whether the command requires a valid phapp manifest.
*
* @var bool
*/
protected $requiresPhappManifest = TRUE;
/**
* The maniftest of the current phapp instance.
*
* @var \drunomics\Phapp\PhappManifest|null
*/
protected $phappManifest;
/**
* The global phapp config.
*
* @var \drunomics\Phapp\GlobalConfig
*/
protected $globalConfig;
/**
* Ensures with a valid phapp definition to interact with.
*
* @hook validate
*/
public function init() {
$this->globalConfig = GlobalConfig::discoverConfig();
if ($this->requiresPhappManifest) {
$this->phappManifest = PhappManifest::getInstance();
$this->initShellEnvironment();
}
$this->stopOnFail(TRUE);
}
/**
* Switches the working directory and adds the composer bin-dir to the path.
*
* @return $this
*/
protected function initShellEnvironment() {
chdir($this->phappManifest->getFile()->getPath());
$path = getenv("PATH");
putenv("PATH=../vendor/bin/:../bin:$path");
return $this;
}
}
|
<?php
namespace drunomics\Phapp;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Robo\Tasks;
/**
* Base class for phapp command classes.
*/
abstract class PhappCommandBase extends Tasks implements LoggerAwareInterface {
use LoggerAwareTrait;
/**
* Whether the command requires a valid phapp manifest.
*
* @var bool
*/
protected $requiresPhappManifest = TRUE;
/**
* The maniftest of the current phapp instance.
*
* @var \drunomics\Phapp\PhappManifest|null
*/
protected $phappManifest;
/**
* The global phapp config.
*
* @var \drunomics\Phapp\GlobalConfig
*/
protected $globalConfig;
/**
* Ensures with a valid phapp definition to interact with.
*
* @hook validate
*/
public function init() {
$this->globalConfig = GlobalConfig::discoverConfig();
if ($this->requiresPhappManifest) {
$this->phappManifest = PhappManifest::getInstance();
$this->initShellEnvironment();
}
$this->stopOnFail(TRUE);
}
/**
* Switches the working directory and adds the composer bin-dir to the path.
*
* @return $this
*/
protected function initShellEnvironment() {
chdir($this->phappManifest->getConfigFile()->getPath());
$path = getenv("PATH");
putenv("PATH=../vendor/bin/:../bin:$path");
return $this;
}
}
|
feat(webpack): Rename bundle to index. Multple entry points for including deps and minifying. Add so
BREAKING CHANGE: rename bundle to index and change dist/.
|
const camelCase = require('camelcase');
const path = require('path');
const webpack = require('webpack');
const pkg = require(path.join(process.cwd(), 'package.json'));
const shouldMininimize = process.argv.indexOf('--min') !== -1;
const standardConfig = {
devtool: 'source-map',
entry: {
'dist/index-with-deps.js': './src/index.js',
'dist/index-with-deps.min.js': './src/index.js',
},
output: {
path: './',
filename: '[name]',
libraryTarget: 'umd',
library: pkg['build:global'] || camelCase(pkg.name),
sourceMapFilename: '[file].map',
},
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css',
}, {
test: /\.less$/,
loader: 'style!css!less',
}, {
loader: 'babel-loader',
test: /\.js$/,
query: {
presets: ['babel-preset-es2015', 'babel-preset-react'],
},
}],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true,
}),
],
};
if (shouldMininimize) {
Object.assign(standardConfig.entry, {
'dist/bundle.min.js': './src/index.js',
});
}
module.exports = standardConfig;
|
var camelCase = require('camelcase');
var path = require('path');
var webpack = require('webpack');
var pkg = require(path.join(process.cwd(), 'package.json'));
var shouldMininimize = process.argv.indexOf('--min') !== -1;
var standardConfig = {
entry: {
'dist/bundle.js': './src/index.js'
},
output: {
path: './',
filename: '[name]',
libraryTarget: 'umd',
library: camelCase(pkg.name),
sourceMapFilename: '[file].map'
},
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css'
}, {
test: /\.less$/,
loader: 'style!css!less'
}, {
loader: 'babel-loader',
test: /\.js$/,
query: {
presets: ['babel-preset-es2015', 'babel-preset-react']
}
}]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})
]
};
if (shouldMininimize) {
Object.assign(standardConfig.entry, {
'dist/bundle.min.js': './src/index.js'
});
}
module.exports = standardConfig;
|
Add the status as fillable attribute
|
<?php namespace Modules\Blog\Entities;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Laracasts\Presenter\PresentableTrait;
use Modules\Media\Support\Traits\MediaRelation;
class Post extends Model
{
use Translatable, MediaRelation, PresentableTrait;
public $translatedAttributes = ['title', 'slug', 'content'];
protected $fillable = ['category_id', 'status', 'title', 'slug', 'content'];
protected $table = 'blog__posts';
protected $presenter = 'Modules\Blog\Presenters\PostPresenter';
public function category()
{
return $this->hasOne('Modules\Blog\Entities\Category');
}
public function tags()
{
return $this->belongsToMany('Modules\Blog\Entities\Tag', 'blog__post_tag');
}
}
|
<?php namespace Modules\Blog\Entities;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Laracasts\Presenter\PresentableTrait;
use Modules\Media\Support\Traits\MediaRelation;
class Post extends Model
{
use Translatable, MediaRelation, PresentableTrait;
public $translatedAttributes = ['title', 'slug', 'content'];
protected $fillable = ['category_id', 'title', 'slug', 'content'];
protected $table = 'blog__posts';
protected $presenter = 'Modules\Blog\Presenters\PostPresenter';
public function category()
{
return $this->hasOne('Modules\Blog\Entities\Category');
}
public function tags()
{
return $this->belongsToMany('Modules\Blog\Entities\Tag', 'blog__post_tag');
}
}
|
Use PascaleCase notation in class
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 KTec S.r.l.
# (<http://www.ktec.it>).
#
# Copyright (C) 2014 Associazione Odoo Italia
# (<http://www.odoo-italia.org>).
#
# 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 models
from openerp import fields
class ResPartner(models.Model):
_inherit = 'res.partner'
ipa_code = fields.Char(string='IPA Code')
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 KTec S.r.l.
# (<http://www.ktec.it>).
#
# Copyright (C) 2014 Associazione Odoo Italia
# (<http://www.odoo-italia.org>).
#
# 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 models
from openerp import fields
class res_partner(models.Model):
_inherit = 'res.partner'
ipa_code = fields.Char(
'IPA Code'
)
|
Update PM version to 1.4.5
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.5"
prepare_environment(**default_settings)
|
'''
### Polemarch is ansible based service for orchestration infrastructure.
* [Documentation](http://polemarch.readthedocs.io/)
* [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues)
* [Source Code](https://gitlab.com/vstconsulting/polemarch)
'''
import os
import warnings
try:
from vstutils.environment import prepare_environment, cmd_execution
except ImportError:
warnings.warn('"vstutils" was not installed', ImportWarning)
prepare_environment = lambda *args, **kwargs: ()
cmd_execution = prepare_environment
default_settings = {
# ansible specific environment variables
"ANSIBLE_HOST_KEY_CHECKING": 'False',
"ANSIBLE_FORCE_COLOR": "true",
# celery specific
"C_FORCE_ROOT": "true",
# django settings module
"DJANGO_SETTINGS_MODULE": os.getenv(
"DJANGO_SETTINGS_MODULE", 'polemarch.main.settings'
),
# VSTUTILS settings
"VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'),
"VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'),
}
__version__ = "1.4.4"
prepare_environment(**default_settings)
|
Test against interface instead of concrete class
|
<?php
namespace Twig;
use Webfactory\Bundle\PiwikBundle\Twig\Extension;
class ExtensionTest extends \PHPUnit_Framework_TestCase
{
public function testPiwikCodeReturnsNoScriptWhenDisabled()
{
$extension = new Extension(true, 1, '', false);
$this->assertNotContains('script', $extension->piwikCode());
}
public function testPiwikCodeReturnsScript()
{
$extension = new Extension(false, 1, '', false);
$this->assertContains('script', $extension->piwikCode());
}
public function testPiwikCodeContainsSiteId()
{
$siteId = 1234;
$extension = new Extension(false, $siteId, '', false);
$this->assertContains((string)$siteId, $extension->piwikCode());
}
public function testPiwikCodeContainsHostName()
{
$hostname = 'myHost.de';
$extension = new Extension(false, 1, $hostname, false);
$this->assertContains($hostname, $extension->piwikCode());
}
public function testIsTwigExtension()
{
$extension = new Extension(false, 1, '', false);
$this->assertInstanceOf('\Twig_ExtensionInterface', $extension);
}
}
|
<?php
namespace Twig;
use Webfactory\Bundle\PiwikBundle\Twig\Extension;
class ExtensionTest extends \PHPUnit_Framework_TestCase
{
public function testPiwikCodeReturnsNoScriptWhenDisabled()
{
$extension = new Extension(true, 1, '', false);
$this->assertNotContains('script', $extension->piwikCode());
}
public function testPiwikCodeReturnsScript()
{
$extension = new Extension(false, 1, '', false);
$this->assertContains('script', $extension->piwikCode());
}
public function testPiwikCodeContainsSiteId()
{
$siteId = 1234;
$extension = new Extension(false, $siteId, '', false);
$this->assertContains((string)$siteId, $extension->piwikCode());
}
public function testPiwikCodeContainsHostName()
{
$hostname = 'myHost.de';
$extension = new Extension(false, 1, $hostname, false);
$this->assertContains($hostname, $extension->piwikCode());
}
public function testIsTwigExtension()
{
$extension = new Extension(false, 1, '', false);
$this->assertInstanceOf('\Twig_Extension', $extension);
}
}
|
Add missing 2 blank lines after end of function or class. (PEP8 E305)
|
from django import template
from django.utils import six
from django.utils.encoding import force_text
from django.utils.safestring import SafeText, mark_safe
from django.template.defaultfilters import stringfilter
try:
from django.utils.functional import keep_lazy as allow_lazy
except ImportError:
from django.utils.functional import allow_lazy
register = template.Library()
_slack_escapes = {
ord('&'): u'&',
ord('<'): u'<',
ord('>'): u'>',
}
@register.filter(is_safe=True)
@stringfilter
def escapeslack(value):
"""
Returns the given text with ampersands and angle brackets encoded for use in
the Slack API, per the Slack API documentation:
<https://api.slack.com/docs/formatting#how_to_escape_characters>
This is based on django.template.defaultfilters.escapejs.
"""
return mark_safe(force_text(value).translate(_slack_escapes))
escapeslack = allow_lazy(escapeslack, six.text_type, SafeText)
|
from django import template
from django.utils import six
from django.utils.encoding import force_text
from django.utils.safestring import SafeText, mark_safe
from django.template.defaultfilters import stringfilter
try:
from django.utils.functional import keep_lazy as allow_lazy
except ImportError:
from django.utils.functional import allow_lazy
register = template.Library()
_slack_escapes = {
ord('&'): u'&',
ord('<'): u'<',
ord('>'): u'>',
}
@register.filter(is_safe=True)
@stringfilter
def escapeslack(value):
"""
Returns the given text with ampersands and angle brackets encoded for use in
the Slack API, per the Slack API documentation:
<https://api.slack.com/docs/formatting#how_to_escape_characters>
This is based on django.template.defaultfilters.escapejs.
"""
return mark_safe(force_text(value).translate(_slack_escapes))
escapeslack = allow_lazy(escapeslack, six.text_type, SafeText)
|
Clean up changes to thread test
|
#!/usr/bin/python2
import pstack
import json
pstack, text = pstack.JSON(["tests/thread"])
result = json.loads(text)
threads = result["threads"]
lwps = result["lwps"]
assert_at = result["assert_at"]
# we have 10 threads + main
assert len(threads) == 11
for thread in pstack:
# this will throw an error if the thread or LWP is not in the output for
# the command, indicating a thread or LWP id from pstack was wrong.
threads.remove(thread["ti_tid"])
lwps.remove(thread["ti_lid"])
for frame in thread["ti_stack"]:
if frame['die'] == 'entry':
# the soruce for "entry" should be thread.c
if not frame['source']:
print "warning: no source info to test"
else:
assert frame['source'][0]['file'].endswith( 'thread.cc' )
lineNo = frame['source'][0]['line']
# we should be between unlocking the mutex and pausing
assert lineNo == assert_at
# When we are finished, pstack should have found all the threads and lwps that
# reported in the output from the command.
assert not lwps
assert not threads
|
#!/usr/bin/python2
import pstack
import json
threads, text = pstack.JSON(["tests/thread"])
result = json.loads(text)
# we have 10 threads + main
assert len(threads) == 11
entryThreads = 0
for thread in threads:
assert thread["ti_lid"] in result["lwps"], "LWP %d not in %s" % (thread["ti_lid"], result["lwps"])
assert thread["ti_tid"] in result["threads"], "thread %d not in %s" % (thread["ti_lid"], result["threads"])
for frame in thread["ti_stack"]:
if frame['die'] == 'entry':
entryThreads += 1
# the soruce for "entry" should be thread.c
if not frame['source']:
print "warning: no source info to test"
else:
assert frame['source'][0]['file'].endswith( 'thread.cc' )
lineNo = frame['source'][0]['line']
# we should be between unlocking the mutex and pausing
assert lineNo == result["assert_at"]
assert entryThreads == 10
|
Fix double call to map rendering and debugger
|
function onDownloadFinished(duration)
{
console.log("Finished download in: " + duration + "ms");
initGame();
initDebugger();
}
/*
* Called on a resource download finish
* Params :
* downloadedAmount : Amount of resource downloaded
* totalAmount : Total amount resource to download
*/
function onDownloadUpdate(downloadedAmount, totalAmount)
{
console.log("Downloaded file : " + downloadedAmount + " / " + totalAmount + "(" + parseInt((downloadedAmount / totalAmount) * 100) + "%)");
}
/*
* Called on a resource download error
* Params :
* error : Error returned by JQuery
*/
function onDownloadError(error)
{
console.error("Failed to download resources :");
console.error(error);
}
// Game Start
$(function()
{
console.log("Game Starting...");
console.log("Download game resources...");
ResourceLoader.downloadGameResources(onDownloadFinished, onDownloadUpdate, onDownloadError);
});
|
function onDownloadFinished(duration)
{
console.log("Finished download in: " + duration + "ms");
initGame();
initDebugger();
}
/*
* Called on a resource download finish
* Params :
* downloadedAmount : Amount of resource downloaded
* totalAmount : Total amount resource to download
*/
function onDownloadUpdate(downloadedAmount, totalAmount)
{
console.log("Downloaded file : " + downloadedAmount + " / " + totalAmount + "(" + parseInt((downloadedAmount / totalAmount) * 100) + "%)");
}
/*
* Called on a resource download error
* Params :
* error : Error returned by JQuery
*/
function onDownloadError(error)
{
console.error("Failed to download resources :");
console.error(error);
}
// Game Start
$(function()
{
console.log("Game Starting...");
console.log("Download game resources...");
ResourceLoader.downloadGameResources(onDownloadFinished, onDownloadUpdate, onDownloadError);
initGame();
initDebugger();
});
|
Build sources for all flag
|
<?php
/**
* mbp-logging-reports.php
*
* A producer to create reports based on logged data in mb-logging-api.
*/
use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users;
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/mbp-logging-reports.config.inc';
if (isset($_GET['source'])) {
$sources[0] = $_GET['source'];
}
elseif (isset($argv[1])) {
$sources[0] = $argv[1];
}
if ($sources[0] == 'all') {
$sources = [
'niche',
'afterschool'
];
}
echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
try {
// Kick off
$mbpLoggingReport = new MBP_LoggingReports_Users();
// Gather digest message mailing list
$mbpLoggingReport->report('runningMonth', $sources);
}
catch(Exception $e) {
echo $e->getMessage(), PHP_EOL;
}
echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
|
<?php
/**
* mbp-logging-reports.php
*
* A producer to create reports based on logged data in mb-logging-api.
*/
use DoSomething\MBP_LoggingReports\MBP_LoggingReports_Users;
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/mbp-logging-reports.config.inc';
if (isset($_GET['source'])) {
$sources[0] = $_GET['source'];
}
elseif (isset($argv[1])) {
$sources[0] = $argv[1];
}
// all
else {
$sources = [
'niche',
'afterschool'
];
}
echo '------- mbp-logging-reports START: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
try {
// Kick off
$mbpLoggingReport = new MBP_LoggingReports_Users();
// Gather digest message mailing list
$mbpLoggingReport->report('runningMonth', $sources);
}
catch(Exception $e) {
echo $e->getMessage(), PHP_EOL;
}
echo '------- mbp-logging-reports END: ' . date('D M j G:i:s T Y') . ' -------', PHP_EOL;
|
Change default admin email to alex.smith@example.com
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def create_users(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
User = apps.get_model('users', 'User')
User.objects.create(
date_joined='2012-10-09T21:42:23Z',
email='alex.smith@example.com',
first_name='Alex',
is_active=True,
is_staff=True,
is_superuser=True,
last_name='Smith',
password=make_password('codigofuente'),
)
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.RunPython(create_users),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def create_users(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
User = apps.get_model('users', 'User')
User.objects.create(
date_joined='2012-10-09T21:42:23Z',
email='alex@smith.com',
first_name='Alex',
is_active=True,
is_staff=True,
is_superuser=True,
last_name='Smith',
password=make_password('codigofuente'),
)
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.RunPython(create_users),
]
|
Add events controller link to available v1 methods
|
'use strict';
const WebController = require('./WebController');
class ApiWebController extends WebController {
constructor(...args) {
super(...args);
// Bind web methods to object context so they can be passed to router.
this.index = this.index.bind(this);
this.v1 = this.v1.bind(this);
this.welcome = this.welcome.bind(this);
}
async welcome(ctx) {
ctx.body = 'Hi, I\'m Blink!';
}
async index(ctx) {
ctx.body = {
v1: this.fullUrl('api.v1'),
};
}
async v1(ctx) {
ctx.body = {
tools: this.fullUrl('api.v1.tools'),
events: this.fullUrl('api.v1.events'),
webhooks: this.fullUrl('api.v1.webhooks'),
};
}
}
module.exports = ApiWebController;
|
'use strict';
const WebController = require('./WebController');
class ApiWebController extends WebController {
constructor(...args) {
super(...args);
// Bind web methods to object context so they can be passed to router.
this.index = this.index.bind(this);
this.v1 = this.v1.bind(this);
this.welcome = this.welcome.bind(this);
}
async welcome(ctx) {
ctx.body = 'Hi, I\'m Blink!';
}
async index(ctx) {
ctx.body = {
v1: this.fullUrl('api.v1'),
};
}
async v1(ctx) {
ctx.body = {
tools: this.fullUrl('api.v1.tools'),
webhooks: this.fullUrl('api.v1.webhooks'),
};
}
}
module.exports = ApiWebController;
|
Fix issue with pulling users with FAQs
|
//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//
// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
var userId = req.params.id;
pg.connect(connectionString, function(error, client, done) {
connectionErrorCheck(error);
client.query(
'SELECT * FROM mentors ' +
'FULL OUTER JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
done();
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500);
} else {
res.send(result.rows);
}
}
);
});
});
module.exports = router;
// Checks for errors connecting to the database
function connectionErrorCheck(error) {
if (error) {
console.log('Database connection error: ', error);
res.sendStatus(500);
}
}
|
//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//
// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
var userId = req.params.id;
pg.connect(connectionString, function(error, client, done) {
connectionErrorCheck(error);
client.query(
'SELECT * FROM mentors ' +
'JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500);
} else {
res.send(result.rows);
}
}
);
});
});
module.exports = router;
// Checks for errors connecting to the database
function connectionErrorCheck(error) {
if (error) {
console.log('Database connection error: ', error);
res.sendStatus(500);
}
}
|
Check for new version on load.
|
// We don't want everyone to be synchronized, so add a random amount to the interval
const NEW_VERSION_INTERVAL = (10 + Math.random() * 5) * 60 * 1000;
// const NEW_VERSION_INTERVAL = 5000; // For debuggins
module.exports = [
'$interval', '$http', '$rootScope', 'storedConfiguration',
($interval, $http, $rootScope, storedConfiguration) => {
let ignoreNewVersion = false;
$rootScope.ignoreNewVersion = () => {
ignoreNewVersion = true;
$rootScope.newVersionAvailable = false;
$interval.cancel(versionCheck);
};
$rootScope.loadNewVersion = () => {
const {configuration} = $rootScope;
storedConfiguration.saveConfiguration(configuration);
window.location.search = 'cacheBust';
};
let versionCheck = $interval(checkForNewVersion, NEW_VERSION_INTERVAL);
checkForNewVersion();
function checkForNewVersion() {
$http
.get('currentVersion?' + new Date().getTime())
.success(version => {
// clVersion is generate at build time and injected into index.html
// it is a global value!
$rootScope.newVersionAvailable = !ignoreNewVersion && clVersion != version;
})
.error(error => {
});
}
}
];
|
// We don't want everyone to be synchronized, so add a random amount to the interval
const NEW_VERSION_INTERVAL = (10 + Math.random() * 5) * 60 * 1000;
// const NEW_VERSION_INTERVAL = 5000; // For debuggins
module.exports = [
'$interval', '$http', '$rootScope', 'storedConfiguration',
($interval, $http, $rootScope, storedConfiguration) => {
let ignoreNewVersion = false;
$rootScope.ignoreNewVersion = () => {
ignoreNewVersion = true;
$rootScope.newVersionAvailable = false;
$interval.cancel(versionCheck);
};
$rootScope.loadNewVersion = () => {
const {configuration} = $rootScope;
storedConfiguration.saveConfiguration(configuration);
window.location.search = 'cacheBust';
};
let versionCheck = $interval(checkForNewVersion, NEW_VERSION_INTERVAL);
function checkForNewVersion() {
$http
.get('currentVersion?' + new Date().getTime())
.success(version => {
// clVersion is generate at build time and injected into index.html
// it is a global value!
$rootScope.newVersionAvailable = !ignoreNewVersion && clVersion != version;
})
.error(error => {
});
}
}
];
|
Comment out console statement that will be needed later.
|
Application.Controllers.controller('projectsProject',
["$scope", "$stateParams", "actionStatus", "provStep",
"model.projects", "projectColors", projectsProject]);
function projectsProject ($scope, $stateParams, actionStatus, provStep, projects, projectColors) {
$scope.isActive = function (tab) {
return tab === $scope.activeTab;
};
actionStatus.addProject($stateParams.id);
provStep.addProject($stateParams.id);
projects.get($stateParams.id).then(function(project) {
$scope.project = project;
//console.dir(project);
projectColors.setCurrentProjectByID($stateParams.id);
});
}
|
Application.Controllers.controller('projectsProject',
["$scope", "$stateParams", "actionStatus", "provStep",
"model.projects", "projectColors", projectsProject]);
function projectsProject ($scope, $stateParams, actionStatus, provStep, projects, projectColors) {
$scope.isActive = function (tab) {
return tab === $scope.activeTab;
};
actionStatus.addProject($stateParams.id);
provStep.addProject($stateParams.id);
projects.get($stateParams.id).then(function(project) {
$scope.project = project;
projectColors.setCurrentProjectByID($stateParams.id);
});
}
|
Add save method and fix delete method in data point repository.
|
/*
* Copyright 2014 Open mHealth
*
* 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.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of data points.
*
* @see org.springframework.data.repository.CrudRepository
* @author Emerson Farrugia
*/
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {
Optional<DataPoint> findOne(String id);
Iterable<DataPoint> findAll();
DataPoint save(DataPoint dataPoint);
Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);
Long delete(String id);
}
|
/*
* Copyright 2014 Open mHealth
*
* 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.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of data points.
*
* @see org.springframework.data.repository.CrudRepository
* @author Emerson Farrugia
*/
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {
Optional<DataPoint> findOne(String id);
Iterable<DataPoint> findAll();
Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);
void delete(String id);
}
|
Use permissions attribute to detect ironic service
Horizon implements a logic to enable/disable panel by permissions
defined in each panel class. This change replaces the current redundant
logic by that built-in feature to simplify how we define requirements
of the Ironic panels.
Change-Id: I4a9dabfea79c23155fb8986fe8386202d7474485
|
# Copyright 2016 Cisco Systems, Inc.
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
import horizon
from openstack_dashboard.dashboards.admin import dashboard
class Ironic(horizon.Panel):
name = _("Ironic Bare Metal Provisioning")
slug = 'ironic'
permissions = ('openstack.roles.admin', 'openstack.services.baremetal',)
dashboard.Admin.register(Ironic)
|
# Copyright 2016 Cisco Systems, Inc.
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
import horizon
from openstack_dashboard.api import base
from openstack_dashboard.dashboards.admin import dashboard
class Ironic(horizon.Panel):
name = _("Ironic Bare Metal Provisioning")
slug = 'ironic'
permissions = ('openstack.roles.admin',)
def allowed(self, context):
request = context['request']
if not base.is_service_enabled(request, 'baremetal'):
return False
else:
return super(Ironic, self).allowed(context)
def nav(self, context):
request = context['request']
if not base.is_service_enabled(request, 'baremetal'):
return False
else:
return True
dashboard.Admin.register(Ironic)
|
Fix prompt arrow on backspace
|
/**
* Chat interface
* really really simple, but im not sure what else to add for now?
**/
const Callback = require('events');
const readline = require('readline');
class QuestionCallback extends Callback {}
class Display extends Callback {
constructor() {
super();
this.cli = readline.createInterface({
input: process.stdin,
output: process.stdout
}).on('line', (line) => this.emit('input', line)).on('SIGINT', () => this.emit('quit'));
this.cli.setPrompt('');
}
recieve(timestamp, nick, body) {
console.log(`[${timestamp}]${nick}: ${body}`);
}
printError(error) {
console.log('Error: ' + error);
}
askQuestion(prompt) {
let callback = new QuestionCallback();
this.cli.question(prompt, (response) => callback.emit('response', response));
return callback;
}
}
module.exports = Display;
|
/**
* Chat interface
* really really simple, but im not sure what else to add for now?
**/
const Callback = require('events');
const readline = require('readline');
class QuestionCallback extends Callback {}
class Display extends Callback {
constructor() {
super();
this.cli = readline.createInterface({
input: process.stdin,
output: process.stdout
}).on('line', (line) => this.emit('input', line)).on('SIGINT', () => this.emit('quit'));
}
recieve(timestamp, nick, body) {
console.log(`[${timestamp}]${nick}: ${body}`);
}
printError(error) {
console.log('Error: ' + error);
}
askQuestion(prompt) {
let callback = new QuestionCallback();
this.cli.question(prompt, (response) => callback.emit('response', response));
return callback;
}
}
module.exports = Display;
|
[github] Add "Enterprise" to the list of possible user plans.
It fixes IDEA-101433, since unknown plan is treated as "free".
|
/*
* Copyright 2000-2012 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 org.jetbrains.plugins.github;
import org.jetbrains.annotations.NotNull;
/**
* Information about a user on GitHub.
*
* @author Kirill Likhodedov
*/
class GithubUser {
enum Plan {
FREE,
MICRO,
SMALL,
MEDIUM,
BRONZE,
SILVER,
GOLD,
PLATINUM,
ENTERPRISE;
public boolean isPrivateRepoAllowed() {
return this != FREE;
}
public static Plan fromString(String name) {
for (Plan plan : values()) {
if (plan.name().equalsIgnoreCase(name)) {
return plan;
}
}
return defaultPlan();
}
private static Plan defaultPlan() {
return FREE;
}
}
@NotNull private final Plan myPlan;
GithubUser(@NotNull Plan plan) {
myPlan = plan;
}
@NotNull
Plan getPlan() {
return myPlan;
}
}
|
/*
* Copyright 2000-2012 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 org.jetbrains.plugins.github;
import org.jetbrains.annotations.NotNull;
/**
* Information about a user on GitHub.
*
* @author Kirill Likhodedov
*/
class GithubUser {
enum Plan {
FREE,
MICRO,
SMALL,
MEDIUM,
BRONZE,
SILVER,
GOLD,
PLATINUM;
public boolean isPrivateRepoAllowed() {
return this != FREE;
}
public static Plan fromString(String name) {
for (Plan plan : values()) {
if (plan.name().equalsIgnoreCase(name)) {
return plan;
}
}
return defaultPlan();
}
private static Plan defaultPlan() {
return FREE;
}
}
@NotNull private final Plan myPlan;
GithubUser(@NotNull Plan plan) {
myPlan = plan;
}
@NotNull
Plan getPlan() {
return myPlan;
}
}
|
Correct name of output file
|
#!/home/daniel/Software/anaconda3/bin/python
# Import modules for CGI handling
import cgi, cgitb
from abundanceDriver import abundancedriver
from emailSender import sendEmail
def cgi2dict(form):
"""Convert the form from cgi.FieldStorage to a python dictionary"""
params = {}
for key in form.keys():
params[key] = form[key].value
return params
def abundance(form):
"""Create the configuration file for running the abundance driver"""
# Make the StarMe_ares.cfg
fout = '/tmp/linelist.moog {Teff} {logg} {feh} {vt}'.format(**form)
with open('/tmp/StarMe_abundance.cfg', 'w') as f:
f.writelines(fout+'\n')
abundancedriver('/tmp/StarMe_abundance.cfg')
if __name__ == '__main__':
# Enable debugging
cgitb.enable()
form = cgi.FieldStorage()
# Run ARES for one or several line lists
formDict = cgi2dict(form)
abundance(formDict)
sendEmail(to=formDict['email'], driver='abundances', data='/tmp/abundresults.dat')
# Show the finished html page
print "Content-type: text/html\n\n"
with open('../html/finish.html', 'r') as lines:
for line in lines:
print line
|
#!/home/daniel/Software/anaconda3/bin/python
# Import modules for CGI handling
import cgi, cgitb
from abundanceDriver import abundancedriver
from emailSender import sendEmail
def cgi2dict(form):
"""Convert the form from cgi.FieldStorage to a python dictionary"""
params = {}
for key in form.keys():
params[key] = form[key].value
return params
def abundance(form):
"""Create the configuration file for running the abundance driver"""
# Make the StarMe_ares.cfg
fout = '/tmp/linelist.moog {Teff} {logg} {feh} {vt}'.format(**form)
with open('/tmp/StarMe_abundance.cfg', 'w') as f:
f.writelines(fout+'\n')
abundancedriver('/tmp/StarMe_abundance.cfg')
if __name__ == '__main__':
# Enable debugging
import os
os.system('touch /tmp/test1')
cgitb.enable()
form = cgi.FieldStorage()
# Run ARES for one or several line lists
formDict = cgi2dict(form)
abundance(formDict)
sendEmail(to=formDict['email'], driver='abundances', data='/tmp/abundances.dat')
# Show the finished html page
print "Content-type: text/html\n\n"
with open('../html/finish.html', 'r') as lines:
for line in lines:
print line
|
Update to change db name on config
|
var config = {
/** app mode **/
mode: 'DEV',
/** db name **/
db: 'tiapp-como',
/** android tablet minimum form factor **/
tablet: {
width: 899,
height: 899
},
/** Actions **/
action: [
{module: 'Try', name: 'doSave', path: 'Como.Controller.Try.doSave'},
{module: 'Try', name: 'showLogin', path: 'Como.Controller.Try.showLogin'},
{module: 'Try', name: 'doLogin', path: 'Como.Controller.Try.doLogin'},
{module: 'Try', name: 'doLogout', path: 'Como.Controller.Try.doLogout'}
]
};
module.exports = config;
|
var config = {
/** app mode **/
mode: 'DEV',
/** db name **/
db: 'tiapp-exercise',
/** android tablet minimum form factor **/
tablet: {
width: 899,
height: 899
},
/** Actions **/
action: [
{module: 'Try', name: 'doSave', path: 'Como.Controller.Try.doSave'},
{module: 'Try', name: 'showLogin', path: 'Como.Controller.Try.showLogin'},
{module: 'Try', name: 'doLogin', path: 'Como.Controller.Try.doLogin'},
{module: 'Try', name: 'doLogout', path: 'Como.Controller.Try.doLogout'}
]
};
module.exports = config;
|
Develop the Regex grammar slightly further
|
#!/usr/bin/python3
import sys, os
import nltk
if len(sys.argv) < 2:
print("Please supply a filename.")
sys.exit(1)
filename = sys.argv[1]
with open(filename, 'r') as f:
data = f.read()
# Break the input down into sentences, then into words, and position tag
# those words.
raw_sentences = nltk.sent_tokenize(data)
sentences = [nltk.pos_tag(nltk.word_tokenize(sentence)) \
for sentence in raw_sentences]
# Define a grammar, and identify the noun phrases in the sentences.
chunk_parser = nltk.RegexpParser(r"NP: {((<DT>|<PRP\$>)?<JJ>*(<NN>|<NNP>)+|<PRP>)}")
trees = [chunk_parser.parse(sentence) for sentence in sentences]
for index, tree in enumerate(trees):
print("===\nSentence: %s\nNoun phrases:" %
raw_sentences[index].replace('\n', ' '))
for subtree in tree.subtrees(filter = lambda t: t.label() == 'NP'):
print(" %s" % subtree)
|
#!/usr/bin/python3
import sys, os
import nltk
if len(sys.argv) < 2:
print("Please supply a filename.")
sys.exit(1)
filename = sys.argv[1]
with open(filename, 'r') as f:
data = f.read()
# Break the input down into sentences, then into words, and position tag
# those words.
sentences = [nltk.pos_tag(nltk.word_tokenize(sentence)) \
for sentence in nltk.sent_tokenize(data)]
# Define a grammar, and identify the noun phrases in the sentences.
chunk_parser = nltk.RegexpParser(r"NP: {<DT>?<JJ>*<NN>}")
trees = [chunk_parser.parse(sentence) for sentence in sentences]
for tree in trees:
print(tree)
#for subtree in tree.subtrees(filter = lambda t: t.label() == 'NP'):
#print(subtree)
|
Fix email value object after refactoring by Daniel Santamaria.
|
<?php
namespace ValueObjects\Internet;
use ValueObjects\ValueObject;
/**
* Class Email
* Value object that represents a mail address.
* @package ValueObjects\Internet
*/
class Email extends ValueObject
{
/**
* @var string
*/
private $email;
/**
* @param string $email
*/
public function __construct(string $email)
{
$this->validate($email);
$this->email = $email;
}
/**
* @param string $email
* @throws \InvalidArgumentException
*/
private function validate(string $email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new \InvalidArgumentException("$email is not a valid e-mail address.");
}
}
/**
* @return string
*/
public function __toString(): string
{
return $this->email;
}
public function username(): string
{
return $this->getEmailParts()[0];
}
public function domain(): string
{
return $this->getEmailParts()[1];
}
private function getEmailParts(): array
{
return explode("@", $this->email);
}
}
|
<?php
namespace ValueObjects\Internet;
use ValueObjects\ValueObject;
/**
* Class Email
* Value object that represents a mail address.
* @package ValueObjects\Internet
*/
class Email extends ValueObject
{
/**
* @var string
*/
private $email;
/**
* @param string $email
*/
public function __construct(string $email)
{
$this->validate($email);
$this->email = $email;
}
/**
* @param string $email
* @throws \InvalidArgumentException
*/
private function validate(string $email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new \InvalidArgumentException("$email is not a valid e-mail address.");
}
}
/**
* @return string
*/
public function __toString(): string
{
return $this->email;
}
public function username(): string
{
return $this->getEmailParts()[0];
}
public function domain(): string
{
return $this->getEmailParts()[1];
}
private function getEmailParts(): array
{
return explode("@", $this->value);
}
}
|
Fix target of dashboard controller tests
|
define([
'client/client_bootstrap',
'client/controllers/dashboard'
],
function (bootstrap, DashboardController) {
describe('client bootstrap', function () {
var config;
beforeEach(function () {
spyOn(DashboardController.prototype, 'render');
config = {
'page-type': 'dashboard'
};
});
it('instantiates a controller from config data', function () {
var controller = bootstrap(config);
expect(controller instanceof DashboardController).toBe(true);
expect(controller.render).toHaveBeenCalled();
});
it('executes page preprocessors', function () {
var originalPreprocessors = bootstrap.preprocessors;
bootstrap.preprocessors = [
jasmine.createSpy(),
jasmine.createSpy()
];
bootstrap(config);
expect(bootstrap.preprocessors[0]).toHaveBeenCalled();
expect(bootstrap.preprocessors[1]).toHaveBeenCalled();
bootstrap.preprocessors = originalPreprocessors;
});
});
});
|
define([
'client/client_bootstrap',
'extensions/controllers/dashboard'
],
function (bootstrap, DashboardController) {
describe('client bootstrap', function () {
var config;
beforeEach(function () {
spyOn(DashboardController.prototype, 'render');
config = {
'page-type': 'dashboard'
};
});
it('instantiates a controller from config data', function () {
var controller = bootstrap(config);
expect(controller instanceof DashboardController).toBe(true);
expect(controller.render).toHaveBeenCalled();
});
it('executes page preprocessors', function () {
var originalPreprocessors = bootstrap.preprocessors;
bootstrap.preprocessors = [
jasmine.createSpy(),
jasmine.createSpy()
];
bootstrap(config);
expect(bootstrap.preprocessors[0]).toHaveBeenCalled();
expect(bootstrap.preprocessors[1]).toHaveBeenCalled();
bootstrap.preprocessors = originalPreprocessors;
});
});
});
|
Fix for brightcove player when orintation is changed
|
/**
* This script keeps the height set on elements with regard to their
* width for a given aspect ratio. Great for "display:block" elements
*
* Example usage:
*
* <div data-keep-aspect-ratio="16:9">
*
* Author: Rod McNew
* License: BSD
*/
new function () {
var setHeights = function () {
$.each($('[data-keep-aspect-ratio]'), function () {
var ele = $(this);
var ratioParts = ele.attr('data-keep-aspect-ratio').split(':');
var ratioWidth = ratioParts[0];
var ratioHeight = ratioParts[1];
var width = ele.width();
var newHeight = width * ratioHeight / ratioWidth;
ele.css('height', newHeight);
})
};
//Run onReady
$(setHeights);
//Run when window is resized
$(window).resize(setHeights);
//Run when target elements are resized without a window resize
$('body').on('resize', '[data-keep-aspect-ratio]', setHeights);
$('body').on('orientationchange', '[data-keep-aspect-ratio]', setHeights);
};
|
/**
* This script keeps the height set on elements with regard to their
* width for a given aspect ratio. Great for "display:block" elements
*
* Example usage:
*
* <div data-keep-aspect-ratio="16:9">
*
* Author: Rod McNew
* License: BSD
*/
new function () {
var setHeights = function () {
$.each($('[data-keep-aspect-ratio]'), function () {
var ele = $(this);
var ratioParts = ele.attr('data-keep-aspect-ratio').split(':');
var ratioWidth = ratioParts[0];
var ratioHeight = ratioParts[1];
var width = ele.width();
var newHeight = width * ratioHeight / ratioWidth;
ele.css('height', newHeight);
})
};
//Run onReady
$(setHeights);
//Run when window is resized
$(window).resize(setHeights);
//Run when target elements are resized without a window resize
$('body').delegate('[data-keep-aspect-ratio]', 'resize', setHeights);
};
|
Fix name: should be TestRuledXmlOrder, not TestRuledXmlForeach.
|
#!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlOrder(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
with open(utils.data('030_target.xml'), 'rb') as target:
utils.xmlEquals(self, result.getvalue(), target.read())
def test_031(self):
result = io.BytesIO()
with open(utils.data('031_source.xml')) as src:
ruledxml.run(src, utils.data('031_rules.py'), result)
with open(utils.data('031_target.xml'), 'rb') as target:
utils.xmlEquals(self, result.getvalue(), target.read())
def run():
unittest.main()
if __name__ == '__main__':
run()
|
#!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlForeach(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
with open(utils.data('030_target.xml'), 'rb') as target:
utils.xmlEquals(self, result.getvalue(), target.read())
def test_031(self):
result = io.BytesIO()
with open(utils.data('031_source.xml')) as src:
ruledxml.run(src, utils.data('031_rules.py'), result)
with open(utils.data('031_target.xml'), 'rb') as target:
utils.xmlEquals(self, result.getvalue(), target.read())
def run():
unittest.main()
if __name__ == '__main__':
run()
|
Fix logic for operator pad
|
package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class LiftControlCommand extends Command {
public LiftControlCommand() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(Robot.lift);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (Robot.oi.operatorPad.getLeftY() <= -.5) {
Robot.lift.goUp();
} else if (Robot.oi.operatorPad.getLeftY() >= .5) {
Robot.lift.goDown();
} else {
Robot.lift.stop();
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class LiftControlCommand extends Command {
public LiftControlCommand() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(Robot.lift);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (Robot.oi.operatorPad.getLeftY() >= .5) {
Robot.lift.goUp();
} else if (Robot.oi.operatorPad.getLeftY() <= -.5) {
Robot.lift.goDown();
} else {
Robot.lift.stop();
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
Remove unnecessary call to mock_datareader().
|
#!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest
import mock
from nose.tools import assert_equal
from pandas_finance import get_stock, get_required_tickers
class PandasFinanceTestCase(unittest.TestCase):
@mock.patch('pandas_finance.web.DataReader')
def test_get_stock_called_correctly(self, mock_datareader):
start = datetime.datetime(1999, 4, 3, 0, 0)
end = datetime.datetime(2005, 2, 5, 0, 0)
get_stock('AAPL', start, end)
mock_datareader.assert_called_with('AAPL', 'yahoo', start, end)
def test_get_required_tickers_parses_tickers_with_newline(self):
m = mock.mock_open(read_data='TWTR,FB,AAPL,MSFT\n')
textfile = None # only used to provide valid argument
with mock.patch('pandas_finance.open', m, create=True):
result = get_required_tickers(textfile)
assert_equal('TWTR,FB,AAPL,MSFT', result)
|
#!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest
import mock
from nose.tools import assert_equal
from pandas_finance import get_stock, get_required_tickers
class PandasFinanceTestCase(unittest.TestCase):
@mock.patch('pandas_finance.web.DataReader')
def test_get_stock_called_correctly(self, mock_datareader):
mock_datareader()
start = datetime.datetime(1999, 4, 3, 0, 0)
end = datetime.datetime(2005, 2, 5, 0, 0)
get_stock('AAPL', start, end)
mock_datareader.assert_called_with('AAPL', 'yahoo', start, end)
def test_get_required_tickers_parses_tickers_with_newline(self):
m = mock.mock_open(read_data='TWTR,FB,AAPL,MSFT\n')
textfile = None # only used to provide valid argument
with mock.patch('pandas_finance.open', m, create=True):
result = get_required_tickers(textfile)
assert_equal('TWTR,FB,AAPL,MSFT', result)
|
Fix ui test with compiler error
|
package de.christinecoenen.code.zapp.app.mediathek.ui.detail;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import de.christinecoenen.code.zapp.app.ZappApplication;
import de.christinecoenen.code.zapp.app.mediathek.MediathekData;
import de.christinecoenen.code.zapp.app.mediathek.model.PersistedMediathekShow;
@RunWith(AndroidJUnit4.class)
public class MediathekPlayerActivityTest {
private PersistedMediathekShow persistedShow;
@Before
public void Setup() {
ZappApplication zappApplication = (ZappApplication) InstrumentationRegistry
.getInstrumentation()
.getTargetContext()
.getApplicationContext();
persistedShow = zappApplication.getMediathekRepository()
.persistOrUpdateShow(MediathekData.getTestShow())
.blockingFirst();
}
@Test
public void testRecreation() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Intent intent = MediathekPlayerActivity.getStartIntent(context, persistedShow.getId());
ActivityScenario<Activity> scenario = ActivityScenario.launch(intent);
scenario.recreate();
scenario.onActivity(activity -> activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE));
scenario.recreate();
}
}
|
package de.christinecoenen.code.zapp.app.mediathek.ui.detail;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import de.christinecoenen.code.zapp.app.mediathek.MediathekData;
@RunWith(AndroidJUnit4.class)
public class MediathekPlayerActivityTest {
@Test
public void testRecreation() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Intent intent = MediathekPlayerActivity.getStartIntent(context, MediathekData.getTestShow());
ActivityScenario scenario = ActivityScenario.launch(intent);
scenario.recreate();
scenario.onActivity(activity -> activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE));
scenario.recreate();
}
}
|
Change argparse requirement to only apply to python versions less than 2.7
|
#!/usr/bin/env python
from setuptools import setup, find_packages
from sys import version_info
from cron_sentry.version import VERSION
requirements = ['raven']
if version_info < (2, 7, 0):
requirements.append('argparse')
setup(
name='cron-sentry',
version=VERSION,
author='Yipit Coders',
author_email='coders@yipit.com',
description='Cron-Sentry is a command-line wrapper that reports unsuccessful runs to Sentry (https://www.getsentry.com)',
long_description=open('README.md').read(),
license='MIT',
classifiers=[
'Topic :: Utilities',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
],
url='http://github.com/yipit/cron-sentry',
packages=find_packages(),
install_requires=requirements,
data_files=[],
entry_points={
'console_scripts': [
# `raven-cron` entry point is for backwards compatibility purposes.
# it should get removed in future releases
'raven-cron = cron_sentry.runner:run',
'cron-sentry = cron_sentry.runner:run',
]
}
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
from cron_sentry.version import VERSION
setup(
name='cron-sentry',
version=VERSION,
author='Yipit Coders',
author_email='coders@yipit.com',
description='Cron-Sentry is a command-line wrapper that reports unsuccessful runs to Sentry (https://www.getsentry.com)',
long_description=open('README.md').read(),
license='MIT',
classifiers=[
'Topic :: Utilities',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
],
url='http://github.com/yipit/cron-sentry',
packages=find_packages(),
install_requires=['raven', 'argparse'],
data_files=[],
entry_points={
'console_scripts': [
# `raven-cron` entry point is for backwards compatibility purposes.
# it should get removed in future releases
'raven-cron = cron_sentry.runner:run',
'cron-sentry = cron_sentry.runner:run',
]
}
)
|
Fix PHPDoc wrong type annotation
|
<?php
/*
* This file is part of the PhpTabs package.
*
* Copyright (c) landrok at github.com/landrok
*
* For the full copyright and license information, please see
* <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
*/
namespace PhpTabs\Component\Renderer;
interface RendererInterface
{
/**
* @param int $index Track index
* @return string
*/
public function render($index);
/**
* @param string $name
* @param int|string $value
* @return \PhpTabs\Component\Renderer\RendererInterface
*/
public function setOption($name, $value);
/**
* @param string $name
* @param int|string $default
* @return int|string
*/
public function getOption($name, $default);
/**
* @param array $options
* @return \PhpTabs\Component\Renderer\RendererInterface
*/
public function setOptions(array $options);
/**
* @return array
*/
public function getOptions();
}
|
<?php
/*
* This file is part of the PhpTabs package.
*
* Copyright (c) landrok at github.com/landrok
*
* For the full copyright and license information, please see
* <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
*/
namespace PhpTabs\Component\Renderer;
interface RendererInterface
{
/**
* @param int $index Track index
* @return string
*/
public function render($index);
/**
* @param string $name
* @param int|string $value
* @return \PhpTabs\Model\RendererInterface
*/
public function setOption($name, $value);
/**
* @param string $name
* @param int|string $default
* @return int|string
*/
public function getOption($name, $default);
/**
* @param array $options
* @return \PhpTabs\Model\RendererInterface
*/
public function setOptions(array $options);
/**
* @return array
*/
public function getOptions();
}
|
Remove spaces that are between > and <
|
<?php
/*
* This file is part of HtmlCompress.
*
** (c) 2014 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\HtmlCompress\Compressor;
/**
* Class HtmlCompressor
*
* @package WyriHaximus\HtmlCompress\Compressor
*/
class HtmlCompressor extends Compressor
{
/**
* {@inheritdoc}
*/
protected function execute($string)
{
// Replace newlines, returns and tabs with nothing
$string = str_replace(["\r", "\n", "\t"], '', $string);
// Replace multiple spaces with a single space
$string = preg_replace('/(\s+)/m', ' ', $string);
// Remove spaces that are followed by either > or <
$string = preg_replace('/ (>)/', '$1', $string);
// Remove spaces that are preceded by either > or <
$string = preg_replace('/(<) /', '$1', $string);
// Remove spaces that are between > and <
$string = preg_replace('/(>) (<)/', '>$2', $string);
return trim($string);
}
}
|
<?php
/*
* This file is part of HtmlCompress.
*
** (c) 2014 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\HtmlCompress\Compressor;
/**
* Class HtmlCompressor
*
* @package WyriHaximus\HtmlCompress\Compressor
*/
class HtmlCompressor extends Compressor
{
/**
* {@inheritdoc}
*/
protected function execute($string)
{
// Replace newlines, returns and tabs with nothing
$string = str_replace(["\r", "\n", "\t"], '', $string);
// Replace multiple spaces with a single space
$string = preg_replace('/(\s+)/m', ' ', $string);
// Remove spaces that are followed by either > or <
$string = preg_replace('/ (>)/', '$1', $string);
// Remove spaces that are preceded by either > or <
$string = preg_replace('/(<) /', '$1', $string);
return trim($string);
}
}
|
Reduce the verbosity of the tests.
Signed-off-by: Gora Khargosh <a2078c57e3ac12c6dfb97b7c2c4e6d6d7db7e92f@gmail.com>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import unittest2 as unittest
current_path = os.path.abspath(os.path.dirname(__file__))
tests_path = os.path.join(current_path, 'tests')
sys.path[0:0] = [
current_path,
tests_path,
]
all_tests = [f[:-3] for f in os.listdir(tests_path)
if f.startswith('test_') and f.endswith(".py")]
def get_suite(tests):
tests = sorted(tests)
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for test in tests:
suite.addTest(loader.loadTestsFromName(test))
return suite
if __name__ == '__main__':
"""
To run all tests:
$ python run_tests.py
To run a single test:
$ python run_tests.py app
To run a couple of tests:
$ python run_tests.py app config sessions
To run code coverage:
$ coverage run run_tests.py
$ coverage report -m
"""
tests = sys.argv[1:]
if not tests:
tests = all_tests
tests = ['%s' % t for t in tests]
suite = get_suite(tests)
unittest.TextTestRunner(verbosity=1).run(suite)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import unittest2 as unittest
current_path = os.path.abspath(os.path.dirname(__file__))
tests_path = os.path.join(current_path, 'tests')
sys.path[0:0] = [
current_path,
tests_path,
]
all_tests = [f[:-3] for f in os.listdir(tests_path)
if f.startswith('test_') and f.endswith(".py")]
def get_suite(tests):
tests = sorted(tests)
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for test in tests:
suite.addTest(loader.loadTestsFromName(test))
return suite
if __name__ == '__main__':
"""
To run all tests:
$ python run_tests.py
To run a single test:
$ python run_tests.py app
To run a couple of tests:
$ python run_tests.py app config sessions
To run code coverage:
$ coverage run run_tests.py
$ coverage report -m
"""
tests = sys.argv[1:]
if not tests:
tests = all_tests
tests = ['%s' % t for t in tests]
suite = get_suite(tests)
unittest.TextTestRunner(verbosity=2).run(suite)
|
Add __get__ to sys.stderr and stdout
|
var $module=(function($B){
return {
modules :
{'__get__':function(){return $B.builtins.dict($B.JSObject($B.imported))},
'__set__':0 // data descriptor, to force use of __get__
},
stderr : {
__get__:function(){return $B.stderr},
__set__:function(self, obj, value){console.log('set stderr');$B.stderr = value},
write:function(data){$B.builtins.getattr($B.stderr,"write")(data)}
},
stdout : {
__get__:function(){return $B.stdout},
__set__:function(self, obj, value){console.log('set stdout');$B.stdout = value},
write:function(data){$B.builtins.getattr($B.stdout,"write")(data)}
},
stdin : $B.stdin
}
})(__BRYTHON__)
|
var $module=(function($B){
return {
modules :
{'__get__':function(){return $B.builtins.dict($B.JSObject($B.imported))},
'__set__':0 // data descriptor, to force use of __get__
},
stderr : {
__set__:function(self, obj, value){$B.stderr = value},
write:function(data){$B.stderr.write(data)}
},
stdout : {
__set__:function(self, obj, value){$B.stdout = value},
write:function(data){$B.stdout.write(data)}
},
stdin : $B.stdin
}
})(__BRYTHON__)
|
Rewrite engine.Dot marshaler to use sprintf instead json.Marshal
|
package engine
import "fmt"
type Dot struct {
X uint8
Y uint8
}
// Equals compares two dots
func (d1 Dot) Equals(d2 Dot) bool {
return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y)
}
// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("[%d,%d]", d.X, d.Y)), nil
}
func (d Dot) String() string {
return fmt.Sprintf("[%d, %d]", d.X, d.Y)
}
// DistanceTo calculates distance between two dots
func (from Dot) DistanceTo(to Dot) (res uint16) {
if !from.Equals(to) {
if from.X > to.X {
res = uint16(from.X - to.X)
} else {
res = uint16(to.X - from.X)
}
if from.Y > to.Y {
res += uint16(from.Y - to.Y)
} else {
res += uint16(to.Y - from.Y)
}
}
return
}
|
package engine
import (
"encoding/json"
"fmt"
)
type Dot struct {
X uint8
Y uint8
}
// Equals compares two dots
func (d1 Dot) Equals(d2 Dot) bool {
return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y)
}
// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
return json.Marshal([]uint8{d.X, d.Y})
}
func (d Dot) String() string {
return fmt.Sprintf("[%d, %d]", d.X, d.Y)
}
// DistanceTo calculates distance between two dots
func (from Dot) DistanceTo(to Dot) (res uint16) {
if !from.Equals(to) {
if from.X > to.X {
res = uint16(from.X - to.X)
} else {
res = uint16(to.X - from.X)
}
if from.Y > to.Y {
res += uint16(from.Y - to.Y)
} else {
res += uint16(to.Y - from.Y)
}
}
return
}
|
AEIV-665: Fix review issues
- minor fix
|
<?php
namespace Oro\Bundle\CalendarBundle\Manager;
use Oro\Bundle\CalendarBundle\Entity\Attendee;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
class AttendeeManager
{
/** @var DoctrineHelper */
protected $doctrineHelper;
/**
* @param DoctrineHelper $doctrineHelper
*/
public function __construct(DoctrineHelper $doctrineHelper)
{
$this->doctrineHelper = $doctrineHelper;
}
/**
* @param string $id
*
* @return Attendee[]
*/
public function loadAttendeesByCalendarEventId($id)
{
return $this->doctrineHelper
->getEntityRepository('OroCalendarBundle:Attendee')
->getAttendeesByCalendarEventId($id);
}
}
|
<?php
namespace Oro\Bundle\CalendarBundle\Manager;
use Oro\Bundle\CalendarBundle\Entity\Attendee;
use Oro\Bundle\CalendarBundle\Entity\Repository\AttendeeRepository;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
class AttendeeManager
{
/** @var DoctrineHelper */
protected $doctrineHelper;
/**
* @param DoctrineHelper $doctrineHelper
*/
public function __construct(DoctrineHelper $doctrineHelper)
{
$this->doctrineHelper = $doctrineHelper;
}
/**
* @param string $id
*
* @return Attendee[]
*/
public function loadAttendeesByCalendarEventId($id)
{
/** @var AttendeeRepository $attendeeRepository */
$attendeeRepository = $this->doctrineHelper->getEntityRepository('OroCalendarBundle:Attendee');
return $attendeeRepository->getAttendeesByCalendarEventId($id);
}
}
|
Add “Settlement” transaction type for Cash Transactions. AMAAS-2012
|
export const CASH_TRANSACTION_TYPES = [ 'Cashflow', 'Coupon', 'Dividend', 'Payment', 'Settlement' ]
export const TRANSACTION_TYPES = [ 'Allocation', 'Block', 'Exercise', 'Expiry', 'Journal', 'Maturity', 'Net', 'Novation', 'Split', 'Trade', 'Transfer', ...CASH_TRANSACTION_TYPES ]
export const TRANSACTION_INVESTOR_ACTIONS = [ 'Subscription', 'Redemption' ]
export const TRANSACTION_LIFECYCLE_ACTIONS = [ 'Acquire', 'Remove' ]
export const TRANSACTION_ACTIONS = [ 'Buy', 'Sell', 'Short Sell', 'Short Cover', 'Deliver', 'Receive', ...TRANSACTION_INVESTOR_ACTIONS, ...TRANSACTION_LIFECYCLE_ACTIONS ]
export const TRANSACTION_CANCEL_STATUSES = [ 'Cancelled', 'Netted', 'Novated' ]
export const TRANSACTION_STATUSES = [ 'New', 'Amended', 'Superseded', ...TRANSACTION_CANCEL_STATUSES ]
|
export const CASH_TRANSACTION_TYPES = [ 'Cashflow', 'Coupon', 'Dividend', 'Payment' ]
export const TRANSACTION_TYPES = [ 'Allocation', 'Block', 'Exercise', 'Expiry', 'Journal', 'Maturity', 'Net', 'Novation', 'Split', 'Trade', 'Transfer', ...CASH_TRANSACTION_TYPES ]
export const TRANSACTION_INVESTOR_ACTIONS = [ 'Subscription', 'Redemption' ]
export const TRANSACTION_LIFECYCLE_ACTIONS = [ 'Acquire', 'Remove' ]
export const TRANSACTION_ACTIONS = [ 'Buy', 'Sell', 'Short Sell', 'Short Cover', 'Deliver', 'Receive', ...TRANSACTION_INVESTOR_ACTIONS, ...TRANSACTION_LIFECYCLE_ACTIONS ]
export const TRANSACTION_CANCEL_STATUSES = [ 'Cancelled', 'Netted', 'Novated' ]
export const TRANSACTION_STATUSES = [ 'New', 'Amended', 'Superseded', ...TRANSACTION_CANCEL_STATUSES ]
|
Use byte strings after serializing with serde
The pymemcache client will return a byte string, so we'll do the same to test that the deserializer works as expected.
This currently fails with Python 3.
|
from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
# pymemcache stores values as byte strings, so we immediately the value
# if needed so deserialized works as it would with a real server
if not isinstance(serialized, six.binary_type):
serialized = six.text_type(serialized).encode('ascii')
deserialized = python_memcache_deserializer(b'key', serialized, flags)
assert deserialized == value
def test_bytes(self):
self.check(b'value')
def test_unicode(self):
self.check(u'value')
def test_int(self):
self.check(1)
def test_long(self):
self.check(123123123123123123123)
def test_pickleable(self):
self.check({'a': 'dict'})
|
from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
deserialized = python_memcache_deserializer(b'key', serialized, flags)
assert deserialized == value
def test_str(self):
self.check('value')
def test_int(self):
self.check(1)
def test_long(self):
self.check(123123123123123123123)
def test_pickleable(self):
self.check({'a': 'dict'})
|
Fix bug where base route would not resolve on page refresh.
|
(function () {
'use strict';
var module = angular.module('app', [
'ui.router',
'ui.bootstrap',
'content'
]);
module.config([
'$stateProvider',
'$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
views: {
main: {
templateUrl: 'templates/app/home.html'
}
}
})
}
]);
}());
|
(function () {
'use strict';
var module = angular.module('app', [
'ui.router',
'ui.bootstrap',
'content'
]);
module.config([
'$stateProvider',
'$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '',
views: {
main: {
templateUrl: 'templates/app/home.html'
}
}
})
}
]);
}());
|
Use constant instead of new instance.
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import org.junit.Test;
/**
* Really not a lot to do here, but checking that no
* Exceptions are thrown.
*
*/
public class NullWriterTest {
@Test
public void testNull() {
final char[] chars = new char[] { 'A', 'B', 'C' };
try (final NullWriter writer = NullWriter.NULL_WRITER) {
writer.write(1);
writer.write(chars);
writer.write(chars, 1, 1);
writer.write("some string");
writer.write("some string", 2, 2);
writer.flush();
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import org.junit.Test;
/**
* Really not a lot to do here, but checking that no
* Exceptions are thrown.
*
*/
public class NullWriterTest {
@Test
public void testNull() {
final char[] chars = new char[] { 'A', 'B', 'C' };
try (final NullWriter writer = new NullWriter()) {
writer.write(1);
writer.write(chars);
writer.write(chars, 1, 1);
writer.write("some string");
writer.write("some string", 2, 2);
writer.flush();
}
}
}
|
Move custom struct for marshal json to MarshalJSON method
|
package operations
import (
"encoding/json"
"time"
"github.com/omise/omise-go"
)
// List contains fields that represent parameters common to most list operations. List
// struct is not an operation in and of itself and cannot be used with client.Do directly.
// Use one of the predefined XXXList operations defined blow instead and supply List
// struct as the first field.
//
// See the Pagination and Lists documentation at https://www.omise.co/api-pagination for
// more information.
type List struct {
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
From time.Time `json:"-"`
To time.Time `json:"-"`
Order omise.Ordering `json:"order,omitempty"`
}
// MarshalJSON List type
func (l List) MarshalJSON() ([]byte, error) {
type Alias List
params := struct {
Alias
PFrom *time.Time `json:"from,omitempty"`
PTo *time.Time `json:"to,omitempty"`
}{
Alias: Alias(l),
}
if !l.From.IsZero() {
params.PFrom = &l.From
}
if !l.To.IsZero() {
params.PTo = &l.To
}
return json.Marshal(params)
}
|
package operations
import (
"encoding/json"
"time"
"github.com/omise/omise-go"
)
// List contains fields that represent parameters common to most list operations. List
// struct is not an operation in and of itself and cannot be used with client.Do directly.
// Use one of the predefined XXXList operations defined blow instead and supply List
// struct as the first field.
//
// See the Pagination and Lists documentation at https://www.omise.co/api-pagination for
// more information.
type List struct {
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
From time.Time `json:"-"`
To time.Time `json:"-"`
Order omise.Ordering `json:"order,omitempty"`
NullableFrom *time.Time `json:"from,omitempty"`
NullableTo *time.Time `json:"to,omitempty"`
}
type optionalFieldList List
// MarshalJSON List type
func (l List) MarshalJSON() ([]byte, error) {
l.SetOptionalField()
return json.Marshal(optionalFieldList(l))
}
func (l *List) SetOptionalField() {
if !l.From.IsZero() {
l.NullableFrom = &l.From
}
if !l.To.IsZero() {
l.NullableTo = &l.To
}
}
|
Load and check the plays in the playbook.
|
package main
import (
"flag"
"log"
"os"
)
var (
PlaybookFile = flag.String("play", "site.yml", "Path to the playbook to execute")
InventoryFile = flag.String("i", "hosts", "Path to the inventory file")
LimitHosts = flag.String("l", "", "Limit hosts")
)
func main() {
flag.Parse()
log.SetFlags(0)
log.SetOutput(os.Stdout)
inv, err := LoadInventoryFile(*InventoryFile)
if err != nil {
log.Fatalf("error loading inventory file %q reason=%s", *InventoryFile, err.Error())
}
if ngroups := len(inv); ngroups == 1 {
log.Println("Loaded 1 group from inventory")
} else {
log.Printf("Loaded %d groups from inventory", ngroups)
}
// Run a sanity check on the inventory groups.
for _, g := range inv {
if err = g.Check(); err != nil {
log.Fatalf("Error in group %q: %s", g.Name, err.Error())
}
}
// Load the playbook.
plays, err := LoadPlaybook(*PlaybookFile)
if err != nil {
log.Fatalf("Error loading playbook %q: %s", *PlaybookFile, err.Error())
}
if nplays := len(plays); nplays == 1 {
log.Println("Loaded 1 play")
} else {
log.Printf("Loaded %d plays", len(plays))
}
// Check the plays.
for _, p := range plays {
if err := p.Check(); err != nil {
log.Fatalf("Error in play %q: %s", p.Name, err.Error())
}
}
return
}
|
package main
import (
"flag"
"log"
"os"
)
var (
PlaybookFile = flag.String("play", "site.yml", "Path to the playbook to execute")
InventoryFile = flag.String("i", "hosts", "Path to the inventory file")
LimitHosts = flag.String("l", "", "Limit hosts")
)
func main() {
flag.Parse()
log.SetFlags(0)
log.SetOutput(os.Stdout)
inv, err := LoadInventoryFile(*InventoryFile)
if err != nil {
log.Fatalf("error loading inventory file %q reason=%s", *InventoryFile, err.Error())
}
if ngroups := len(inv); ngroups == 1 {
log.Println("Loaded 1 group from inventory")
} else {
log.Printf("Loaded %d groups from inventory", ngroups)
}
// Run a sanity check on the inventory groups.
for _, g := range inv {
if err = g.Check(); err != nil {
log.Fatalf("Error in group %q: %s", g.Name, err.Error())
}
}
return
}
|
Fix model not being passed in snippet recursion
|
function dieRoll (min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function processDirective (directive, model, cb) {
if (directive[0] === ':') {
return cb(directive.slice(1), model);
}
if (directive[0] === '#') {
return dieRoll(...directive.slice(1).split('-').map(n => parseInt(n, 10)));
}
if (directive.indexOf('.') !== -1) {
const propChain = directive.split('.');
return propChain.reduce((obj, prop) => obj[prop], model);
}
return `${model[directive]}`;
}
export default function template (phrase, model, cb) {
const [openBracket, closeBracket] = [phrase.indexOf('['), phrase.indexOf(']')];
if (openBracket === -1) return phrase;
if (closeBracket === -1) {
throw new Error(`Missing close bracket in phrase: ${phrase}`);
}
const before = phrase.slice(0, openBracket);
const after = phrase.slice(closeBracket + 1);
const directive = phrase.substring(openBracket + 1, closeBracket);
return template(
`${before}${processDirective(directive, model, cb)}${after}`,
model,
cb
);
}
|
function dieRoll (min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function processDirective (directive, model, cb) {
if (directive[0] === ':') {
return cb(directive.slice(1));
}
if (directive[0] === '#') {
return dieRoll(...directive.slice(1).split('-').map(n => parseInt(n, 10)));
}
if (directive.indexOf('.') !== -1) {
const propChain = directive.split('.');
return propChain.reduce((obj, prop) => obj[prop], model);
}
return `${model[directive]}`;
}
export default function template (phrase, model, cb) {
const [openBracket, closeBracket] = [phrase.indexOf('['), phrase.indexOf(']')];
if (openBracket === -1) return phrase;
if (closeBracket === -1) {
throw new Error(`Missing close bracket in phrase: ${phrase}`);
}
const before = phrase.slice(0, openBracket);
const after = phrase.slice(closeBracket + 1);
const directive = phrase.substring(openBracket + 1, closeBracket);
return template(
`${before}${processDirective(directive, model, cb)}${after}`,
model,
cb
);
}
|
Make IDE stop complaining about syntax error
|
<?php
namespace PHPFastCGI\FastCGIDaemon\Driver;
class DriverContainer implements DriverContainerInterface
{
/**
* @var array
*/
private $drivers;
/**
* Constructor.
*/
public function __construct()
{
$this->drivers = [
'userland' => [
'object' => null,
'classPath' => 'PHPFastCGI\FastCGIDaemon\Driver\Userland\UserlandDaemonFactory',
],
];
}
/**
* {@inheritdoc}
*/
public function getFactory($driver)
{
if (!isset($this->drivers[$driver])) {
throw new \InvalidArgumentException('Unknown driver: '.$driver);
}
if (null === $this->drivers[$driver]['object']) {
$class = $this->drivers[$driver]['classPath'];
$this->drivers[$driver]['object'] = new $class();
}
return $this->drivers[$driver]['object'];
}
}
|
<?php
namespace PHPFastCGI\FastCGIDaemon\Driver;
class DriverContainer implements DriverContainerInterface
{
/**
* @var array
*/
private $drivers;
/**
* Constructor.
*/
public function __construct()
{
$this->drivers = [
'userland' => [
'object' => null,
'classPath' => 'PHPFastCGI\FastCGIDaemon\Driver\Userland\UserlandDaemonFactory',
],
];
}
/**
* {@inheritdoc}
*/
public function getFactory($driver)
{
if (!isset($this->drivers[$driver])) {
throw new \InvalidArgumentException('Unknown driver: '.$driver);
}
if (null === $this->drivers[$driver]['object']) {
$this->drivers[$driver]['object'] = new $this->drivers[$driver]['classPath']();
}
return $this->drivers[$driver]['object'];
}
}
|
Replace matrixStack in test living renderer
|
package info.u_team.u_team_test.entity.render;
import com.mojang.blaze3d.vertex.PoseStack;
import info.u_team.u_team_test.TestMod;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.client.renderer.entity.ZombieRenderer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.monster.Zombie;
public class TestLivingEntityRenderer extends ZombieRenderer {
private static final ResourceLocation TEXTURE = new ResourceLocation(TestMod.MODID, "textures/entity/test_living/test_living.png");
public TestLivingEntityRenderer(EntityRendererProvider.Context renderManager) {
super(renderManager);
}
@Override
protected void scale(Zombie zombie, PoseStack poseStack, float partialTickTime) {
poseStack.scale(1.8F, 1.8F, 1.8F);
super.scale(zombie, poseStack, partialTickTime);
}
@Override
public ResourceLocation getTextureLocation(Zombie entity) {
return TEXTURE;
}
}
|
package info.u_team.u_team_test.entity.render;
import com.mojang.blaze3d.vertex.PoseStack;
import info.u_team.u_team_test.TestMod;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.client.renderer.entity.ZombieRenderer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.monster.Zombie;
public class TestLivingEntityRenderer extends ZombieRenderer {
private static final ResourceLocation TEXTURE = new ResourceLocation(TestMod.MODID, "textures/entity/test_living/test_living.png");
public TestLivingEntityRenderer(EntityRendererProvider.Context renderManager) {
super(renderManager);
}
@Override
protected void scale(Zombie zombie, PoseStack matrixStack, float partialTickTime) {
matrixStack.scale(1.8F, 1.8F, 1.8F);
super.scale(zombie, matrixStack, partialTickTime);
}
@Override
public ResourceLocation getTextureLocation(Zombie entity) {
return TEXTURE;
}
}
|
Add tests to be implemented for persist
|
import { createCookieStore } from '../../src/storage'
import Cookie from 'js-cookie'
describe('cookie store', () => {
describe('#persist', () => {
it('returns resolved promise', () => {
const cookieStore = createCookieStore()
expect(cookieStore.persist()).resolves
})
it('saves data to cookie with default key', () => {
const cookieStore = createCookieStore()
const spy = jest.spyOn(Cookie, 'set')
cookieStore.persist({ key: 'value' })
expect(spy).toHaveBeenCalledWith(
'redux-simple-auth-session',
{ key: 'value' },
{ domain: null, expires: null, path: '/', secure: false }
)
})
xit('allows a configured cookie name')
xit('allows a custom path')
xit('allows a custom domain')
xit('allows setting expiration')
xit('allows setting secure cookie')
})
})
|
import { createCookieStore } from '../../src/storage'
import Cookie from 'js-cookie'
describe('cookie store', () => {
describe('#persist', () => {
it('returns resolved promise', () => {
const cookieStore = createCookieStore()
expect(cookieStore.persist()).resolves
})
it('saves data to cookie with default key', () => {
const cookieStore = createCookieStore()
const spy = jest.spyOn(Cookie, 'set')
cookieStore.persist({ key: 'value' })
expect(spy).toHaveBeenCalledWith(
'redux-simple-auth-session',
{ key: 'value' },
{ domain: null, expires: null, path: '/', secure: false }
)
})
})
})
|
Use full path of template as filename when compiling
|
import os.path
from .compiler import kompile
PATHS = []
class TemplateNotFound(Exception):
pass
def add_path(path):
path = os.path.abspath(path)
if path not in PATHS:
PATHS.append(path)
def load_template(name, paths=None, raw=False):
if paths is None:
paths = PATHS[:]
for path in paths:
full_name = os.path.abspath(os.path.join(path, name))
if not full_name.startswith(path):
continue
try:
with open(full_name, encoding='utf-8') as fin:
src = fin.read()
return kompile(src, raw=raw, filename=full_name)
except FileNotFoundError:
pass
else:
raise TemplateNotFound(name)
|
import os.path
from .compiler import kompile
PATHS = []
class TemplateNotFound(Exception):
pass
def add_path(path):
path = os.path.abspath(path)
if path not in PATHS:
PATHS.append(path)
def load_template(name, paths=None, raw=False):
if paths is None:
paths = PATHS[:]
for path in paths:
full_name = os.path.abspath(os.path.join(path, name))
if not full_name.startswith(path):
continue
try:
with open(full_name, encoding='utf-8') as fin:
src = fin.read()
return kompile(src, raw=raw, filename=name)
except FileNotFoundError:
pass
else:
raise TemplateNotFound(name)
|
Set instance to null if client is closed
|
import { MongoClient } from 'mongodb';
const MONGODB_URI = process.env.MONGODB_URI;
// Database Name
const dbName = 'cofacts';
export default class CofactsMongoClient {
/**
* @type {?Promise<CofactsMongoClient>}
*/
static _instance = null;
static async getInstance() {
if (this._instance === null) {
this._instance = new Promise(async (resolve, reject) => {
const client = new CofactsMongoClient(MONGODB_URI);
try {
await client.mongoClient.connect();
resolve(client);
} catch (e) {
reject(e);
}
});
}
return this._instance;
}
constructor(uri, options) {
this.mongoClient = new MongoClient(uri, options);
}
get db() {
return this.mongoClient.db(dbName);
}
/**
*
* @param {string} name
*/
async collection(name) {
return this.db.collection(name);
}
async close() {
await this.mongoClient.close();
this._instance = null;
}
}
|
import { MongoClient } from 'mongodb';
const MONGODB_URI = process.env.MONGODB_URI;
// Database Name
const dbName = 'cofacts';
export default class CofactsMongoClient {
/**
* @type {?Promise<CofactsMongoClient>}
*/
static _instance = null;
static async getInstance() {
if (this._instance === null) {
this._instance = new Promise(async (resolve, reject) => {
const client = new CofactsMongoClient(MONGODB_URI);
try {
await client.mongoClient.connect();
resolve(client);
} catch (e) {
reject(e);
}
});
}
return this._instance;
}
constructor(uri, options) {
this.mongoClient = new MongoClient(uri, options);
}
get db() {
return this.mongoClient.db(dbName);
}
/**
*
* @param {string} name
*/
async collection(name) {
return this.db.collection(name);
}
async close() {
return this.mongoClient.close();
}
}
|
Add onChange handling -- part of STRIPES-85.
|
import React from 'react';
import css from './FilterPaneSearch.css';
import Icon from '@folio/stripes-components/lib/Icon';
import Button from '@folio/stripes-components/lib/Button';
class FilterPaneSearch extends React.Component{
constructor(props){
super(props);
this.searchInput = null;
}
clearSearchField(){
this.searchInput.value = '';
const evt = new Event('input', {bubbles: true});
this.searchInput.dispatchEvent(evt);
}
onChange() {
console.log("changed: new value =", this.searchInput.value);
// XXX We need to somehow feed the changed value into stripes-connect for the parent component
}
render(){
return(
<div className={css.headerSearchContainer}>
<div style={{alignSelf:"center"}}><Icon icon="search"/></div>
<input className={css.headerSearchInput} ref={(ref) => this.searchInput = ref} type="text" value = {this.props.value} onChange={this.onChange.bind(this)} placeholder="Search"/>
<Button className={css.headerSearchClearButton} onClick={this.clearSearchField.bind(this)} ><Icon icon="clearX" iconClassName={css.clearIcon}/></Button>
</div>
);
}
}
export default FilterPaneSearch;
|
import React from 'react';
import css from './FilterPaneSearch.css';
import Icon from '@folio/stripes-components/lib/Icon';
import Button from '@folio/stripes-components/lib/Button';
class FilterPaneSearch extends React.Component{
constructor(props){
super(props);
this.searchInput = null;
}
clearSearchField(){
this.searchInput.value = '';
const evt = new Event('input', {bubbles: true});
this.searchInput.dispatchEvent(evt);
}
render(){
return(
<div className={css.headerSearchContainer}>
<div style={{alignSelf:"center"}}><Icon icon="search"/></div>
<input className={css.headerSearchInput} ref={(ref) => this.searchInput = ref} type="text" value = {this.props.value} onChange={this.props.onChange} placeholder="Search"/>
<Button className={css.headerSearchClearButton} onClick={this.clearSearchField.bind(this)} ><Icon icon="clearX" iconClassName={css.clearIcon}/></Button>
</div>
);
}
}
export default FilterPaneSearch;
|
Remove unneeded code to disable audio muting.
|
import Phaser from 'phaser'
import { centerGameObjects } from '../utils'
export default class extends Phaser.State {
init () {}
preload () {
this.loaderBg = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBg')
this.loaderBar = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBar')
centerGameObjects([this.loaderBg, this.loaderBar])
this.game.load.setPreloadSprite(this.loaderBar)
//
// load your assets
//
this.load.image('bullet', 'assets/images/bullet.png')
this.load.spritesheet('player', 'assets/images/player.png',32,32,12)
this.load.image('ship', 'assets/images/ship.png')
this.load.image('enemy', 'assets/images/enemyship.png')
this.load.image('space', 'assets/images/space.png')
this.load.image('room', 'assets/images/room.png')
}
create () {
this.state.start('Shooter')
}
}
|
import Phaser from 'phaser'
import { centerGameObjects } from '../utils'
export default class extends Phaser.State {
init () {
this.game.sound.mute = false
}
preload () {
this.loaderBg = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBg')
this.loaderBar = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBar')
centerGameObjects([this.loaderBg, this.loaderBar])
this.game.load.setPreloadSprite(this.loaderBar)
//
// load your assets
//
this.load.image('bullet', 'assets/images/bullet.png')
this.load.spritesheet('player', 'assets/images/player.png',32,32,12)
this.load.image('ship', 'assets/images/ship.png')
this.load.image('enemy', 'assets/images/enemyship.png')
this.load.image('space', 'assets/images/space.png')
this.load.image('room', 'assets/images/room.png')
}
create () {
this.state.start('Shooter')
}
}
|
Add the user detail ID to the form validation
|
<?php
namespace AppBundle\Form\Type;
use AppBundle\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Class UserType
* @package AppBundle\Form\Type
*/
class UserType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', null, [
'description' => 'The user name'
]);
$builder->add('userDetails', EntityType::class, [
'class' => 'AppBundle:UserDetail',
'description' => 'The user detail id',
]);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
'csrf_protection' => false,
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';
}
}
|
<?php
namespace AppBundle\Form\Type;
use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Class UserType
* @package AppBundle\Form\Type
*/
class UserType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', null, [
'description' => 'The user name'
]);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
'csrf_protection' => false,
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';
}
}
|
[Espresso] Fix stack to only protect closures
|
<?php
namespace React\Espresso;
use React\EventLoop\Factory;
use React\Socket\Server as SocketServer;
use React\Http\Server as HttpServer;
class Stack extends \Pimple
{
public function __construct($app)
{
$this['loop'] = $this->share(function () {
return Factory::create();
});
$this['socket'] = $this->share(function ($stack) {
return new SocketServer($stack['loop']);
});
$this['http'] = $this->share(function ($stack) {
return new HttpServer($stack['socket']);
});
$this['app'] = $app instanceof \Closure ? $this->protect($app) : $app;
}
public function listen($port, $host = '127.0.0.1')
{
$this['http']->on('request', $this['app']);
$this['socket']->listen($port, $host);
$this['loop']->run();
}
}
|
<?php
namespace React\Espresso;
use React\EventLoop\Factory;
use React\Socket\Server as SocketServer;
use React\Http\Server as HttpServer;
class Stack extends \Pimple
{
public function __construct($app)
{
$this['loop'] = $this->share(function () {
return Factory::create();
});
$this['socket'] = $this->share(function ($stack) {
return new SocketServer($stack['loop']);
});
$this['http'] = $this->share(function ($stack) {
return new HttpServer($stack['socket']);
});
$this['app'] = $this->protect($app);
}
public function listen($port, $host = '127.0.0.1')
{
$this['http']->on('request', $this['app']);
$this['socket']->listen($port, $host);
$this['loop']->run();
}
}
|
Change deprecated $app->bindShared() to $app->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 the deployment config file be optional
It shouldn't be required
|
<?php
/**
* @author Andrew Coulton <andrew@ingenerator.com>
* @copyright 2014 inGenerator Ltd
* @licence BSD
*/
namespace Ingenerator\Config;
use Ingenerator\Config\JsonConfigReader;
/**
* Initialises configuration for the application - used to allow reloading the same config in a behat test
* when asserting that config has changed.
*/
class ConfigInitialiser {
public static function user_config_path()
{
return APPPATH.'/config/user_config_overrides.json';
}
public static function deployment_config_path()
{
return APPPATH.'/config/deployment_config_overrides.json';
}
public static function initialise(\Config $config)
{
$config->attach(new \Config_File);
foreach (
array(self::deployment_config_path(), self::user_config_path())
as $file
) {
if (file_exists($file)) {
$config->attach(new JsonConfigReader($file));
}
}
return $config;
}
}
|
<?php
/**
* @author Andrew Coulton <andrew@ingenerator.com>
* @copyright 2014 inGenerator Ltd
* @licence BSD
*/
namespace Ingenerator\Config;
use Ingenerator\Config\JsonConfigReader;
/**
* Initialises configuration for the application - used to allow reloading the same config in a behat test
* when asserting that config has changed.
*/
class ConfigInitialiser {
public static function user_config_path()
{
return APPPATH.'/config/user_config_overrides.json';
}
public static function initialise(\Config $config)
{
$config->attach(new \Config_File);
$config->attach(new JsonConfigReader(APPPATH.'/config/deployment_config_overrides.json'));
if (file_exists(self::user_config_path()))
{
$config->attach(new JsonConfigReader(self::user_config_path()));
}
return $config;
}
}
|
patron-client: Update syntax for creating the store, to harmonize with more recent examples
|
import { browserHistory } from 'react-router'
import thunkMiddleware from 'redux-thunk'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import createLogger from 'redux-logger'
import persistState from 'redux-localstorage'
import adapter from 'redux-localstorage/lib/adapters/localStorage'
import filter from 'redux-localstorage-filter'
import rootReducer from '../reducers'
const storage = compose(
filter([ 'application.locale' ])
)(adapter(window.localStorage))
const reduxRouterMiddleware = routerMiddleware(browserHistory)
const middleware = [ thunkMiddleware, reduxRouterMiddleware ]
if (process.env.NODE_ENV !== 'production') {
const loggerMiddleware = createLogger()
middleware.push(loggerMiddleware)
}
const store = createStore(rootReducer, compose(
applyMiddleware(...middleware),
persistState(storage, 'patron-client')
))
export default store
|
import { browserHistory } from 'react-router'
import thunkMiddleware from 'redux-thunk'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import createLogger from 'redux-logger'
import persistState from 'redux-localstorage'
import adapter from 'redux-localstorage/lib/adapters/localStorage'
import filter from 'redux-localstorage-filter'
import rootReducer from '../reducers'
const storage = compose(
filter([ 'application.locale' ])
)(adapter(window.localStorage))
const reduxRouterMiddleware = routerMiddleware(browserHistory)
let middleware = [ thunkMiddleware, reduxRouterMiddleware ]
if (process.env.NODE_ENV !== 'production') {
// Only apply in development mode
const loggerMiddleware = createLogger()
middleware = [ ...middleware, loggerMiddleware ]
}
const createPersistentStoreWithMiddleware = compose(
applyMiddleware(...middleware),
persistState(storage, 'patron-client')
)(createStore)
const store = createPersistentStoreWithMiddleware(rootReducer)
export default store
|
Make the secure session cookie setting case-insensitive
|
import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'].lower() != 'false'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
|
import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'] != 'False'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
|
Add example two: remove information leaking response headers
|
var path = require('path');
module.exports = {
one: function (req, res) {
/* vcl:
vcl 4.0; backend default { .host = "www.vclfiddle.net"; .port = "80"; }
sub vcl_backend_response {
if (beresp.http.Content-Type ~ "^image/") {
set beresp.http.Cache-Control = "public, max-age=300";
set beresp.ttl = 300s;
}
}
*/
/* curl:
curl "http://www.vclfiddle.net/example/one"
*/
req.session = null; // don't send Set-Cookie: sails.sid=
return res
.header('Link', '<https://www.flickr.com/photos/crazymandi/8165527856/>; rel=alternate')
.header('Cache-Control', 'public, max-age=0')
.sendfile(path.join(__dirname, 'flickr-crazymandi-puppy.jpg'));
},
two: function (req, res) {
/* vcl:
vcl 4.0; backend default { .host = "www.vclfiddle.net"; .port = "80"; }
sub vcl_deliver {
unset resp.http.Server;
unset resp.http.X-Powered-By;
}
*/
/* curl:
curl "http://www.vclfiddle.net/example/two"
*/
return res.send('Where are the Server and X-Powered-By response headers?');
}
}
|
var path = require('path');
module.exports = {
one: function (req, res) {
/* vcl:
vcl 4.0; backend default { .host = "www.vclfiddle.net"; .port = "80"; }
sub vcl_backend_response {
if (beresp.http.Content-Type ~ "^image/") {
set beresp.http.Cache-Control = "public, max-age=300";
set beresp.ttl = 300s;
}
}
*/
/* curl:
curl "http://www.vclfiddle.net/example/one"
*/
req.session = null; // don't send Set-Cookie: sails.sid=
return res
.header('Link', '<https://www.flickr.com/photos/crazymandi/8165527856/>; rel=alternate')
.header('Cache-Control', 'public, max-age=0')
.sendfile(path.join(__dirname, 'flickr-crazymandi-puppy.jpg'));
}
}
|
Check that single element in array is a valid React element
|
import React from 'react';
const ReactUil = {
/**
* Wrap React elements
*
* If elements is an array with a single element, it will not be wrapped
* unless alwaysWrap is true.
*
* @param {Array.<ReactElement>|ReactElement} elements
* @param {function|String} wrapper component
* @param {boolean} [alwaysWrap]
*
* @returns {ReactElement} wrapped react elements
*/
wrapElements(elements, wrapper = 'div', alwaysWrap = false) {
if (elements == null && !alwaysWrap) {
return null;
}
if (Array.isArray(elements) && elements.length === 1
&& React.isValidElement(elements[0]) && !alwaysWrap) {
return elements[0];
}
if (React.isValidElement(elements) && !alwaysWrap) {
return elements;
}
return React.createElement(wrapper, null, elements);
}
};
module.exports = ReactUil;
|
import React from 'react';
const ReactUil = {
/**
* Wrap React elements
*
* If elements is an array with a single element, it will not be wrapped
* unless alwaysWrap is true.
*
* @param {Array.<ReactElement>|ReactElement} elements
* @param {function|String} wrapper component
* @param {boolean} [alwaysWrap]
*
* @returns {ReactElement} wrapped react elements
*/
wrapElements(elements, wrapper = 'div', alwaysWrap = false) {
if (elements == null && !alwaysWrap) {
return null;
}
if (Array.isArray(elements) && elements.length === 1 && !alwaysWrap) {
return elements[0];
}
if (React.isValidElement(elements) && !alwaysWrap) {
return elements;
}
return React.createElement(wrapper, null, elements);
}
};
module.exports = ReactUil;
|
Allow each event registration to have several ticket types attached to it, each with a different quantity.
|
<?php
/**
* Represents a registration to an event.
*
* @package silverstripe-eventmanagement
*/
class EventRegistration extends DataObject {
public static $db = array(
'Name' => 'Varchar(255)',
'Email' => 'Varchar(255)',
'Confirmed' => 'Boolean',
'Token' => 'Varchar(48)'
);
public static $has_one = array(
'Time' => 'RegisterableDateTime',
'Member' => 'Member'
);
public static $many_many = array(
'Tickets' => 'EventTicket'
);
public static $many_many_extraFields = array(
'Tickets' => array('Quantity' => 'Int')
);
public static $summary_fields = array(
'Name' => 'Name',
'Email' => 'Email',
'Event.Title' => 'Event',
'Places' => 'Places',
'DatesSummary' => 'Date(s)',
'TimesSummary' => 'Time(s)'
);
protected function onBeforeWrite() {
if (!$this->isInDB()) {
$generator = new RandomGenerator();
$this->Token = $generator->generateHash('sha1');
}
parent::onBeforeWrite();
}
/**
* @return string
*/
public function DatesSummary() {
return $this->Time()->_Dates();
}
/**
* @return string
*/
public function TimesSummary() {
return $this->Time()->_Times();
}
}
|
<?php
/**
* Represents a registration to an event.
*
* @package silverstripe-eventmanagement
*/
class EventRegistration extends DataObject {
public static $db = array(
'Name' => 'Varchar(255)',
'Email' => 'Varchar(255)',
'Places' => 'Int',
'Confirmed' => 'Boolean',
'Token' => 'Varchar(48)'
);
public static $has_one = array(
'Time' => 'RegisterableDateTime',
'Ticket' => 'EventTicket',
'Member' => 'Member'
);
public static $summary_fields = array(
'Name' => 'Name',
'Email' => 'Email',
'Event.Title' => 'Event',
'Places' => 'Places',
'DatesSummary' => 'Date(s)',
'TimesSummary' => 'Time(s)'
);
protected function onBeforeWrite() {
if (!$this->isInDB()) {
$generator = new RandomGenerator();
$this->Token = $generator->generateHash('sha1');
}
parent::onBeforeWrite();
}
/**
* @return string
*/
public function DatesSummary() {
return $this->Time()->_Dates();
}
/**
* @return string
*/
public function TimesSummary() {
return $this->Time()->_Times();
}
}
|
Remove this os.Remove, it is handled inside inceptionmain now.
|
/**
* Copyright 2014 Paul Querna
*
* 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 generator
import (
"errors"
"fmt"
)
func GenerateFiles(inputPath string, outputPath string) error {
packageName, structs, err := ExtractStructs(inputPath)
if err != nil {
return err
}
im := NewInceptionMain(inputPath, outputPath)
err = im.Generate(packageName, structs)
if err != nil {
return errors.New(fmt.Sprintf("error=%v path=%q", err, im.TempMainPath))
}
err = im.Run()
if err != nil {
return err
}
return nil
}
|
/**
* Copyright 2014 Paul Querna
*
* 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 generator
import (
"errors"
"fmt"
"os"
)
func GenerateFiles(inputPath string, outputPath string) error {
packageName, structs, err := ExtractStructs(inputPath)
if err != nil {
return err
}
im := NewInceptionMain(inputPath, outputPath)
err = im.Generate(packageName, structs)
if err != nil {
return errors.New(fmt.Sprintf("error=%v path=%q", err, im.TempMainPath))
}
defer os.Remove(im.TempMainPath)
err = im.Run()
if err != nil {
return err
}
return nil
}
|
Fix Python 2 test failure
|
'''Test issue that arises when too many labels are added to NER model.'''
from __future__ import unicode_literals
import random
from ...lang.en import English
def train_model(train_data, entity_types):
nlp = English(pipeline=[])
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner)
for entity_type in list(entity_types):
ner.add_label(entity_type)
optimizer = nlp.begin_training()
# Start training
for i in range(20):
losses = {}
index = 0
random.shuffle(train_data)
for statement, entities in train_data:
nlp.update([statement], [entities], sgd=optimizer, losses=losses, drop=0.5)
return nlp
def test_train_with_many_entity_types():
train_data = []
train_data.extend([("One sentence", {"entities": []})])
entity_types = [str(i) for i in range(1000)]
model = train_model(train_data, entity_types)
|
'''Test issue that arises when too many labels are added to NER model.'''
import random
from ...lang.en import English
def train_model(train_data, entity_types):
nlp = English(pipeline=[])
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner)
for entity_type in list(entity_types):
ner.add_label(entity_type)
optimizer = nlp.begin_training()
# Start training
for i in range(20):
losses = {}
index = 0
random.shuffle(train_data)
for statement, entities in train_data:
nlp.update([statement], [entities], sgd=optimizer, losses=losses, drop=0.5)
return nlp
def test_train_with_many_entity_types():
train_data = []
train_data.extend([("One sentence", {"entities": []})])
entity_types = [str(i) for i in range(1000)]
model = train_model(train_data, entity_types)
|
Split fill and stroke functions
|
import historySvg from 'static/assets/history-16.svg';
import bookmarkSvg from 'static/assets/bookmark.svg';
import { compose } from 'redux';
// Firefox doesnt like # signs in data uris so hex values are a no-go,
// inline the rgb values instead so the colors show up.
export const BOOKMARK_COLOR = 'rgba(54, 57, 89)';
export const HISTORY_COLOR = 'rgb(68, 0, 113)';
const fillSvgUri = replaceAttr('fill');
const strokeSvgUri = replaceAttr('stroke');
export const filledHistorySvg = fillSvgUri(historySvg, HISTORY_COLOR);
export const filledBookmarkSvg = fillAndStroke(bookmarkSvg, BOOKMARK_COLOR);
function replaceAttr(key) {
return function replace(uri, value) {
const pattern = new RegExp(`(${key}=')[\\w-_]+(')`);
return uri.replace(pattern, (_, m1, m2) => m1 + value + m2);
};
}
// Given a non-base64 encoded data uri of an svg, along with valid-string
// values for the svg fill and stroke attributes, return a new
// svg data uri with the given fill and stroke settings
function fillAndStroke(svgDataUri, fill, stroke) {
if (!fill && !stroke) {
return svgDataUri;
}
stroke = stroke || fill;
return compose(x => strokeSvgUri(x, stroke), fillSvgUri)(svgDataUri, fill);
}
|
import histSvg from 'static/assets/history-16.svg';
import bkmrkSvg from 'static/assets/bookmark.svg';
// Firefox doesnt like # signs in data uris so hex values are a no-go,
// inline the rgb values instead so the colors show up.
export const BOOKMARK_COLOR = 'rgba(54, 57, 89)';
export const HISTORY_COLOR = 'rgba(98, 0, 164)';
const historySvg = histSvg;
const bookmarkSvg = bkmrkSvg;
const historySvgFillStroke = (fill, stroke) =>
fillAndStroke(historySvg, fill, stroke);
const bookmarkSvgFillStroke = (fill, stroke) =>
fillAndStroke(bookmarkSvg, fill, stroke);
export const filledHistorySvg = historySvgFillStroke('white', HISTORY_COLOR);
export const filledBookmarkSvg = bookmarkSvgFillStroke(BOOKMARK_COLOR);
// Given a non-base64 encoded data uri of an svg, along with valid-string
// values for the svg fill and stroke attributes, return a new
// svg data uri with the given fill and stroke settings
function fillAndStroke(svgDataUri, fill, stroke) {
if (!fill && !stroke) {
return svgDataUri;
}
stroke = stroke || fill;
// Can't replace matched groups directly, just capture what we want
// saved
return svgDataUri.replace(
/(fill=')\w+(' stroke=')\w+(')/,
function replaceFillStroke(_, m1, m2, m3) {
// eslint-disable-next-line prefer-string-template
return m1 + fill + m2 + stroke + m3;
},
);
}
|
Drop FK before dropping instance_id column.
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.from sqlalchemy import *
from sqlalchemy import Column, Integer, String, MetaData, Table
meta = MetaData()
#
# Tables to alter
#
#
instance_id = Column('instance_id', Integer())
instance_uuid = Column('instance_uuid', String(255))
def upgrade(migrate_engine):
meta.bind = migrate_engine
migrations = Table('migrations', meta, autoload=True)
migrations.create_column(instance_uuid)
if migrate_engine.name == "mysql":
migrate_engine.execute("ALTER TABLE migrations DROP FOREIGN KEY " \
"`migrations_ibfk_1`;")
migrations.c.instance_id.drop()
def downgrade(migrate_engine):
meta.bind = migrate_engine
migrations = Table('migrations', meta, autoload=True)
migrations.c.instance_uuid.drop()
migrations.create_column(instance_id)
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.from sqlalchemy import *
from sqlalchemy import Column, Integer, String, MetaData, Table
meta = MetaData()
#
# Tables to alter
#
#
instance_id = Column('instance_id', Integer())
instance_uuid = Column('instance_uuid', String(255))
def upgrade(migrate_engine):
meta.bind = migrate_engine
migrations = Table('migrations', meta, autoload=True)
migrations.create_column(instance_uuid)
migrations.c.instance_id.drop()
def downgrade(migrate_engine):
meta.bind = migrate_engine
migrations = Table('migrations', meta, autoload=True)
migrations.c.instance_uuid.drop()
migrations.create_column(instance_id)
|
Remove deprecated Logger usage in Analytics
Change-Id: I66165a76f3a8a47af8473555c6280450835a75c2
|
/*
* Copyright Google 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.
*/
package com.google.samples.quickstart.analytics;
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
/**
* This is a subclass of {@link Application} used to provide shared objects for this app, such as
* the {@link Tracker}.
*/
public class AnalyticsApplication extends Application {
private Tracker mTracker;
/**
* Gets the default {@link Tracker} for this {@link Application}.
* @return tracker
*/
synchronized public Tracker getDefaultTracker() {
if (mTracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
mTracker = analytics.newTracker(R.xml.global_tracker);
}
return mTracker;
}
}
|
/*
* Copyright Google 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.
*/
package com.google.samples.quickstart.analytics;
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
/**
* This is a subclass of {@link Application} used to provide shared objects for this app, such as
* the {@link Tracker}.
*/
public class AnalyticsApplication extends Application {
private Tracker mTracker;
/**
* Gets the default {@link Tracker} for this {@link Application}.
* @return tracker
*/
synchronized public Tracker getDefaultTracker() {
if (mTracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
mTracker = analytics.newTracker(R.xml.global_tracker);
}
return mTracker;
}
}
|
Add support for `n` Node.js version manager
|
import os
import platform
import subprocess
IS_MACOS = platform.system() == 'Darwin'
IS_WINDOWS = platform.system() == 'Windows'
def node_bridge(data, bin, args=[]):
env = None
startupinfo = None
if IS_MACOS:
# GUI apps on macOS doesn't contain .bashrc/.zshrc set paths
env = os.environ.copy()
env['PATH'] += os.path.expanduser('~/n/bin')
env['PATH'] += ':/usr/local/bin'
if IS_WINDOWS:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try:
p = subprocess.Popen(['node', bin] + args,
stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
env=env, startupinfo=startupinfo)
except OSError:
raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.')
stdout, stderr = p.communicate(input=data.encode('utf-8'))
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if stderr:
raise Exception('Error: %s' % stderr)
else:
return stdout
|
import os
import platform
import subprocess
IS_MACOS = platform.system() == 'Darwin'
IS_WINDOWS = platform.system() == 'Windows'
def node_bridge(data, bin, args=[]):
env = None
startupinfo = None
if IS_MACOS:
# GUI apps on macOS doesn't contain .bashrc/.zshrc set paths
env = os.environ.copy()
env['PATH'] += ':/usr/local/bin'
if IS_WINDOWS:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try:
p = subprocess.Popen(['node', bin] + args,
stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
env=env, startupinfo=startupinfo)
except OSError:
raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.')
stdout, stderr = p.communicate(input=data.encode('utf-8'))
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if stderr:
raise Exception('Error: %s' % stderr)
else:
return stdout
|
Add truffle org to permission checking
|
const { execSync } = require("child_process");
const getPkgPermissions = userOrOrg => {
const bufferResponse = execSync(`npm access ls-packages ${userOrOrg}`);
const stringResponse = bufferResponse.toString();
return JSON.parse(stringResponse);
};
const orgs = ["trufflesuite", "truffle"];
for (let org of orgs) {
const permissions = getPkgPermissions(org);
const getNpmUsername = () => {
const bufferResponse = execSync("npm whoami");
return bufferResponse.toString();
};
const username = getNpmUsername();
const userPermissionsObject = getPkgPermissions(username);
for (const pkg in permissions) {
if (!userPermissionsObject[pkg])
throw new Error(`You don't have permissions to publish ${pkg}`);
if (permissions[pkg] !== userPermissionsObject[pkg])
throw new Error(`Missing correct 'read-write' access to ${pkg}`);
}
}
|
const { execSync } = require("child_process");
const getPkgPermissions = userOrOrg => {
const bufferResponse = execSync(`npm access ls-packages ${userOrOrg}`);
const stringResponse = bufferResponse.toString();
return JSON.parse(stringResponse);
};
const truffleSuiteOrgPermissionsObject = getPkgPermissions("trufflesuite");
const getNpmUsername = () => {
const bufferResponse = execSync("npm whoami");
return bufferResponse.toString();
};
const username = getNpmUsername();
const userPermissionsObject = getPkgPermissions(username);
for (const pkg in truffleSuiteOrgPermissionsObject) {
if (!userPermissionsObject[pkg])
throw new Error(`You don't have permissions to publish ${pkg}`);
if (truffleSuiteOrgPermissionsObject[pkg] !== userPermissionsObject[pkg])
throw new Error(`Missing correct 'read-write' access to ${pkg}`);
}
|
Add language to html tag
|
import React from 'react'
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { GA_TRACKING_ID } from 'libs/gtag'
export default class extends Document {
render() {
return (
<Html lang="en">
<Head>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`} />
<script
dangerouslySetInnerHTML={{
__html: `window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${GA_TRACKING_ID}', { page_path: window.location.pathname, }); `,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
|
import React from 'react'
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { GA_TRACKING_ID } from 'libs/gtag'
export default class extends Document {
render() {
return (
<Html>
<Head>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`} />
<script
dangerouslySetInnerHTML={{
__html: `window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${GA_TRACKING_ID}', { page_path: window.location.pathname, }); `,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
|
Check if $images exists in gallery upload view.
|
<div id="{{ $id or 'gallery-upload' }}" class="gallery-upload {{ $class or ''}}">
<p>
<button type="button" class="btn btn-default">{{ $button or 'Upload' }}</button>
<input type="file" class="hidden" accept="image/*">
</p>
<div class="image-gallery clearfix">
@if (isset($images))
@foreach ($images as $image)
<div class="image-preview" style="background-image:url({{$image->getThumbUrl()}})">
<span><i class="fa fa-times"></i></span>
<input type="hidden" name="{{ $name or 'images' }}[]" value="{{ $image_id or '' }}">
</div>
@endforeach
@endif
</div>
<p class="text-muted">Drag and drop to change the order of images.</p>
<template>
<div class="image-preview">
<span><i class="fa fa-times"></i></span>
<input type="hidden" name="{{ $name or 'images' }}[]">
</div>
</template>
</div>
|
<div id="{{ $id or 'gallery-upload' }}" class="gallery-upload {{ $class or ''}}">
<p>
<button type="button" class="btn btn-default">{{ $button or 'Upload' }}</button>
<input type="file" class="hidden" accept="image/*">
</p>
<div class="image-gallery clearfix">
@foreach ($images as $image)
<div class="image-preview" style="background-image:url({{$image->getThumbUrl()}})">
<span><i class="fa fa-times"></i></span>
<input type="hidden" name="{{ $name or 'images' }}[]" value="{{ $image_id or '' }}">
</div>
@endforeach
</div>
<p class="text-muted">Drag and drop to change the order of images.</p>
<template>
<div class="image-preview">
<span><i class="fa fa-times"></i></span>
<input type="hidden" name="{{ $name or 'images' }}[]">
</div>
</template>
</div>
|
Fix the easter-egg command name in tests.
|
package fi.helsinki.cs.tmc.cli.command;
import static org.junit.Assert.assertTrue;
import fi.helsinki.cs.tmc.cli.Application;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class TestCommandTest {
Application app;
OutputStream os;
@Before
public void setUp() {
app = new Application();
os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);
}
@Test
public void runWorksRightWithoutOption() {
String[] args = {"easter-egg"};
app.run(args);
assertTrue(os.toString().contains("Let's run easter egg."));
}
@Test
public void runWorksRightWithOption() {
String[] args = {"easter-egg", "-a"};
app.run(args);
assertTrue(os.toString().contains("Let's run easter egg with -a"));
}
}
|
package fi.helsinki.cs.tmc.cli.command;
import static org.junit.Assert.assertTrue;
import fi.helsinki.cs.tmc.cli.Application;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class TestCommandTest {
Application app;
OutputStream os;
@Before
public void setUp() {
app = new Application();
os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);
}
@Test
public void runWorksRightWithoutOption() {
String[] args = {"EasterEgg"};
app.run(args);
assertTrue(os.toString().contains("Let's run easter egg."));
}
@Test
public void runWorksRightWithOption() {
String[] args = {"EasterEgg", "-a"};
app.run(args);
assertTrue(os.toString().contains("Let's run easter egg with -a"));
}
}
|
Add docstring to Button.time_held() method
|
import time
class Button(object):
"""Class representing keyboard keys."""
def __init__(self, game, number):
self.game = game
self.number = number
self.event = None # The last event that caused the button press
self.pressed = 0 # If the button was just pressed
self.held = 0 # If the button is held
self.released = 0 # If the button was just released
self.press_time = 0.0
def press(self):
self.pressed = 1
self.held = 1
self.press_time = time.time()
def release(self):
self.held = 0
self.released = 1
def reset(self):
self.pressed = 0
self.released = 0
def time_held(self) -> float:
"""Return the amount of time this button has been held for in seconds."""
if self.held:
return time.time() - self.press_time
else:
return 0.0
|
import time
class Button(object):
"""Class representing keyboard keys."""
def __init__(self, game, number):
self.game = game
self.number = number
self.event = None # The last event that caused the button press
self.pressed = 0 # If the button was just pressed
self.held = 0 # If the button is held
self.released = 0 # If the button was just released
self.press_time = 0.0
def press(self):
self.pressed = 1
self.held = 1
self.press_time = time.time()
def release(self):
self.held = 0
self.released = 1
def reset(self):
self.pressed = 0
self.released = 0
def time_held(self):
if self.held:
return time.time() - self.press_time
else:
return 0.0
|
Fix serve bug executing only the first operation
Fix a bug where only the first operation as part of a trigger was
executed when running in serve mode.
Signed-off-by: Arnaud Porterie (icecrime) <55258e89a8b41a46066b3a9514b15a78c1a88d17@docker.com>
|
package server
import (
"poule/configuration"
"poule/gh"
"poule/runner"
"github.com/Sirupsen/logrus"
)
func executeAction(config *configuration.Config, action configuration.Action, item gh.Item) error {
for _, opConfig := range action.Operations {
logrus.WithFields(logrus.Fields{
"operation": opConfig.Type,
"number": item.Number(),
"repository": item.Repository(),
}).Info("running operation")
opRunner, err := runner.NewOperationRunnerFromConfig(config, &opConfig)
if err != nil {
return err
}
if err := opRunner.Handle(item); err != nil {
return err
}
}
return nil
}
func executeActionOnAllItems(config *configuration.Config, action configuration.Action) error {
for _, opConfig := range action.Operations {
logrus.WithFields(logrus.Fields{
"operation": opConfig.Type,
}).Info("running operation on stock")
opRunner, err := runner.NewOperationRunnerFromConfig(config, &opConfig)
if err != nil {
return err
}
if err := opRunner.HandleStock(); err != nil {
return err
}
}
return nil
}
|
package server
import (
"poule/configuration"
"poule/gh"
"poule/runner"
"github.com/Sirupsen/logrus"
)
func executeAction(config *configuration.Config, action configuration.Action, item gh.Item) error {
for _, opConfig := range action.Operations {
logrus.WithFields(logrus.Fields{
"operation": opConfig.Type,
"number": item.Number(),
"repository": item.Repository(),
}).Info("running operation")
opRunner, err := runner.NewOperationRunnerFromConfig(config, &opConfig)
if err != nil {
return err
}
return opRunner.Handle(item)
}
return nil
}
func executeActionOnAllItems(config *configuration.Config, action configuration.Action) error {
for _, opConfig := range action.Operations {
logrus.WithFields(logrus.Fields{
"operation": opConfig.Type,
}).Info("running operation on stock")
opRunner, err := runner.NewOperationRunnerFromConfig(config, &opConfig)
if err != nil {
return err
}
return opRunner.HandleStock()
}
return nil
}
|
Insert custom commands through the getCommands() function.
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Newsfeeds
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Newsfeeds Toolbar Class
*
* @author Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
* @category Nooku
* @package Nooku_Server
* @subpackage Newsfeeds
*/
class ComNewsfeedsControllerToolbarNewsfeeds extends ComDefaultControllerToolbarDefault
{
public function getCommands()
{
$this->addSeperator()
->addEnable()
->addDisable();
return parent::getCommands();
}
}
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Newsfeeds
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Newsfeeds Toolbar Class
*
* @author Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
* @category Nooku
* @package Nooku_Server
* @subpackage Newsfeeds
*/
class ComNewsfeedsControllerToolbarNewsfeeds extends ComDefaultControllerToolbarDefault
{
public function __construct(KConfig $config)
{
parent::__construct($config);
$this->addSeperator()
->addEnable()
->addDisable();
}
}
|
Fix for RSF-42, binding to empty String
|
/*
* Created on 13-Jan-2006
*/
package uk.org.ponder.rsf.components;
import uk.org.ponder.beanutil.BeanUtil;
/** A special class to hold EL references so they may be detected in the
* component tree. When held in this member, it is devoid of the packaging #{..}
* characters - they are removed and replaced by the parser in transit from
* XML form.
* @author Antranig Basman (amb26@ponder.org.uk)
*
*/
// TODO: in RSF 0.8 this class will be deprecated in favour of the version
// in PUC.
public class ELReference {
public ELReference() {}
public ELReference(String value) {
String stripped = BeanUtil.stripEL(value);
this.value = stripped == null? value : stripped;
if ("".equals(value)) {
throw new IllegalArgumentException(
"Cannot issue an EL reference to an empty path. For an empty binding please either supply null, or else provide a non-empty String as path");
}
}
public String value;
public static ELReference make(String value) {
return value == null? null : new ELReference(value);
}
}
|
/*
* Created on 13-Jan-2006
*/
package uk.org.ponder.rsf.components;
import uk.org.ponder.beanutil.BeanUtil;
/** A special class to hold EL references so they may be detected in the
* component tree. When held in this member, it is devoid of the packaging #{..}
* characters - they are removed and replaced by the parser in transit from
* XML form.
* @author Antranig Basman (amb26@ponder.org.uk)
*
*/
// TODO: in RSF 0.8 this class will be deprecated in favour of the version
// in PUC.
public class ELReference {
public ELReference() {}
public ELReference(String value) {
String stripped = BeanUtil.stripEL(value);
this.value = stripped == null? value : stripped;
}
public String value;
public static ELReference make(String value) {
return value == null? null : new ELReference(value);
}
}
|
Switch tests to fake redis implementation
|
import django_rq
from fakeredis import FakeStrictRedis
from redis import Redis
from rq import Queue
connection = FakeStrictRedis()
class FakeRedisTestCaseMixin:
"""TestCase mixin that provides easy setup of FakeRedis connection to both
Django-RQ and RQ-Scheduler, as well as test-teardown with scheduled jobs
purging."""
def setUp(self):
super().setUp()
self.connection = connection
# self.connection = Redis()
self.queue = Queue(is_async=False, connection=self.connection)
self.scheduler = django_rq.get_scheduler('testing', queue=self.queue)
def tearDown(self):
# clear job queue
for job in self.scheduler.get_jobs():
self.scheduler.cancel(job)
assert not bool(list(self.scheduler.get_jobs()))
assert self.scheduler.count() == 0
super().tearDown()
|
import django_rq
from fakeredis import FakeStrictRedis
from redis import Redis
from rq import Queue
class FakeRedisTestCaseMixin:
"""TestCase mixin that provides easy setup of FakeRedis connection to both
Django-RQ and RQ-Scheduler, as well as test-teardown with scheduled jobs
purging."""
def setUp(self):
super().setUp()
# self.connection = FakeStrictRedis()
self.connection = Redis()
self.queue = Queue(is_async=False, connection=self.connection)
self.scheduler = django_rq.get_scheduler('testing', queue=self.queue)
def tearDown(self):
# clear job queue
for job in self.scheduler.get_jobs():
self.scheduler.cancel(job)
assert not bool(list(self.scheduler.get_jobs()))
assert self.scheduler.count() == 0
super().tearDown()
|
Hide color picker if there is only one available
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import map from 'lodash/map';
import classNames from 'classnames';
const ColorPicker = ({ colors, current, urlPrefix, onClick }) => {
return (
Object.keys(colors).length > 1
?
<div className="colorPicker">
{map(colors, color => {
const className = classNames('color', color.id, {
active: current === color.id
});
return (
<Link key={color.id}
to={`${urlPrefix}${color.id}`}
className={className} activeClassName="active"
onClick={() => onClick(color.id)}
>
</Link>
);
})}
</div>
:
<div/>
);
}
export default ColorPicker;
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import map from 'lodash/map';
import classNames from 'classnames';
const ColorPicker = ({ colors, current, urlPrefix, onClick }) => {
return (
<div className="colorPicker">
{map(colors, color => {
const className = classNames('color', color.id, {
active: current === color.id
});
return (
<Link key={color.id}
to={`${urlPrefix}${color.id}`}
className={className} activeClassName="active"
onClick={() => onClick(color.id)}
>
</Link>
);
})}
</div>
);
}
export default ColorPicker;
|
Set the type correctly (noticed by David Blacka).
|
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.*;
import org.xbill.DNS.utils.*;
/**
* Key - contains a cryptographic public key for use by DNS.
* The data can be converted to objects implementing
* java.security.interfaces.PublicKey
* @see DNSSEC
*
* @author Brian Wellington
*/
public class DNSKEYRecord extends KEYBase {
public static class Protocol {
private Protocol() {}
/** Key will be used for DNSSEC */
public static final int DNSSEC = 3;
}
public static class Flags {
private Flags() {}
/** Key is a zone key */
public static final int ZONE_KEY = 0x100;
/** Key is a secure entry point key */
public static final int SEP_KEY = 0x1;
}
DNSKEYRecord() {}
Record
getObject() {
return new DNSKEYRecord();
}
/**
* Creates a DNSKEY Record from the given data
* @param flags Flags describing the key's properties
* @param proto The protocol that the key was created for
* @param alg The key's algorithm
* @param key Binary data representing the key
*/
public
DNSKEYRecord(Name name, int dclass, long ttl, int flags, int proto, int alg,
byte [] key)
{
super(name, Type.DNSKEY, dclass, ttl, flags, proto, alg, key);
}
}
|
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.*;
import org.xbill.DNS.utils.*;
/**
* Key - contains a cryptographic public key for use by DNS.
* The data can be converted to objects implementing
* java.security.interfaces.PublicKey
* @see DNSSEC
*
* @author Brian Wellington
*/
public class DNSKEYRecord extends KEYBase {
public static class Protocol {
private Protocol() {}
/** Key will be used for DNSSEC */
public static final int DNSSEC = 3;
}
public static class Flags {
private Flags() {}
/** Key is a zone key */
public static final int ZONE_KEY = 0x100;
/** Key is a secure entry point key */
public static final int SEP_KEY = 0x1;
}
DNSKEYRecord() {}
Record
getObject() {
return new DNSKEYRecord();
}
/**
* Creates a KEY Record from the given data
* @param flags Flags describing the key's properties
* @param proto The protocol that the key was created for
* @param alg The key's algorithm
* @param key Binary data representing the key
*/
public
DNSKEYRecord(Name name, int dclass, long ttl, int flags, int proto, int alg,
byte [] key)
{
super(name, Type.KEY, dclass, ttl, flags, proto, alg, key);
}
}
|
Add field for pre-tokenized texts
|
from typing import Union, List
class InputExample:
"""
Structure for one input example with texts, the label and a unique id
"""
def __init__(self, guid: str = '', texts: List[str] = None, texts_tokenized: List[List[int]] = None, label: Union[int, float] = None):
"""
Creates one InputExample with the given texts, guid and label
str.strip() is called on both texts.
:param guid
id for the example
:param texts
the texts for the example
:param texts_tokenized
Optional: Texts that are already tokenized. If texts_tokenized is passed, texts must not be passed.
:param label
the label for the example
"""
self.guid = guid
self.texts = [text.strip() for text in texts] if texts is not None else texts
self.texts_tokenized = texts_tokenized
self.label = label
def __str__(self):
return "<InputExample> label: {}, texts: {}".format(str(self.label), "; ".join(self.texts))
|
from typing import Union, List
class InputExample:
"""
Structure for one input example with texts, the label and a unique id
"""
def __init__(self, guid: str = '', texts: Union[List[str], List[int]] = [], label: Union[int, float] = None):
"""
Creates one InputExample with the given texts, guid and label
str.strip() is called on both texts.
:param guid
id for the example
:param texts
the texts for the example
:param label
the label for the example
"""
self.guid = guid
self.texts = [text.strip() if isinstance(text, str) else text for text in texts]
self.label = label
def __str__(self):
return "<InputExample> label: {}, texts: {}".format(str(self.label), "; ".join(self.texts))
|
Fix modules path in test cases
|
;(function() {
var MODULES_PATH = 'https://a.alipayobjects.com/static/arale/'
//var MODULES_PATH = 'http://modules.seajs.org/'
if (location.href.indexOf('/~lifesinger/') > 0) {
MODULES_PATH = 'http://' + location.host + '/~lifesinger/seajs/spm/modules/'
}
// Ref: https://github.com/miohtama/detectmobile.js
var isMobile = Math.max(screen.availWidth || screen.availHeight) <= 480
function root(path) {
return MODULES_PATH + path
}
var hash = {
'$': root(isMobile ? 'zepto/0.8.0/zepto.js' : 'jquery/1.7.2/jquery.js'),
'coffee': root('coffee/1.3.3/coffee-script.js'),
'less': root('less/1.3.0/less.js')
}
seajs.config({
alias: hash
})
define({ isMobile: isMobile })
})()
|
;(function() {
var MODULES_PATH = 'https://a.alipayobjects.com/static/arale/'
//var MODULES_PATH = 'http://modules.seajs.org/'
if (location.href.indexOf('/~lifesinger/x') > 0) {
MODULES_PATH = 'http://' + location.host + '/~lifesinger/seajs/spm/modules/'
}
// Ref: https://github.com/miohtama/detectmobile.js
var isMobile = Math.max(screen.availWidth || screen.availHeight) <= 480
function root(path) {
return MODULES_PATH + path
}
var hash = {
'$': root(isMobile ? 'zepto/0.8.0/zepto.js' : 'jquery/1.7.2/jquery.js'),
'coffee': root('coffee/1.3.3/coffee-script.js'),
'less': root('less/1.3.0/less.js')
}
seajs.config({
alias: hash
})
define({ isMobile: isMobile })
})()
|
Use integer for cache key
|
import LRU from 'lru-cache'
import path from 'path'
import fs from 'fs-plus'
import _ from 'underscore'
export default class ReadCache {
constructor (folder, cacheSize) {
this.path = path.join(folder, 'Storage', 'db.json')
this.cache = LRU({
max: cacheSize
})
}
load () {
var result = {}
try {
result = JSON.parse(fs.readFileSync(this.path, 'utf8'))
} catch (e) {
console.log(e)
}
if (result['read']) {
_.each(result['read'].reverse(), function (val) {
this.set(val)
}, this)
}
}
store () {
var result = []
this.cache.forEach(function (value, key) {
result.push(key)
})
fs.writeFileSync(this.path, JSON.stringify({ read: result }), 'utf8')
}
set (val) {
return this.cache.set(val, val)
}
contains (val) {
return this.cache.has(val)
}
}
|
import LRU from 'lru-cache'
import path from 'path'
import fs from 'fs-plus'
import _ from 'underscore'
export default class ReadCache {
constructor (folder, cacheSize) {
this.path = path.join(folder, 'Storage', 'db.json')
this.cache = LRU({
max: cacheSize,
length: function (n) {
return n.length
}
})
}
load () {
var result = {}
try {
result = JSON.parse(fs.readFileSync(this.path, 'utf8'))
} catch (e) {
console.log(e)
}
if (result['read']) {
_.each(result['read'].reverse(), function (val) {
this.set(val)
}, this)
}
}
store () {
var result = []
this.cache.forEach(function (value, key) {
result.push(key)
})
fs.writeFileSync(this.path, JSON.stringify({ read: result }), 'utf8')
}
set (val) {
val = val.toString()
return this.cache.set(val, val)
}
contains (val) {
val = val.toString()
return this.cache.has(val)
}
}
|
Use proper Jersey aborts instead of Shiro Exceptions
The Shiro exceptions will not return the proper HTTP statuscode, but will instead return a 500 Internal Server Error.
* Replace UnauthorizedException and ForbiddenException with Jersey aborts.
|
package dk.kroeger.dennis.shiro.jersey.filters;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import java.io.IOException;
/**
* Common base class for all request filters.
*
* @author Dennis Du Krøger
* @since 02-08-2014
*/
abstract class ShiroContainerRequestFilter implements ContainerRequestFilter {
/**
* @return True if current filter is satisfied.
*/
protected abstract boolean checkAccess(Subject subject);
/**
* In most cases, a filter requires the user to be remembered or authenticated,
* but some filters may skip that.
*
* @return True if filter consider user allowed
*/
boolean checkAuthentication(Subject subject) {
return subject.isRemembered() || subject.isAuthenticated();
}
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
Subject subject = SecurityUtils.getSubject();
if (!checkAuthentication(subject)) {
containerRequestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(
"Unauthorized").build());
} else if (!checkAccess(subject)) {
containerRequestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(
"Forbidden").build());
}
}
}
|
package dk.kroeger.dennis.shiro.jersey.filters;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import java.io.IOException;
/**
* Common base class for all request filters.
*
* @author Dennis Du Krøger
* @since 02-08-2014
*/
abstract class ShiroContainerRequestFilter implements ContainerRequestFilter {
/**
* @return True if current filter is satisfied.
*/
protected abstract boolean checkAccess(Subject subject);
/**
* In most cases, a filter requires the user to be remembered or authenticated,
* but some filters may skip that.
*
* @return True if filter consider user allowed
*/
boolean checkAuthentication(Subject subject) {
return subject.isRemembered() || subject.isAuthenticated();
}
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
Subject subject = SecurityUtils.getSubject();
if (!checkAuthentication(subject)) {
throw new UnauthorizedException();
} else if (!checkAccess(subject)) {
throw new ForbiddenException();
}
}
}
|
Fix can merge check for column merge
|
var _ = require('underscore');
var cdb = require('cartodb.js');
var ChooseKeyColumnsModel = require('./choose_key_columns_model');
module.exports = cdb.core.Model.extend({
defaults: {
illustrationIconType: 'IllustrationIcon--alert',
icon: 'iconFont-Question',
title: 'Column join',
desc: 'Merge two datasets based on a shared value (ex. ISO codes in both datasets)',
table: undefined,
excludeColumns: []
},
initialize: function(attrs) {
if (!attrs.table) throw new Error('table is required');
if (!attrs.excludeColumns || _.isEmpty(attrs.excludeColumns)) cdb.log.error('excludeColumns was empty');
this.elder('initialize');
},
isAvailable: function() {
// Need at least one more column than the_geom to do a column merge
return _.chain(this.get('table').get('schema'))
.map(function(column) {
return column[0]; //name
})
.without(this.get('excludeColumns'))
.any(function(columnName) {
return columnName !== 'the_geom';
})
.value();
},
firstStep: function() {
return new ChooseKeyColumnsModel({
leftTable: this.get('table'),
excludeColumns: this.get('excludeColumns')
});
}
});
|
var _ = require('underscore');
var cdb = require('cartodb.js');
var ChooseKeyColumnsModel = require('./choose_key_columns_model');
module.exports = cdb.core.Model.extend({
defaults: {
illustrationIconType: 'IllustrationIcon--alert',
icon: 'iconFont-Question',
title: 'Column join',
desc: 'Merge two datasets based on a shared value (ex. ISO codes in both datasets)',
table: undefined,
excludeColumns: []
},
initialize: function(attrs) {
if (!attrs.table) throw new Error('table is required');
if (!attrs.excludeColumns || _.isEmpty(attrs.excludeColumns)) cdb.log.error('excludeColumns was empty');
this.elder('initialize');
},
isAvailable: function() {
// Need at least one more column than the_geom to do a column merge
return _.chain(this.get('table').get('schema'))
.map(function(column) {
return column[0]; //name
})
.without(this.get('filteredColumns'))
.any(function(columnName) {
return columnName !== 'the_geom';
})
.value();
},
firstStep: function() {
return new ChooseKeyColumnsModel({
leftTable: this.get('table'),
excludeColumns: this.get('excludeColumns')
});
}
});
|
Fix for adding tags that are substrings of existing tags
https://github.com/select2/select2/issues/4093
|
@section("field")
<div class="select2-tags">
<select name="{{ $prefixed_field_name }}[]" class="form-control" id="{{ $field_id }}" multiple>
@foreach((array) $field_value as $value)
<option value="{{ $value }}" selected>{{ $value }}</option>
@endforeach
</select>
</div>
@overwrite
@section('footer.js')
@parent
<script>
$(function(){
$('#{{ $field_id }}').select2({
tags: true,
multiple: true,
//dropdownCssClass: 'hide',
{!! app('soda.form')->buildJsParams($field_parameters['settings']) !!}
});
});
</script>
@stop
|
@section("field")
<div class="select2-tags">
<select name="{{ $prefixed_field_name }}[]" class="form-control" id="{{ $field_id }}" multiple>
@foreach((array) $field_value as $value)
<option value="{{ $value }}" selected>{{ $value }}</option>
@endforeach
</select>
</div>
@overwrite
@section('footer.js')
@parent
<script>
$(function(){
$('#{{ $field_id }}').select2({
tags: true,
multiple: true,
dropdownCssClass: 'hide',
{!! app('soda.form')->buildJsParams($field_parameters['settings']) !!}
});
});
</script>
@stop
|
Remove unused link to cookie.js
remove SVN external
git-svn-id: d66344a971a0a943c9b1d460f97ab888aaee4784@27866 ee427ae8-e902-0410-961c-c3ed070cd9f9
|
<?php
function get_nested_set_manager($model, $field, $root = 0){
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/jsTree/themes/default/style.css');
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/css/screen.css');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/jquery.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/jquery.cookie.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/jquery.tree.min.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/plugins/jquery.tree.cookie.js');
return get_component('sfJqueryTreeDoctrineManager', 'manager', array('model' => $model, 'field' => $field, 'root' => $root));
}
|
<?php
function get_nested_set_manager($model, $field, $root = 0){
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/jsTree/themes/default/style.css');
sfContext::getInstance()->getResponse()->addStylesheet('/sfJqueryTreeDoctrineManagerPlugin/css/screen.css');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/lib/jquery.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/jquery.tree.min.js');
sfContext::getInstance()->getResponse()->addJavascript('/sfJqueryTreeDoctrineManagerPlugin/jsTree/plugins/jquery.tree.cookie.js');
return get_component('sfJqueryTreeDoctrineManager', 'manager', array('model' => $model, 'field' => $field, 'root' => $root));
}
|
Add fader to the pagerAdapter
|
package dk.cmol.arduinorgb_controller;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MenuPagerAdapter extends FragmentPagerAdapter {
public MenuPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment;
switch (position) {
case 0:
fragment = new ColorDotsFragment();
break;
case 1:
fragment = new SliderFragment();
break;
case 2:
fragment = new FaderFragment();
break;
default:
fragment = new ColorDotsFragment();
break;
}
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Dots";
case 1:
return "Slider";
case 2:
return "Fader";
}
return null;
}
}
|
package dk.cmol.arduinorgb_controller;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MenuPagerAdapter extends FragmentPagerAdapter {
public MenuPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment;
switch (position) {
case 0:
fragment = new ColorDotsFragment();
break;
case 1:
fragment = new SliderFragment();
break;
default:
fragment = new ColorDotsFragment();
break;
}
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Dots";
case 1:
return "Slider";
}
return null;
}
}
|
Fix bug in server image
|
var fs = require("fs");
var queryString = require("querystring");
function start(response, postData) {
console.log("Request handler 'start' was called.");
fs.readFile("./public/index.html", "utf8", function(error, data) {
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write(data);
response.end();
});
}
function upload(response, postData) {
console.log("Request handler 'upload' was called.");
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.write("You have sent: " + queryString.parse(postData).text);
response.end();
}
function show(response) {
console.log("Request handler 'show' was called.");
response.writeHead(200, {
"Content-Type": "image/png"
});
fs.createReadStream("./tmp/test.png").pipe(response);
}
exports.start = start;
exports.upload = upload;
exports.show = show;
|
var fs = require("fs");
var queryString = require("querystring");
function start(response, postData) {
console.log("Request handler 'start' was called.");
fs.readFile("./public/index.html", "utf8", function(error, data) {
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write(data);
response.end();
});
}
function upload(response, postData) {
console.log("Request handler 'upload' was called.");
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.write("You have sent: " + queryString.parse(postData).text);
response.end();
}
function show(response) {
console.log("Request handler 'show' was called.");
response.writeHead(200, {
"Content-Type": "image/png"
});
fs.createReadStream("/tmp/text.png").pipe(response);
}
exports.start = start;
exports.upload = upload;
exports.show = show;
|
Fix ubuntu version in test prog
|
import azurerm
import json
# Load Azure app defaults
try:
with open('azurermconfig.json') as configFile:
configData = json.load(configFile)
except FileNotFoundError:
print("Error: Expecting vmssConfig.json in current folder")
sys.exit()
tenant_id = configData['tenantId']
app_id = configData['appId']
app_secret = configData['appSecret']
subscription_id = configData['subscriptionId']
access_token = azurerm.get_access_token(tenant_id, app_id, app_secret)
'''
pubs = azurerm.list_publishers(access_token, subscription_id, 'southeastasia')
for pub in pubs:
print(pub['name'])
offers = azurerm.list_offers(access_token, subscription_id, 'southeastasia', 'MicrosoftWindowsServer')
for offer in offers:
print(offer['name'])
skus = azurerm.list_skus(access_token, subscription_id, 'southeastasia', 'MicrosoftWindowsServer', 'WindowsServer')
for sku in skus:
print(sku['name'])
'''
#versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastus', 'MicrosoftWindowsServer', 'WindowsServer', '2012-R2-Datacenter')
versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastus', 'Canonical', 'UbuntuServer', '15.10')
for version in versions:
print(version['name'])
|
import azurerm
import json
# Load Azure app defaults
try:
with open('azurermconfig.json') as configFile:
configData = json.load(configFile)
except FileNotFoundError:
print("Error: Expecting vmssConfig.json in current folder")
sys.exit()
tenant_id = configData['tenantId']
app_id = configData['appId']
app_secret = configData['appSecret']
subscription_id = configData['subscriptionId']
access_token = azurerm.get_access_token(tenant_id, app_id, app_secret)
'''
pubs = azurerm.list_publishers(access_token, subscription_id, 'southeastasia')
for pub in pubs:
print(pub['name'])
offers = azurerm.list_offers(access_token, subscription_id, 'southeastasia', 'MicrosoftWindowsServer')
for offer in offers:
print(offer['name'])
skus = azurerm.list_skus(access_token, subscription_id, 'southeastasia', 'MicrosoftWindowsServer', 'WindowsServer')
for sku in skus:
print(sku['name'])
'''
#versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastus', 'MicrosoftWindowsServer', 'WindowsServer', '2012-R2-Datacenter')
versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastus', 'Canonical', 'UbuntuServer', '15.04')
for version in versions:
print(version['name'])
|
Fix model path for serialization in init command
|
<?php
/**
* This file is part of the cast package.
*
* Copyright (c) 2013 Jason Coward <jason@opengeek.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cast\Commands;
use Cast\Cast;
class CastInit extends CastCommand
{
protected $command = 'init';
public function run(array $args = array())
{
$directory = isset($args[0]) && !empty($args[0]) ? $args[0] : $this->cast->git->getPath();
if ($this->cast->git->isInitialized()) throw new \RuntimeException('Cannot reinitialize an existing git repository at ' . $directory);
if ($this->cast->git->getOption('core.bare', null, false)) {
throw new \RuntimeException('Cast does not currently support bare repositories');
}
$this->cast->serializeModel(null, rtrim($directory, '/') . '/' . $this->cast->getOption(Cast::SERIALIZED_MODEL_PATH, null, '.model/'));
return $this->cast->git->init->run($args);
}
}
|
<?php
/**
* This file is part of the cast package.
*
* Copyright (c) 2013 Jason Coward <jason@opengeek.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cast\Commands;
class CastInit extends CastCommand
{
protected $command = 'init';
public function run(array $args = array())
{
$directory = isset($args[0]) ? $args[0] : $this->cast->git->getPath();
if ($this->cast->git->isInitialized()) throw new \RuntimeException('Cannot reinitialize an existing git repository at ' . $this->cast->git->getPath());
if ($this->cast->git->getOption('core.bare', null, false)) {
throw new \RuntimeException('Cast does not currently support bare repositories');
}
$this->cast->serializeModel(null, rtrim($directory, '/') . '/');
return $this->cast->git->init->run($args);
}
}
|
Modify return variable and partenesis
|
# -*- coding:utf8 -*-
from plantmeter.isodates import isodate
from dateutil.relativedelta import relativedelta
waitYears = 1
expirationYears = 25
def previousAmortizationDate(purchase_date, current_date):
years = relativedelta(
isodate(current_date),
isodate(purchase_date),
).years
if years <= waitYears:
return None
firstAmortization = (
isodate(purchase_date)
+ relativedelta(years = min(years,expirationYears)
))
return str(firstAmortization)
def pendingAmortization(purchase_date, current_date, investment_amount, amortized_amount):
years = relativedelta(
isodate(current_date),
isodate(purchase_date),
).years
yearly_amortitzation = investment_amount / expirationYears
if years <= waitYears:
return 0
if years >= expirationYears:
return investment_amount - amortized_amount
toAmortize = (years-1)*yearly_amortitzation - amortized_amount
return max(0, toAmortize)
# vim: et ts=4 sw=4
|
# -*- coding:utf8 -*-
from plantmeter.isodates import isodate
from dateutil.relativedelta import relativedelta
waitYears = 1
expirationYears = 25
def previousAmortizationDate(purchase_date, current_date):
years = relativedelta(
isodate(current_date),
isodate(purchase_date),
).years
if years <= waitYears:
return None
firstAmortization = (
isodate(purchase_date)
+ relativedelta(years = min(years,expirationYears)
)
return str(amortizationDate)
def pendingAmortization(purchase_date, current_date, investment_amount, amortized_amount):
years = relativedelta(
isodate(current_date),
isodate(purchase_date),
).years
yearly_amortitzation = investment_amount / expirationYears
if years <= waitYears:
return 0
if years >= expirationYears:
return investment_amount - amortized_amount
toAmortize = (years-1)*yearly_amortitzation - amortized_amount
return max(0, toAmortize)
# vim: et ts=4 sw=4
|
Move remove code down to fix undefined var error
|
from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_popup_distance(self, distance):
self._popup_distance = distance
def create_menu(self):
menu = BuddyMenu(self._shell, self._friend)
menu.connect('action', self._popup_action_cb)
return menu
def _popup_action_cb(self, popup, action):
self.popdown()
buddy = self._friend.get_buddy()
if buddy == None:
return
model = self._shell.get_model()
if action == BuddyMenu.ACTION_INVITE:
activity = model.get_current_activity()
activity.invite(buddy)
elif action == BuddyMenu.ACTION_MAKE_FRIEND:
friends = model.get_friends()
friends.make_friend(buddy)
elif action == BuddyMenu.ACTION_REMOVE_FRIEND:
friends = model.get_friends()
friends.remove(buddy)
|
from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_popup_distance(self, distance):
self._popup_distance = distance
def create_menu(self):
menu = BuddyMenu(self._shell, self._friend)
menu.connect('action', self._popup_action_cb)
return menu
def _popup_action_cb(self, popup, action):
self.popdown()
model = self._shell.get_model()
if action == BuddyMenu.ACTION_REMOVE_FRIEND:
friends = model.get_friends()
friends.remove(buddy)
buddy = self._friend.get_buddy()
if buddy == None:
return
if action == BuddyMenu.ACTION_INVITE:
activity = model.get_current_activity()
activity.invite(buddy)
elif action == BuddyMenu.ACTION_MAKE_FRIEND:
friends = model.get_friends()
friends.make_friend(buddy)
|
Revert early removal of certificate field
|
"""
Models for the records app.
"""
import uuid
from django.db import models
from django_extensions.db.models import TimeStampedModel
from credentials.apps.catalog.models import CourseRun, Program
from credentials.apps.core.models import User
from credentials.apps.credentials.models import ProgramCertificate
class UserGrade(TimeStampedModel):
"""
A grade for a specific user and course run
"""
username = models.CharField(max_length=150, blank=False)
course_run = models.ForeignKey(CourseRun)
letter_grade = models.CharField(max_length=255, blank=True)
percent_grade = models.DecimalField(max_digits=5, decimal_places=4, null=False)
verified = models.BooleanField(verbose_name='Verified Learner ID', default=True)
class Meta(object):
unique_together = ('username', 'course_run')
class ProgramCertRecord(TimeStampedModel):
"""
Connects a User with a Program
"""
certificate = models.ForeignKey(ProgramCertificate, null=True)
program = models.ForeignKey(Program, null=True)
user = models.ForeignKey(User)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
def __str__(self):
return 'ProgramCertificateRecord: {uuid}'.format(uuid=self.uuid)
class Meta(object):
verbose_name = "A viewable record of a program"
|
"""
Models for the records app.
"""
import uuid
from django.db import models
from django_extensions.db.models import TimeStampedModel
from credentials.apps.catalog.models import CourseRun, Program
from credentials.apps.core.models import User
class UserGrade(TimeStampedModel):
"""
A grade for a specific user and course run
"""
username = models.CharField(max_length=150, blank=False)
course_run = models.ForeignKey(CourseRun)
letter_grade = models.CharField(max_length=255, blank=True)
percent_grade = models.DecimalField(max_digits=5, decimal_places=4, null=False)
verified = models.BooleanField(verbose_name='Verified Learner ID', default=True)
class Meta(object):
unique_together = ('username', 'course_run')
class ProgramCertRecord(TimeStampedModel):
"""
Connects a User with a Program
"""
program = models.ForeignKey(Program, null=True)
user = models.ForeignKey(User)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
def __str__(self):
return 'ProgramCertificateRecord: {uuid}'.format(uuid=self.uuid)
class Meta(object):
verbose_name = "A viewable record of a program"
|
Set up a imgdata route to fetch latest image.
|
"""Set up a bottle server to accept post requests commanding the drone."""
from bottle import post, run, hook, response, get, abort
from venthur_api import libardrone
drone = libardrone.ARDrone()
@hook('after_request')
def enable_cors():
"""Allow control headers."""
response.headers['Access-Control-Allow-Origin'] = '*'
@get('/imgdata')
def imgdata():
"""Return the current drone image."""
print(type(drone.image))
return drone.image
@get('/navdata')
def navdata():
"""Return packet of navdata."""
response.content_type = 'image/x-rgb'
print(drone.navdata)
return drone.navdata
@post('/do/<command>')
def do(command):
"""Execute the given command from the route."""
try:
print('Command received: {}'.format(command))
getattr(drone, command)()
print('Command executed: {}'.format(command))
return 'Command executed: {}'.format(command)
except AttributeError:
print('Bad Command: {}'.format(command))
abort(404, 'Bad Command: {}'.format(command))
try:
run(host='127.0.0.1', port=8080)
finally:
drone.land()
drone.halt()
|
"""Set up a bottle server to accept post requests commanding the drone."""
from bottle import post, run, hook, response, get, abort
from venthur_api import libardrone
drone = libardrone.ARDrone()
@hook('after_request')
def enable_cors():
"""Allow control headers."""
response.headers['Access-Control-Allow-Origin'] = '*'
@get('/navdata')
def navdata():
"""Return packet of navdata."""
print(type(drone.image))
return drone.image
@get('/imgdata')
def navdata():
"""Return packet of navdata."""
print(drone.navdata)
return drone.navdata
@post('/do/<command>')
def do(command):
"""Execute the given command from the route."""
try:
print('Command received: {}'.format(command))
getattr(drone, command)()
print('Command executed: {}'.format(command))
return 'Command executed: {}'.format(command)
except AttributeError:
print('Bad Command: {}'.format(command))
abort(404, 'Bad Command: {}'.format(command))
try:
run(host='127.0.0.1', port=8080)
finally:
drone.land()
drone.halt()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.