text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update dependency configuration as App now composes the container | <?php
// DIC configuration
$container = $app->getContainer();
// -----------------------------------------------------------------------------
// Service providers
// -----------------------------------------------------------------------------
// Twig
$view = new \Slim\Views\Twig(
$app->settings['view']['template_path'],
$app->settings['view']['twig']
);
$twig = $view->getEnvironment();
$twig->addExtension(new Twig_Extension_Debug());
$container->register($view);
// Flash messages
$container->register(new \Slim\Flash\Messages);
// -----------------------------------------------------------------------------
// Service factories
// -----------------------------------------------------------------------------
// monolog
$container['logger'] = function ($c) {
$settings = $c['settings']['logger'];
$logger = new \Monolog\Logger($settings['name']);
$logger->pushProcessor(new \Monolog\Processor\UidProcessor());
$logger->pushHandler(new \Monolog\Handler\StreamHandler($settings['path'], \Monolog\Logger::DEBUG));
return $logger;
};
// -----------------------------------------------------------------------------
// Action factories
// -----------------------------------------------------------------------------
$container['App\Action\HomeAction'] = function ($c) {
return new App\Action\HomeAction($c['view'], $c['logger']);
};
| <?php
// DIC configuration
// -----------------------------------------------------------------------------
// Service providers
// -----------------------------------------------------------------------------
// Twig
$view = new \Slim\Views\Twig(
$app['settings']['view']['template_path'],
$app['settings']['view']['twig']
);
$twig = $view->getEnvironment();
$twig->addExtension(new Twig_Extension_Debug());
$app->register($view);
// Flash messages
$app->register(new \Slim\Flash\Messages);
// -----------------------------------------------------------------------------
// Service factories
// -----------------------------------------------------------------------------
// monolog
$app['logger'] = function ($c) {
$settings = $c['settings']['logger'];
$logger = new \Monolog\Logger($settings['name']);
$logger->pushProcessor(new \Monolog\Processor\UidProcessor());
$logger->pushHandler(new \Monolog\Handler\StreamHandler($settings['path'], \Monolog\Logger::DEBUG));
return $logger;
};
// -----------------------------------------------------------------------------
// Action factories
// -----------------------------------------------------------------------------
$app['App\Action\HomeAction'] = function ($c) {
return new App\Action\HomeAction($c['view'], $c['logger']);
};
|
Allow sub- and superscript tags | from markdown.extensions import nl2br, sane_lists, fenced_code
from pymdownx import magiclink
from mdx_unimoji import UnimojiExtension
import utils.markdown
markdown_extensions = [
magiclink.MagiclinkExtension(),
nl2br.Nl2BrExtension(),
utils.markdown.ExtendedLinkExtension(),
sane_lists.SaneListExtension(),
fenced_code.FencedCodeExtension(),
utils.markdown.CuddledListExtension(),
UnimojiExtension()
]
content_allowed_tags = (
# text
'p', 'em', 'strong', 'br', 'a', 'img', 'sub', 'sup',
# citation
'blockquote', 'cite',
# headings
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
# lists
'ol', 'ul', 'li',
# code
'pre', 'code'
)
content_allowed_attributes = {
'*': ['id', 'title'],
'a': ['href', 'title', 'data-component', 'data-grouplink-ref'],
'code': ['class'],
'img': ['src', 'alt']
}
| from markdown.extensions import nl2br, sane_lists, fenced_code
from pymdownx import magiclink
from mdx_unimoji import UnimojiExtension
import utils.markdown
markdown_extensions = [
magiclink.MagiclinkExtension(),
nl2br.Nl2BrExtension(),
utils.markdown.ExtendedLinkExtension(),
sane_lists.SaneListExtension(),
fenced_code.FencedCodeExtension(),
utils.markdown.CuddledListExtension(),
UnimojiExtension()
]
content_allowed_tags = (
# text
'p', 'em', 'strong', 'br', 'a', 'img',
# citation
'blockquote', 'cite',
# headings
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
# lists
'ol', 'ul', 'li',
# code
'pre', 'code'
)
content_allowed_attributes = {
'*': ['id', 'title'],
'a': ['href', 'title', 'data-component', 'data-grouplink-ref'],
'code': ['class'],
'img': ['src', 'alt']
}
|
Use File.createTempFile() instead of hardcoded path. | package com.darwinsys.todo.test;
import static org.junit.Assert.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Before;
import org.junit.Test;
import com.darwinsys.todo.model.Date;
public class DateSerializeTest {
static final File TEMPFILE;
static {
try {
TEMPFILE = File.createTempFile("abc", "def");
TEMPFILE.delete();
} catch(IOException e) {
throw new ExceptionInInitializerError("Canna create temp file");
}
}
final Date origDate = new Date(2014, 05, 06);
@Before
public void setUp() throws Exception {
}
@Test
public void test() throws Exception {
ObjectOutputStream os = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(TEMPFILE)));
os.writeObject(origDate);
os.close();
ObjectInputStream is = new ObjectInputStream(
new FileInputStream(TEMPFILE));
Date d2 = (Date) is.readObject();
is.close();
System.out.println(d2);
assertEquals(origDate.getYear(), d2.getYear());
}
}
| package com.darwinsys.todo.test;
import static org.junit.Assert.*;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Before;
import org.junit.Test;
import com.darwinsys.todo.model.Date;
public class DateSerializeTest {
static final String FILENAME = "/tmp/sss"; // XXX use file.makeTempFile()
final Date origDate = new Date(2014, 05, 06);
@Before
public void setUp() throws Exception {
}
@Test
public void test() throws Exception {
ObjectOutputStream os = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(FILENAME)));
os.writeObject(origDate);
os.close();
ObjectInputStream is = new ObjectInputStream(
new FileInputStream(FILENAME));
Date d2 = (Date) is.readObject();
is.close();
System.out.println(d2);
assertEquals(origDate.getYear(), d2.getYear());
}
}
|
Make changes to default to Python3
Since we have undoubtedly moved to Python3 for the most part within the community, this should be Python3 by default. We make Python2 users work harder now. | #!/usr/bin/env python3
# Password Hashing Module for Linux
# Author: Dave Russell Jr (drussell393)
from getpass import getpass
import crypt
# If you like Python 2, please to be importing.
#import os
#import binascii
password = getpass('Enter your desired password, Harry: ')
passwordConfirm = getpass('Confirm your password: ')
if (password == passwordConfirm):
# Python 2 alternative, os.urandom()
#passwordHash = crypt.crypt(password, '$6$' + binascii.hexlify(os.urandom(4)))
# Python 3 likes my crypt (mksalt doesn't work in Python 2)
passwordHash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
print('You\'re a wizard, Harry: ' + passwordHash)
else:
print('Dobby has heard of your greatness, sir. But of your goodness, Dobby never knew.')
print('Your confirmation password didn\'t match, Oh Great One.')
| #!/usr/bin/env python
# Password Hashing Module for Linux
# Author: Dave Russell Jr (drussell393)
from getpass import getpass
import crypt
# If you like Python 2, please to be importing.
import os
import binascii
password = getpass('Enter your desired password, Harry: ')
passwordConfirm = getpass('Confirm your password: ')
if (password == passwordConfirm):
# Python 2 alternative, os.urandom()
passwordHash = crypt.crypt(password, '$6$' + binascii.hexlify(os.urandom(4)))
# Python 3 likes my crypt (mksalt doesn't work in Python 2)
#passwordHash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
print('You\'re a wizard, Harry: ' + passwordHash)
else:
print('Dobby has heard of your greatness, sir. But of your goodness, Dobby never knew.')
print('Your confirmation password didn\'t match, Oh Great One.')
|
Fix logo path and markup | <!doctype html>
<html>
<head>
<link rel="stylesheet" href="<?php echo $my_url; ?>/static/pure-min.css">
<link rel="stylesheet" href="<?php echo $my_url; ?>/static/grids-responsive-min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $title; ?></title>
</head>
<body>
<div class="pure-g">
<div class="pure-u-1">
<h1><?php echo $title; ?></h1>
<!-- .pure-img makes images responsive -->
<img class="pure-img" src="<?php echo $my_url; ?>static/logo.png"/>
</div>
| <!doctype html>
<html>
<head>
<link rel="stylesheet" href="<?php echo $my_url; ?>/static/pure-min.css">
<link rel="stylesheet" href="<?php echo $my_url; ?>/static/grids-responsive-min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $title; ?></title>
</head>
<body>
<div class="pure-g">
<div class="pure-u-1">
<h1><?php echo $title; ?></h1>
<!-- .pure-img makes images responsive -->
<img class="pure-img" scc="<?php echo $my_url; ?>/logo.png"/>
</div>
|
Revert "FIX: Download of files named "true" or "false" impossible"
This reverts commit d2d71c8797f7e7b51e55bec4217738faaf6a08ca.
which was accidentally commited | <?php
/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
// only need filesystem apps
$RUNTIME_APPTYPES=array('filesystem');
// Init owncloud
// Check if we are a user
OCP\User::checkLoggedIn();
$files = $_GET["files"];
$dir = $_GET["dir"];
$files_list = json_decode($files);
// in case we get only a single file
if ($files_list === NULL ) {
$files_list = array($files);
}
OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);
| <?php
/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
// only need filesystem apps
$RUNTIME_APPTYPES=array('filesystem');
// Init owncloud
// Check if we are a user
OCP\User::checkLoggedIn();
$files = $_GET["files"];
$dir = $_GET["dir"];
$files_list = json_decode($files);
// in case we get only a single file
if ($files_list === NULL || $files_list === true || $files_list === false) {
$files_list = array($files);
}
OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);
|
Update archetype to use Game.Default. | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.core;
import static playn.core.PlayN.*;
import playn.core.Game;
import playn.core.Image;
import playn.core.ImageLayer;
public class ${JavaGameClassName} extends Game.Default {
public ${JavaGameClassName}() {
super(33); // call update every 33ms (30 times per second)
}
@Override
public void init() {
// create and add background image layer
Image bgImage = assets().getImage("images/bg.png");
ImageLayer bgLayer = graphics().createImageLayer(bgImage);
graphics().rootLayer().add(bgLayer);
}
@Override
public void update(int delta) {
}
@Override
public void paint(float alpha) {
// the background automatically paints itself, so no need to do anything here!
}
}
| #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.core;
import static playn.core.PlayN.*;
import playn.core.Game;
import playn.core.Image;
import playn.core.ImageLayer;
public class ${JavaGameClassName} implements Game {
@Override
public void init() {
// create and add background image layer
Image bgImage = assets().getImage("images/bg.png");
ImageLayer bgLayer = graphics().createImageLayer(bgImage);
graphics().rootLayer().add(bgLayer);
}
@Override
public void paint(float alpha) {
// the background automatically paints itself, so no need to do anything here!
}
@Override
public void update(float delta) {
}
@Override
public int updateRate() {
return 25;
}
}
|
Test setting our own alias via PEP
Astonishingly, this was untested... |
"""
Test alias setting support.
"""
from servicetest import EventPattern, assertEquals
from gabbletest import exec_test, acknowledge_iq
import constants as cs
import ns
def validate_pep_update(pep_update, expected_nickname):
publish = pep_update.query.elements(uri=ns.PUBSUB, name='publish').next()
assertEquals(ns.NICK, publish['node'])
item = publish.elements(uri=ns.PUBSUB, name='item').next()
nick = item.elements(uri=ns.NICK, name='nick').next()
assertEquals(expected_nickname, nick.children[0])
def test(q, bus, conn, stream):
iq_event = q.expect('stream-iq', to=None, query_ns='vcard-temp',
query_name='vCard')
acknowledge_iq(stream, iq_event.stanza)
conn.Aliasing.SetAliases({1: 'lala'})
pep_update = q.expect('stream-iq', iq_type='set', query_ns=ns.PUBSUB, query_name='pubsub')
validate_pep_update(pep_update, 'lala')
acknowledge_iq(stream, pep_update.stanza)
iq_event = q.expect('stream-iq', iq_type='set', query_ns='vcard-temp',
query_name='vCard')
acknowledge_iq(stream, iq_event.stanza)
event = q.expect('dbus-signal', signal='AliasesChanged',
args=[[(1, u'lala')]])
if __name__ == '__main__':
exec_test(test)
|
"""
Test alias setting support.
"""
from servicetest import EventPattern
from gabbletest import exec_test, acknowledge_iq
import constants as cs
def test(q, bus, conn, stream):
iq_event = q.expect('stream-iq', to=None, query_ns='vcard-temp',
query_name='vCard')
acknowledge_iq(stream, iq_event.stanza)
conn.Aliasing.SetAliases({1: 'lala'})
iq_event = q.expect('stream-iq', iq_type='set', query_ns='vcard-temp',
query_name='vCard')
acknowledge_iq(stream, iq_event.stanza)
event = q.expect('dbus-signal', signal='AliasesChanged',
args=[[(1, u'lala')]])
if __name__ == '__main__':
exec_test(test)
|
Write tests for User model | const dotenv = require('dotenv');
dotenv.config();
module.exports = {
development: {
username: 'Newman',
password: 'andela2017',
database: 'postit-db-dev',
host: '127.0.0.1',
port: 5432,
secret_key: process.env.SECRET_KEY,
dialect: 'postgres'
},
test: {
username: 'Newman',
password: 'andela2017',
database: 'postit-db-test',
// username: 'postgres',
// password: '',
// database: 'postit_db_test',
host: '127.0.0.1',
port: 5432,
secret_key: process.env.SECRET_KEY,
dialect: 'postgres'
},
production: {
use_env_variable: 'PROD_DB_URL',
username: '?',
password: '?',
database: '?',
host: '?',
dialect: '?'
}
};
| const dotenv = require('dotenv');
dotenv.config();
module.exports = {
development: {
username: 'Newman',
password: 'andela2017',
database: 'postit-db-dev',
host: '127.0.0.1',
port: 5432,
secret_key: process.env.SECRET_KEY,
dialect: 'postgres'
},
test: {
// username: 'Newman',
// password: 'andela2017',
// database: 'postit-db-test',
username: 'postgres',
password: '',
database: 'postit_db_test',
host: '127.0.0.1',
port: 5432,
secret_key: process.env.SECRET_KEY,
dialect: 'postgres'
},
production: {
use_env_variable: 'PROD_DB_URL',
username: '?',
password: '?',
database: '?',
host: '?',
dialect: '?'
}
};
|
Add feedback during county loader | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import csv
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from ...models import County
from scuole.states.models import State
class Command(BaseCommand):
help = 'Bootstraps County models using DSHS county list.'
def handle(self, *args, **options):
self.texas = State.objects.get(name='Texas')
counties_file = os.path.join(
settings.DATA_FOLDER, 'counties', 'counties.csv')
with open(counties_file, 'rU') as f:
reader = csv.DictReader(f)
counties = []
for row in reader:
counties.append(self.create_county(row))
County.objects.bulk_create(counties)
def create_county(self, county):
self.stdout.write(
'Creating {} County...'.format(county['County Name']))
return County(
name=county['County Name'],
slug=slugify(county['County Name']),
fips=county['FIPS #'],
state=self.texas,
)
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import csv
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from ...models import County
from scuole.states.models import State
class Command(BaseCommand):
help = 'Bootstraps County models using DSHS county list.'
def handle(self, *args, **options):
self.texas = State.objects.get(name='Texas')
counties_file = os.path.join(
settings.DATA_FOLDER, 'counties', 'counties.csv')
with open(counties_file, 'rU') as f:
reader = csv.DictReader(f)
counties = []
for row in reader:
counties.append(self.create_county(row))
County.objects.bulk_create(counties)
def create_county(self, county):
return County(
name=county['County Name'],
slug=slugify(county['County Name']),
fips=county['FIPS #'],
state=self.texas,
)
|
Clean usage of Trait variant | <?php
/**
* @link https://github.com/paulzi/yii2-adjacency-list
* @copyright Copyright (c) 2015 PaulZi <pavel.zimakoff@gmail.com>
* @license MIT (https://github.com/paulzi/yii2-adjacency-list/blob/master/LICENSE)
*/
namespace paulzi\adjacencylist;
/**
* @author PaulZi <pavel.zimakoff@gmail.com>
*/
trait AdjacencyListQueryTrait
{
/**
* @return \yii\db\ActiveQuery
*/
public function roots()
{
/** @var \yii\db\ActiveQuery $this */
$class = $this->modelClass;
$model = new $class;
return $this->andWhere([$model->parentAttribute => null]);
}
}
| <?php
/**
* @link https://github.com/paulzi/yii2-adjacency-list
* @copyright Copyright (c) 2015 PaulZi <pavel.zimakoff@gmail.com>
* @license MIT (https://github.com/paulzi/yii2-adjacency-list/blob/master/LICENSE)
*/
namespace paulzi\adjacencylist;
/**
* @author PaulZi <pavel.zimakoff@gmail.com>
*/
trait AdjacencyListQueryTrait
{
/**
* @return \yii\db\ActiveQuery
*/
public function roots()
{
/** @var \yii\db\ActiveQuery $this */
$class = $this->modelClass;
if (isset($class::$adjacencyListParentAttribute)) {
return $this->andWhere([$class::$adjacencyListParentAttribute => null]);
} else {
/** @var \yii\db\ActiveRecord|AdjacencyListBehavior $model */
$model = new $class;
return $this->andWhere([$model->parentAttribute => null]);
}
}
}
|
Set ember-data versions in ember try config to canary to make tests pass for each scenario | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release',
'ember-data': 'components/ember-data#canary'
},
resolutions: {
'ember': 'release',
'ember-data': 'canary'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta',
'ember-data': 'components/ember-data#canary'
},
resolutions: {
'ember': 'beta',
'ember-data': 'canary'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary',
'ember-data': 'components/ember-data#canary'
},
resolutions: {
'ember': 'canary',
'ember-data': 'canary'
}
}
]
};
| module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
|
Make squish private as it's dangerous. | function compose() {
fs = arguments;
return function(x) {
for(var i in fs) {
var f = fs[fs.length - i - 1];
x = f.apply(null, [x]);
}
return x;
}
}
function merge(x1, x2) {
function squish(under, over) {
for (var key in over) {
under[key] = over[key];
}
return under;
}
return squish(squish({}, x1), x2);
}
function Person(name) {
return {_name: name};
}
function Titled(x) {
return merge(x, {_title: "Dr"});
}
function Friendly(x) {
return merge(x, {hello: function() { return "Hi, I'm " + x._title + " " + x._name;}});
}
var TitledPerson = compose(Titled, Person);
var Friend = compose(Friendly, Titled, Person);
var tony = new Friend("Tony");
console.log(tony);
console.log(tony.hello());
| function compose() {
fs = arguments;
return function(x) {
for(var i in fs) {
var f = fs[fs.length - i - 1];
x = f.apply(null, [x]);
}
return x;
}
}
function squish(x1, x2) {
for (var key in x2) {
x1[key] = x2[key];
}
return x1;
}
function merge(x1, x2) {
return squish(squish({}, x1), x2);
}
function Person(name) {
return {_name: name};
}
function Titled(x) {
return merge(x, {_title: "Dr"});
}
function Friendly(x) {
return merge(x, {hello: function() { return "Hi, I'm " + x._title + " " + x._name;}});
}
var TitledPerson = compose(Titled, Person);
var Friend = compose(Friendly, Titled, Person);
var tony = new Friend("Tony");
console.log(tony);
console.log(tony.hello());
|
Fix checking if array contains a string | import queryString from 'query-string';
export const getFromQuery = (key, defaultValue = null) => {
let value = queryString.parse(location.search)[key];
return value || defaultValue;
};
export const getAttributesFromQuery = (exclude) => {
// Exclude parameter is used to exclude other query string parameters than
// product attribute filters.
const urlParams = queryString.parse(location.search);
let attributes = [];
Object.keys(urlParams).forEach(key => {
if (!exclude.includes(key)) {
if (Array.isArray(urlParams[key])) {
const values = urlParams[key];
values.map((valueSlug) => {
attributes.push(`${key}:${valueSlug}`);
});
} else {
const valueSlug = urlParams[key];
attributes.push(`${key}:${valueSlug}`);
}
}
});
return attributes;
};
export const ensureAllowedName = (name, allowed) => {
let origName = name;
if (name && name[0] === '-') {
name = name.substr(1, name.length);
}
return allowed.indexOf(name) > -1 ? origName : null;
};
| import queryString from 'query-string';
export const getFromQuery = (key, defaultValue = null) => {
let value = queryString.parse(location.search)[key];
return value || defaultValue;
};
export const getAttributesFromQuery = (exclude) => {
// Exclude parameter is used to exclude other query string parameters than
// product attribute filters.
const urlParams = queryString.parse(location.search);
let attributes = [];
Object.keys(urlParams).forEach(key => {
if (!exclude.includes(key)) {
if (Array.isArray(urlParams[key])) {
const values = urlParams[key];
values.map((valueSlug) => {
attributes.push(`${key}:${valueSlug}`);
});
} else {
const valueSlug = urlParams[key];
attributes.push(`${key}:${valueSlug}`);
}
}
});
return attributes;
};
export const ensureAllowedName = (name, allowed) => {
let origName = name;
if (name && name[0] === '-') {
name = name.substr(1, name.length);
}
return name in allowed ? origName : null;
};
|
Add access token to path URL | var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/pages');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.get('/', function(req, res) {
res.render('index', { 'foo': 'hi' });
});
app.post('/hook', function(req, res) {
if (req.body && req.body.after) {
console.log("checking: " + req.body.after);
var request = https.request({ 'host': 'api.github.com',
'path': '/repos/' + config.repoURL + '/status/' + req.body.after + '?access_token=' + config.githubToken,
'method': 'POST'});
request.write(JSON.stringify({ 'state': 'pending' }));
request.end();
}
res.end();
});
app.listen(2345);
| var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/pages');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.get('/', function(req, res) {
res.render('index', { 'foo': 'hi' });
});
app.post('/hook', function(req, res) {
if (req.body && req.body.after) {
console.log("checking: " + req.body.after);
var request = https.request({ 'host': 'api.github.com',
'path': '/repos/' + config.repoURL + '/status/' + req.body.after,
'method': 'POST'});
request.write(JSON.stringify({ 'state': 'pending' }));
request.end();
}
res.end();
});
app.listen(2345);
|
Add javadoc to DraggablePanel application class | /*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* 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.github.pedrovgs.sample;
import android.app.Application;
import com.github.pedrovgs.sample.di.MainModule;
import dagger.ObjectGraph;
/**
* Application implementation created to handle the dependency container implementation provided by the ObjectGraph
* entity.
*
* @author Pedro Vicente Gómez Sánchez.
*/
public class DraggablePanelApplication extends Application {
private ObjectGraph objectGraph;
/**
* Override method used to initialize the dependency container graph with the MainModule.
*/
@Override
public void onCreate() {
super.onCreate();
MainModule mainModule = new MainModule(this);
objectGraph = ObjectGraph.create(mainModule);
objectGraph.inject(this);
objectGraph.injectStatics();
}
/**
* Inject an object to provide all the needed dependencies.
*
* @param object
*/
public void inject(Object object) {
objectGraph.inject(object);
}
}
| /*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* 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.github.pedrovgs.sample;
import android.app.Application;
import com.github.pedrovgs.sample.di.MainModule;
import dagger.ObjectGraph;
/**
* @author Pedro Vicente Gómez Sánchez.
*/
public class DraggablePanelApplication extends Application {
private ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
MainModule mainModule = new MainModule(this);
objectGraph = ObjectGraph.create(mainModule);
objectGraph.inject(this);
objectGraph.injectStatics();
}
public void inject(Object object) {
objectGraph.inject(object);
}
}
|
Add a limit to number of undoable actions | import undoable from 'redux-undo-immutable';
import { fromJS } from 'immutable';
import { findPathByNodeId } from '../utils/vertTreeUtils';
const verticalTreeData = (
state = fromJS([
{
value: 'Root',
children: [
{ value: 'child', children: [], _id: 2000 },
{ value: 'child2', children: [ { value: 'grandchild', children: [], _id: 3000 } ], _id: 4000 }
],
_id: 1000
}
]),
action
) => {
let path = findPathByNodeId(action.nodeId, state);
switch (action.type) {
case 'UPDATE_VERT_STRUCTURE':
return action.newState;
case 'HIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, true);
case 'UNHIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, false);
default:
return state;
}
};
const undoableVerticalTreeData = undoable(verticalTreeData, {
limit: 20
});
export default {
verticalTreeData: undoableVerticalTreeData,
testableVerticalTreeData: verticalTreeData
};
| import undoable from 'redux-undo-immutable';
import { fromJS } from 'immutable';
import { findPathByNodeId } from '../utils/vertTreeUtils';
const verticalTreeData = (
state = fromJS([
{
value: 'Root',
children: [
{ value: 'child', children: [], _id: 2000 },
{ value: 'child2', children: [ { value: 'grandchild', children: [], _id: 3000 } ], _id: 4000 }
],
_id: 1000
}
]),
action
) => {
let path = findPathByNodeId(action.nodeId, state);
switch (action.type) {
case 'UPDATE_VERT_STRUCTURE':
return action.newState;
case 'HIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, true);
case 'UNHIGHLIGHT_NODE':
path.push('highlighted');
return state.setIn(path, false);
default:
return state;
}
};
const undoableVerticalTreeData = undoable(verticalTreeData);
export default {
verticalTreeData: undoableVerticalTreeData,
testableVerticalTreeData: verticalTreeData
};
|
Drop email as property from post_update_user_schema | from app.schema_validation.definitions import uuid, datetime
post_create_user_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for creating user",
"type": "object",
"properties": {
'email': {"type": "string"},
'name': {"type": "string"},
'active': {"type": "boolean"},
'access_area': {"type": "string"},
},
"required": ['email']
}
post_update_user_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for updating user",
"type": "object",
"properties": {
'name': {"type": "string"},
'active': {"type": "boolean"},
'access_area': {"type": "string"},
'last_login': {"type": "date-time"},
'session_id': {"type": "string"},
'ip': {"type": "string"},
},
"required": []
}
| from app.schema_validation.definitions import uuid, datetime
post_create_user_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for creating user",
"type": "object",
"properties": {
'email': {"type": "string"},
'name': {"type": "string"},
'active': {"type": "boolean"},
'access_area': {"type": "string"},
},
"required": ['email']
}
post_update_user_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for updating user",
"type": "object",
"properties": {
'email': {"format": "email", "type": "string"},
'name': {"type": "string"},
'active': {"type": "boolean"},
'access_area': {"type": "string"},
'last_login': {"type": "date-time"},
'session_id': {"type": "string"},
'ip': {"type": "string"},
},
"required": ['email']
}
|
Move api config outside of manager commands | from flask_script import Manager
from flask_restful import Api
from config import app
from api import api
manager = Manager(app)
def setup_api(app):
"""
Config resources with flask app
"""
service = Api(app)
service.add_resource(api.MailChimpList,'/api/list/<list_id>',endpoint='list')
service.add_resource(api.MailChimpMember,'/api/member/<asu_id>',endpoint='member')
service.add_resource(api.GenerateAuthToken,'/api/gen_token',endpoint='token')
return app
serviced_app = setup_api(app)
# Deploy for development
@manager.command
def run_dev():
serviced_app.run(debug=True)
# Deploy for intergation tests
@manager.command
def run_test():
# To-Do
pass
# Deploy for production
@manager.command
def run_production():
# TO-DO
pass
if __name__ == '__main__':
manager.run()
| from flask_script import Manager
from flask_restful import Api
from config import app
from api import api
manager = Manager(app)
def setup_api(app):
"""
Config resources with flask app
"""
service = Api(app)
service.add_resource(api.MailChimpList,'/api/list/<list_id>',endpoint='list')
service.add_resource(api.MailChimpMember,'/api/member/<asu_id>',endpoint='member')
service.add_resource(api.GenerateAuthToken,'/api/gen_token',endpoint='token')
return app
# Deploy for development
@manager.command
def run_dev():
serviced_app = setup_api(app)
serviced_app.run(debug=True)
# Deploy for intergation tests
@manager.command
def run_test():
# To-Do
pass
# Deploy for production
@manager.command
def run_production():
# TO-DO
pass
if __name__ == '__main__':
manager.run()
|
Add space at start of comments when writing config | package com.Acrobot.Breeze.Configuration;
import com.Acrobot.Breeze.Configuration.Annotations.ConfigurationComment;
import com.Acrobot.Breeze.Configuration.Annotations.Parser;
import java.lang.reflect.Field;
/**
* @author Acrobot
*/
public class FieldParser {
/**
* Parses a field into a YAML-compatible string
*
* @param field Field to parse
* @return Parsed field
*/
public static String parse(Field field) {
StringBuilder builder = new StringBuilder(50);
if (field.isAnnotationPresent(ConfigurationComment.class)) {
builder.append("# ").append(field.getAnnotation(ConfigurationComment.class).value()).append('\n');
}
ValueParser parser = Configuration.getParser(field);
try {
builder.append(field.getName()).append(": ").append(parser.parseToYAML(field.get(null)));
} catch (IllegalAccessException e) {
e.printStackTrace();
return "";
}
return builder.toString();
}
}
| package com.Acrobot.Breeze.Configuration;
import com.Acrobot.Breeze.Configuration.Annotations.ConfigurationComment;
import com.Acrobot.Breeze.Configuration.Annotations.Parser;
import java.lang.reflect.Field;
/**
* @author Acrobot
*/
public class FieldParser {
/**
* Parses a field into a YAML-compatible string
*
* @param field Field to parse
* @return Parsed field
*/
public static String parse(Field field) {
StringBuilder builder = new StringBuilder(50);
if (field.isAnnotationPresent(ConfigurationComment.class)) {
builder.append('#').append(field.getAnnotation(ConfigurationComment.class).value()).append('\n');
}
ValueParser parser = Configuration.getParser(field);
try {
builder.append(field.getName()).append(": ").append(parser.parseToYAML(field.get(null)));
} catch (IllegalAccessException e) {
e.printStackTrace();
return "";
}
return builder.toString();
}
}
|
Set username, password and don't set socket timeout | package com.proofpoint.dbpool;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import static java.lang.Math.ceil;
import static java.util.concurrent.TimeUnit.SECONDS;
public class MySqlDataSource extends ManagedDataSource
{
public MySqlDataSource(MySqlDataSourceConfig config)
{
super(createMySQLConnectionPoolDataSource(config),
config.getMaxConnections(),
config.getMaxConnectionWait());
}
private static MysqlConnectionPoolDataSource createMySQLConnectionPoolDataSource(MySqlDataSourceConfig config) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setServerName(config.getHost());
dataSource.setUser(config.getUsername());
dataSource.setPassword(config.getPassword());
dataSource.setPort(config.getPort());
dataSource.setDatabaseName(config.getDatabaseName());
dataSource.setConnectTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setInitialTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setDefaultFetchSize(config.getDefaultFetchSize());
dataSource.setUseSSL(config.getUseSsl());
return dataSource;
}
}
| package com.proofpoint.dbpool;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import static java.lang.Math.ceil;
import static java.util.concurrent.TimeUnit.SECONDS;
public class MySqlDataSource extends ManagedDataSource
{
public MySqlDataSource(MySqlDataSourceConfig config)
{
super(createMySQLConnectionPoolDataSource(config),
config.getMaxConnections(),
config.getMaxConnectionWait());
}
private static MysqlConnectionPoolDataSource createMySQLConnectionPoolDataSource(MySqlDataSourceConfig config) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setServerName(config.getHost());
dataSource.setPort(config.getPort());
dataSource.setDatabaseName(config.getDatabaseName());
dataSource.setConnectTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setInitialTimeout((int) ceil(config.getMaxConnectionWait().convertTo(SECONDS)));
dataSource.setSocketTimeout((int) ceil(config.getMaxConnectionWait().toMillis()));
dataSource.setDefaultFetchSize(config.getDefaultFetchSize());
dataSource.setUseSSL(config.getUseSsl());
return dataSource;
}
}
|
Change use of quotation marks | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: goodson@google.com
# Maintained By: goodson@google.com
"""
Remove relationships related to deleted response objects
Create Date: 2016-05-10 12:25:26.383695
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '44ebc240800b'
down_revision = '3715694bd315'
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
op.execute(
"""
DELETE FROM relationships
WHERE source_type IN
("Response", "DocumentationResponse", "InterviewResponse",
"PopulationSampleResponse")
OR destination_type IN
("Response", "DocumentationResponse", "InterviewResponse",
"PopulationSampleResponse")
""")
def downgrade():
"""Downgrade database schema and/or data back to the previous revision."""
pass
| # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: goodson@google.com
# Maintained By: goodson@google.com
"""
Remove relationships related to deleted response objects
Create Date: 2016-05-10 12:25:26.383695
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '44ebc240800b'
down_revision = '3715694bd315'
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
op.execute(
'DELETE FROM relationships '
'WHERE source_type IN '
' ("Response", "DocumentationResponse", "InterviewResponse",'
' "PopulationSampleResponse") '
' OR destination_type IN '
' ("Response", "DocumentationResponse", "InterviewResponse", '
' "PopulationSampleResponse")')
def downgrade():
"""Downgrade database schema and/or data back to the previous revision."""
pass
|
Remove shell console script from entry points
Amends e09ee16a77a7181fbf8ee18841be6ca37fd32250 | from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.web',
version='1.0a13.dev0',
description='RESTful Web Framework',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.web/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=PEP420PackageFinder.find(include=['tangled*']),
include_package_data=True,
install_requires=[
'tangled>=1.0a12',
'MarkupSafe>=0.23',
'WebOb>=1.5.1',
],
entry_points="""
[tangled.scripts]
serve = tangled.web.scripts.serve
show = tangled.web.scripts.show
[tangled.scaffolds]
basic = tangled.web.scaffolds:basic
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
)
| from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.web',
version='1.0a13.dev0',
description='RESTful Web Framework',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.web/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=PEP420PackageFinder.find(include=['tangled*']),
include_package_data=True,
install_requires=[
'tangled>=1.0a12',
'MarkupSafe>=0.23',
'WebOb>=1.5.1',
],
entry_points="""
[tangled.scripts]
serve = tangled.web.scripts.serve
shell = tangled.web.scripts.shell
show = tangled.web.scripts.show
[tangled.scaffolds]
basic = tangled.web.scaffolds:basic
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
)
|
Add missing validate method to GoogleAppsPasswordValidator
Django complains when updating the password:
'GoogleAppsPasswordValidator' object has no attribute 'validate' | # -*- coding: utf-8 -*-
# Copyright (c) Polytechnique.org
# This code is distributed under the Affero General Public License version 3
import crypt
import sys
from django.core.exceptions import ObjectDoesNotExist
from django.utils.crypto import get_random_string
from . import models
class GoogleAppsPasswordValidator(object):
"""Update the Google Apps password when a user changes her password"""
def validate(self, password, user=None):
return
def password_changed(self, raw_password, user):
# Hash the password in a way compatible with Google Apps: crypt with $6
if sys.version_info >= (3,):
password = crypt.crypt(raw_password, salt=crypt.METHOD_SHA512)
else:
password = crypt.crypt(raw_password.encode('utf-8'), '$6$' + get_random_string(16))
try:
user.gapps_password.password = password
except ObjectDoesNotExist:
models.GoogleAppsPassword.objects.create(user=user, password=password)
else:
user.gapps_password.save()
| # -*- coding: utf-8 -*-
# Copyright (c) Polytechnique.org
# This code is distributed under the Affero General Public License version 3
import crypt
import sys
from django.core.exceptions import ObjectDoesNotExist
from django.utils.crypto import get_random_string
from . import models
class GoogleAppsPasswordValidator(object):
"""Update the Google Apps password when a user changes her password"""
def password_changed(self, raw_password, user):
# Hash the password in a way compatible with Google Apps: crypt with $6
if sys.version_info >= (3,):
password = crypt.crypt(raw_password, salt=crypt.METHOD_SHA512)
else:
password = crypt.crypt(raw_password.encode('utf-8'), '$6$' + get_random_string(16))
try:
user.gapps_password.password = password
except ObjectDoesNotExist:
models.GoogleAppsPassword.objects.create(user=user, password=password)
else:
user.gapps_password.save()
|
Adjust to new endpoint method in connector 1.8 | package org.osiam.addons.administration.config;
import org.osiam.client.OsiamConnector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* This class is responsible for building an osiam-connector.
*/
@Configuration
public class ConnectorBuilder {
@Value("${org.osiam.clientId}")
private String clientId;
@Value("${org.osiam.clientSecret}")
private String clientSecret;
@Value("${org.osiam.endpoint}")
private String osiamEndpoint;
@Value("${org.osiam.redirectUri}")
private String redirectUri;
@Bean
public OsiamConnector build() {
return new OsiamConnector.Builder()
.withEndpoint(osiamEndpoint)
.setClientRedirectUri(redirectUri)
.setClientId(clientId)
.setClientSecret(clientSecret)
.build();
}
}
| package org.osiam.addons.administration.config;
import org.osiam.client.OsiamConnector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* This class is responsible for building an osiam-connector.
*/
@Configuration
public class ConnectorBuilder {
@Value("${org.osiam.clientId}")
private String clientId;
@Value("${org.osiam.clientSecret}")
private String clientSecret;
@Value("${org.osiam.endpoint}")
private String osiamEndpoint;
@Value("${org.osiam.redirectUri}")
private String redirectUri;
@Bean
public OsiamConnector build() {
return new OsiamConnector.Builder()
.setEndpoint(osiamEndpoint)
.setClientRedirectUri(redirectUri)
.setClientId(clientId)
.setClientSecret(clientSecret)
.build();
}
}
|
Fix crash when none resolved hostname | package main
import (
"fmt"
"net"
"os"
flags "github.com/jessevdk/go-flags"
)
const version = "1.0.0"
var opts struct {
Version bool `short:"v" long:"version" description:"Show version"`
}
func main() {
parser := flags.NewParser(&opts, flags.Default)
parser.Usage = "HOSTNAME [OPTIONS]"
args, _ := parser.Parse()
if len(args) == 0 {
if opts.Version {
fmt.Println("ptrhost version", version)
}
os.Exit(1)
}
hostname := args[0]
addr, _ := net.LookupHost(hostname)
for _, v := range addr {
resolvedHost, err := net.LookupAddr(v)
if err == nil {
fmt.Println(v, "->", resolvedHost[0])
} else {
fmt.Println(v, "->", err.(*net.DNSError).Err)
}
}
}
| package main
import (
"fmt"
"net"
"os"
flags "github.com/jessevdk/go-flags"
)
const version = "1.0.0"
var opts struct {
Version bool `short:"v" long:"version" description:"Show version"`
}
func main() {
parser := flags.NewParser(&opts, flags.Default)
parser.Usage = "HOSTNAME [OPTIONS]"
args, _ := parser.Parse()
if len(args) == 0 {
if opts.Version {
fmt.Println("ptrhost version", version)
}
os.Exit(1)
}
hostname := args[0]
addr, _ := net.LookupHost(hostname)
for _, v := range addr {
ptrAddr, _ := net.LookupAddr(v)
fmt.Println(v, "->", ptrAddr[0])
}
}
|
Update goyaml dependency to new location | package transition
import (
"io/ioutil"
"gopkg.in/yaml.v2"
// "log"
)
type FeatureGroup struct {
Group string
Transition string
Features []string
Idle bool
Associated bool
}
type MorphTemplate struct {
Group string
Combinations []string
}
type FeatureSetup struct {
FeatureGroups []FeatureGroup `yaml:"feature groups"`
MorphTemplates []MorphTemplate `yaml:"morph templates"`
}
func (s *FeatureSetup) NumFeatures() int {
var (
numFeatures int
groupId int
exists bool
)
groupMap := make(map[string]int)
for i, group := range s.FeatureGroups {
numFeatures += len(group.Features)
groupMap[group.Group] = i
}
for _, tmpl := range s.MorphTemplates {
groupId, exists = groupMap[tmpl.Group]
if exists {
numFeatures += len(s.FeatureGroups[groupId].Features) * len(tmpl.Combinations)
}
}
return numFeatures
}
func LoadFeatureConf(conf []byte) *FeatureSetup {
setup := new(FeatureSetup)
yaml.Unmarshal(conf, setup)
return setup
}
func LoadFeatureConfFile(filename string) (*FeatureSetup, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
setup := LoadFeatureConf(data)
return setup, nil
}
| package transition
import (
"io/ioutil"
"launchpad.net/goyaml"
// "log"
)
type FeatureGroup struct {
Group string
Transition string
Features []string
Idle bool
Associated bool
}
type MorphTemplate struct {
Group string
Combinations []string
}
type FeatureSetup struct {
FeatureGroups []FeatureGroup `yaml:"feature groups"`
MorphTemplates []MorphTemplate `yaml:"morph templates"`
}
func (s *FeatureSetup) NumFeatures() int {
var (
numFeatures int
groupId int
exists bool
)
groupMap := make(map[string]int)
for i, group := range s.FeatureGroups {
numFeatures += len(group.Features)
groupMap[group.Group] = i
}
for _, tmpl := range s.MorphTemplates {
groupId, exists = groupMap[tmpl.Group]
if exists {
numFeatures += len(s.FeatureGroups[groupId].Features) * len(tmpl.Combinations)
}
}
return numFeatures
}
func LoadFeatureConf(conf []byte) *FeatureSetup {
setup := new(FeatureSetup)
goyaml.Unmarshal(conf, setup)
return setup
}
func LoadFeatureConfFile(filename string) (*FeatureSetup, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
setup := LoadFeatureConf(data)
return setup, nil
}
|
Remove extra " in generated <source> tags. | <?php
namespace ResponsiveImages;
use Functional as F;
class Source
{
/**
* @var Size[]
*/
private $sizes;
/**
* Whether or not to render as an <img> instead of <source>. This is important
* since the last element in a <picture> should be an <img>, but otherwise is
* nearly the same as a <source>.
*
* @var bool
*/
private $as_img;
function __construct(array $sizes, $as_img=false)
{
$this->sizes = $sizes;
$this->as_img = $as_img;
}
public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
{
$last = F\last($this->sizes);
$srcset = F\map($this->sizes, function(Size $size) use ($uri, $srcset_gen){
return $srcset_gen->listFor($uri, $size);
});
$srcset = F\unique(F\flatten($srcset));
$srcset = implode(', ', $srcset);
$sizes = F\map($this->sizes, function(Size $size) use ($last){
return $size === $last ? $size->renderWidthOnly() : (string)$size;
});
$sizes = implode(', ', $sizes);
$media = !$this->as_img ? ' media="'.$last->getMediaQuery().'"' : '';
$attributes = "srcset=\"$srcset\" sizes=\"$sizes\"$media";
return $this->as_img ? "<img $attributes>" : "<source $attributes>";
}
}
| <?php
namespace ResponsiveImages;
use Functional as F;
class Source
{
/**
* @var Size[]
*/
private $sizes;
/**
* Whether or not to render as an <img> instead of <source>. This is important
* since the last element in a <picture> should be an <img>, but otherwise is
* nearly the same as a <source>.
*
* @var bool
*/
private $as_img;
function __construct(array $sizes, $as_img=false)
{
$this->sizes = $sizes;
$this->as_img = $as_img;
}
public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
{
$last = F\last($this->sizes);
$srcset = F\map($this->sizes, function(Size $size) use ($uri, $srcset_gen){
return $srcset_gen->listFor($uri, $size);
});
$srcset = F\unique(F\flatten($srcset));
$srcset = implode(', ', $srcset);
$sizes = F\map($this->sizes, function(Size $size) use ($last){
return $size === $last ? $size->renderWidthOnly() : (string)$size;
});
$sizes = implode(', ', $sizes);
$media = !$this->as_img ? ' media="'.$last->getMediaQuery().'""' : '';
$attributes = "srcset=\"$srcset\" sizes=\"$sizes\"$media";
return $this->as_img ? "<img $attributes>" : "<source $attributes>";
}
}
|
Fix global test driver initialization | import atexit
import tempfile
import sys
import mock
from selenium import webdriver
import os
def build_mock_mapping(name):
mock_driver = mock.Mock()
browser_mapping = {name: mock_driver}
mock_driver.return_value.name = name
return browser_mapping
test_driver = None
def get_driver():
global test_driver
if not test_driver:
options = webdriver.ChromeOptions()
options.add_argument('headless')
test_driver = webdriver.Chrome(chrome_options=options)
atexit.register(test_driver.quit)
test_driver.delete_all_cookies()
test_driver.switch_to.default_content()
return test_driver
def make_temp_page(src):
f = tempfile.mktemp(".html")
fh = open(f, "w")
fh.write(src.replace("\n", ""))
fh.close()
atexit.register(lambda: os.remove(f))
return "file://%s" % f
def mock_open():
if sys.version_info >= (3, 0, 0):
return mock.patch("builtins.open")
return mock.patch("__builtin__.open")
| import atexit
import tempfile
import sys
import mock
from selenium import webdriver
import os
def build_mock_mapping(name):
mock_driver = mock.Mock()
browser_mapping = {name: mock_driver}
mock_driver.return_value.name = name
return browser_mapping
test_driver = None
def get_driver():
global test_driver
if not test_driver:
options = webdriver.ChromeOptions()
options.add_argument('headless')
chrome = webdriver.Chrome(chrome_options=options)
atexit.register(chrome.quit)
chrome.delete_all_cookies()
chrome.switch_to.default_content()
return chrome
def make_temp_page(src):
f = tempfile.mktemp(".html")
fh = open(f, "w")
fh.write(src.replace("\n", ""))
fh.close()
atexit.register(lambda: os.remove(f))
return "file://%s" % f
def mock_open():
if sys.version_info >= (3, 0, 0):
return mock.patch("builtins.open")
return mock.patch("__builtin__.open")
|
Fix syntax error from wrong quotation mark. | <?php
function env_is_cli() {
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}
// ----- only run from command line -----
if (!env_is_cli())
die;
// ----- params -----
set_time_limit(0);
error_reporting(E_ALL);
define('CAPTURE', 'onepercent');
// ----- includes -----
include __DIR__ . '/../../config.php'; // load base config file
include __DIR__ . '/../../common/functions.php'; // load base functions file
include __DIR__ . '/../common/functions.php'; // load capture function file
require __DIR__ . '/../common/tmhOAuth/tmhOAuth.php';
$thislockfp = script_lock(CAPTURE);
if (!is_resource($thislockfp)) {
logit(CAPTURE . ".error.log", "script invoked but will not continue because a process is already holding the lock file.");
die; // avoid double execution of script
}
if (dbserver_has_utf8mb4_support() == false) {
logit(CAPTURE . ".error.log", "DMI-TCAT requires at least MySQL version 5.5.3 - please upgrade your server");
exit();
}
// ----- connection -----
dbconnect(); // connect to database @todo, rewrite mysql calls with pdo
tracker_run();
| <?php
function env_is_cli() {
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}
// ----- only run from command line -----
if (!env_is_cli())
die;
// ----- params -----
set_time_limit(0);
error_reporting(E_ALL);
define('CAPTURE', 'onepercent');
// ----- includes -----
include __DIR__ . '/../../config.php'; // load base config file
include __DIR__ . '/../../common/functions.php'; // load base functions file
include __DIR__ . '/../common/functions.php"; // load capture function file
require __DIR__ . '/../common/tmhOAuth/tmhOAuth.php';
$thislockfp = script_lock(CAPTURE);
if (!is_resource($thislockfp)) {
logit(CAPTURE . ".error.log", "script invoked but will not continue because a process is already holding the lock file.");
die; // avoid double execution of script
}
if (dbserver_has_utf8mb4_support() == false) {
logit(CAPTURE . ".error.log", "DMI-TCAT requires at least MySQL version 5.5.3 - please upgrade your server");
exit();
}
// ----- connection -----
dbconnect(); // connect to database @todo, rewrite mysql calls with pdo
tracker_run();
|
Remove comment, and remove an unnecessary variable | <?php
if ($cfg->db->connect) {
if (isset($_COOKIE[$cfg->system->cookie]) && !empty($_COOKIE[$cfg->system->cookie])) {
$cookie = explode(".", $_COOKIE[$cfg->system->cookie]);
if (count($cookie) === 2) {
$cookie[0] = intval($cookie[0]);
$cookie[1] = $mysqli->real_escape_string($cookie[1]);
$query = sprintf(
"SELECT * FROM %s_users WHERE id = '%s' AND password = '%s' LIMIT %s",
$cfg->db->prefix, $cookie[0], $cookie[1], 1
);
$source = $mysqli->query($query);
if ($source->num_rows == 1) {
$auth = true;
$authData = $source->fetch_assoc();
} else {
$auth = false;
}
}
} else {
$auth = false;
}
} else {
$auth = false;
}
| <?php
// controlador de sessão
if ($cfg->db->connect) {
if (isset($_COOKIE[$cfg->system->cookie]) && !empty($_COOKIE[$cfg->system->cookie])) {
$cookie = explode(".", $_COOKIE[$cfg->system->cookie]);
if (count($cookie) === 2) {
$cookie[0] = intval($cookie[0]);
$cookie[1] = $mysqli->real_escape_string($cookie[1]);
$query = sprintf(
"SELECT * FROM %s_users WHERE id = '%s' AND password = '%s' LIMIT %s",
$cfg->db->prefix, $cookie[0], $cookie[1], 1
);
$source = $mysqli->query($query);
$nr = $source->num_rows;
if ($nr === 1) {
$auth = true;
$authData = $source->fetch_assoc();
} else {
$auth = false;
}
}
} else {
$auth = false;
}
} else {
$auth = false;
}
|
Update Persian language for AdminLte template | <?php
return array (
'ADMINISTRATION' => 'مدیریت کل',
'Control Panel' => 'پنل کنترل',
'Dashboard' => 'داشبورد',
'Files' => 'فایل ها',
'Forgot Password?' => 'فراموشی رمزعبور؟',
'Logout' => 'خروج',
'Member since {0}' => 'عضو از {0}',
'Profile' => 'پروفایل',
'Roles' => 'وظیفه ها',
'Settings' => 'تنظیمات',
'Sign In' => 'ورود',
'Sign Up' => 'عضویت',
'Sign out' => 'خروج',
'Users' => 'کاربران',
);
| <?php
return array (
'ADMINISTRATION' => 'مدیریت کل',
'Control Panel' => 'پنل کنترل',
'Dashboard' => 'داشبورد',
'Files' => '',
'Forgot Password?' => 'فراموشی رمزعبور؟',
'Logout' => 'خروج',
'Member since {0}' => 'عضو از {0}',
'Profile' => 'پروفایل',
'Roles' => 'وظیفه ها',
'Settings' => 'تنظیمات',
'Sign In' => 'ورود',
'Sign Up' => 'عضویت',
'Sign out' => 'خروج',
'Users' => 'کاربران',
);
|
Hide searchbar in upload modal ctm when not allowed to read
Signed-off-by: soupette <0a59f0508aa203bc732745954131d022d9f538a9@gmail.com> | import React, { useState, useEffect, memo } from 'react';
import { useDebounce } from '@buffetjs/hooks';
import { useGlobalContext } from 'strapi-helper-plugin';
import getTrad from '../../utils/getTrad';
import useModalContext from '../../hooks/useModalContext';
import HeaderSearch from './HeaderSearch';
const Search = () => {
const [value, setValue] = useState('');
const {
allowedActions: { canRead },
setParam,
} = useModalContext();
const { formatMessage } = useGlobalContext();
const debouncedSearch = useDebounce(value, 300);
useEffect(() => {
if (canRead) {
setParam({ name: '_q', value: debouncedSearch });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debouncedSearch, canRead]);
const handleSearchChange = e => {
setValue(e.target.value);
};
const handleClear = () => {
setValue('');
};
if (!canRead) {
return null;
}
return (
<HeaderSearch
onChange={handleSearchChange}
onClear={handleClear}
placeholder={formatMessage({ id: getTrad('search.placeholder') })}
name="_q"
value={value}
/>
);
};
export default memo(Search);
| import React, { useState, useEffect, memo } from 'react';
import { useDebounce } from '@buffetjs/hooks';
import { useGlobalContext } from 'strapi-helper-plugin';
import getTrad from '../../utils/getTrad';
import useModalContext from '../../hooks/useModalContext';
import HeaderSearch from './HeaderSearch';
const Search = () => {
const [value, setValue] = useState('');
const { setParam } = useModalContext();
const { formatMessage } = useGlobalContext();
const debouncedSearch = useDebounce(value, 300);
useEffect(() => {
setParam({ name: '_q', value: debouncedSearch });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debouncedSearch]);
const handleSearchChange = e => {
setValue(e.target.value);
};
const handleClear = () => {
setValue('');
};
return (
<HeaderSearch
onChange={handleSearchChange}
onClear={handleClear}
placeholder={formatMessage({ id: getTrad('search.placeholder') })}
name="_q"
value={value}
/>
);
};
export default memo(Search);
|
Remove duplicate entry for vikidia and gutenberg in burundi boxes | """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa
(_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa
(_('Origin'), ['country', 'city', 'country_of_origin_occupation', 'school_level', 'is_sent_to_school']), # noqa
(_('Language skills'), ['rn_level', 'sw_level', 'fr_level']),
(_('National residents'), ['id_card_number']),
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'cpassorcier',
},
{
'id': 'ted',
},
]
| """Generic config for Ideasbox of Burundi"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['refugee_id', 'short_name', 'full_name', 'birth_year', 'gender', 'phone']), # noqa
(_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa
(_('In the camp'), ['camp_entry_date', 'camp_activities', 'current_occupation', 'camp_address']), # noqa
(_('Origin'), ['country', 'city', 'country_of_origin_occupation', 'school_level', 'is_sent_to_school']), # noqa
(_('Language skills'), ['rn_level', 'sw_level', 'fr_level']),
(_('National residents'), ['id_card_number']),
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'vikidia',
},
{
'id': 'gutenberg',
},
{
'id': 'cpassorcier',
},
{
'id': 'ted',
},
]
|
Remove single char args, this is not an interactive tool. | package com.vaguehope.morrigan;
import org.kohsuke.args4j.Option;
public class Args {
@Option(name = "--dlna", usage = "Enable DLNA.") private boolean dlna;
@Option(name = "--interface", usage = "Hostname or IP address of interface to bind to.") private String iface;
@Option(name = "--port", usage = "Local port to bind HTTP UI to.") private int httpPort = -1;
@Option(name = "--ssh", usage = "Local port to bind SSH UI to.") private int sshPort = -1;
@Option(name = "-v", aliases = { "--verbose" }, usage = "print log lines for various events.") private boolean verboseLog = false;
public String getInterface () {
return this.iface;
}
public int getHttpPort() {
return this.httpPort;
}
public int getSshPort() {
return this.sshPort;
}
public boolean isDlna() {
return this.dlna;
}
public boolean isVerboseLog() {
return this.verboseLog;
}
}
| package com.vaguehope.morrigan;
import org.kohsuke.args4j.Option;
public class Args {
@Option(name = "-d", aliases = { "--dlna" }, usage = "Enable DLNA.") private boolean dlna;
@Option(name = "-i", aliases = { "--interface" }, usage = "Hostname or IP address of interface to bind to.") private String iface;
@Option(name = "-p", aliases = { "--port" }, usage = "Local port to bind HTTP UI to.") private int httpPort = -1;
@Option(name = "-s", aliases = { "--ssh" }, usage = "Local port to bind SSH UI to.") private int sshPort = -1;
@Option(name = "-v", aliases = { "--verbose" }, usage = "print log lines for various events.") private boolean verboseLog = false;
public String getInterface () {
return this.iface;
}
public int getHttpPort() {
return this.httpPort;
}
public int getSshPort() {
return this.sshPort;
}
public boolean isDlna() {
return this.dlna;
}
public boolean isVerboseLog() {
return this.verboseLog;
}
}
|
Update script-src to include newrelic | # define flask extensions in separate file, to resolve import dependencies
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from flask_caching import Cache
cache = Cache()
from flask_assets import Environment
assets = Environment()
from flask_babel import Babel
babel = Babel()
from flask_mail import Mail
mail = Mail()
from flask_login import LoginManager
login_manager = LoginManager()
from flask_restless import APIManager
rest = APIManager()
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()
from flask_store import Store
store = Store()
from flask_rq2 import RQ
rq = RQ()
from flask_talisman import Talisman
CALLPOWER_CSP = {
'default-src':'\'self\'',
'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'',
'cdnjs.cloudflare.com', 'media.twiliocdn.com', 'js-agent.newrelic.com'],
'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
'font-src': ['\'self\'', 'fonts.gstatic.com'],
'media-src': ['\'self\'', 'media.twiliocdn.com'],
'connect-src': ['\'self\'', 'wss://*.twilio.com', ]
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman = Talisman() | # define flask extensions in separate file, to resolve import dependencies
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from flask_caching import Cache
cache = Cache()
from flask_assets import Environment
assets = Environment()
from flask_babel import Babel
babel = Babel()
from flask_mail import Mail
mail = Mail()
from flask_login import LoginManager
login_manager = LoginManager()
from flask_restless import APIManager
rest = APIManager()
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()
from flask_store import Store
store = Store()
from flask_rq2 import RQ
rq = RQ()
from flask_talisman import Talisman
CALLPOWER_CSP = {
'default-src':'\'self\'',
'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'],
'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
'font-src': ['\'self\'', 'fonts.gstatic.com'],
'media-src': ['\'self\'', 'media.twiliocdn.com'],
'connect-src': ['\'self\'', 'wss://*.twilio.com', ]
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman = Talisman() |
Rename unused but needed variable | #!/usr/bin/env python3
from flask import Flask, redirect, request
from resumable import rebuild, split
app = Flask(__name__)
# for the purposes of this demo, we will explicitly pass request
# and response (this is not needed in flask)
@rebuild
def controller(_):
page = '''
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<form action="/c/welcomed" method=post>
<input name="name"/>
<button type=submit>Submit</button>
</form>
'''
response = value(page, 'welcomed')
page = '''
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<form action="/c/my_name" method=post>
<label>
Hi, {}, my name is
<input name="my_name"/>
</label>
<button type=submit>Submit</button>
</form>
'''.format(response.form['name'])
response = value(page, 'my_name')
return value('Sweet, my name is {}!'.format(response.form['my_name']))
@app.route('/c/<name>', methods=['POST', 'GET'])
def router(name):
return controller[name](request)
@app.route('/')
def index():
return redirect('/c/controller')
if __name__ == '__main__':
app.run(debug=True)
| #!/usr/bin/env python3
from flask import Flask, redirect, request
from resumable import rebuild, split
app = Flask(__name__)
# for the purposes of this demo, we will explicitly pass request
# and response (this is not needed in flask)
@rebuild
def controller(request):
page = '''
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<form action="/c/welcomed" method=post>
<input name="name"/>
<button type=submit>Submit</button>
</form>
'''
response = value(page, 'welcomed')
page = '''
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<form action="/c/my_name" method=post>
<label>
Hi, {}, my name is
<input name="my_name"/>
</label>
<button type=submit>Submit</button>
</form>
'''.format(response.form['name'])
response = value(page, 'my_name')
return value('Sweet, my name is {}!'.format(response.form['my_name']))
@app.route('/c/<name>', methods=['POST', 'GET'])
def router(name):
return controller[name](request)
@app.route('/')
def index():
return redirect('/c/controller')
if __name__ == '__main__':
app.run(debug=True)
|
Return types in routing and news bundle | <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ProductStatusBundle\Entity;
use WellCommerce\Bundle\RoutingBundle\Entity\Route;
use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface;
/**
* Class ProductStatusRoute
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ProductStatusRoute extends Route implements RouteInterface
{
/**
* @var ProductStatusInterface
*/
protected $identifier;
/**
* @return string
*/
public function getType() : string
{
return 'product_status';
}
}
| <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ProductStatusBundle\Entity;
use WellCommerce\Bundle\RoutingBundle\Entity\Route;
use WellCommerce\Bundle\RoutingBundle\Entity\RouteInterface;
/**
* Class ProductStatusRoute
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ProductStatusRoute extends Route implements RouteInterface
{
/**
* @var ProductStatusInterface
*/
protected $identifier;
/**
* @return string
*/
public function getType()
{
return 'product_status';
}
}
|
Enhance nav component and introduce prefix prop | import React from 'react';
import classnames from 'classnames';
function Nav({ inverse, children, fixed, prefix }) {
const className = classnames('ui-nav', {
'ui-nav-fixed': fixed,
'ui-nav-inverse': inverse,
});
return (
<div className={className}>
{prefix && <div className="ui-nav-prefix">{prefix}</div>}
<div className={classnames('ui-nav-navitems')}>
{children}
</div>
</div>
);
}
Nav.propTypes = {
fixed: React.PropTypes.bool.isRequired,
inverse: React.PropTypes.bool.isRequired,
children: React.PropTypes.node,
prefix: React.PropTypes.node,
};
Nav.defaultProps = {
fixed: false,
inverse: false,
prefix: null,
children: null,
};
export default Nav;
| import React from 'react';
import classnames from 'classnames';
import { GridContainer, GridRow, GridCol } from '../Grid';
const Nav = props => (
<div
className={classnames('ui-nav', {
'ui-nav-fixed': props.fixed,
'ui-nav-inverse': props.inverse,
})}
>
<GridContainer fluid>
<GridRow>
<GridCol>
<div className={classnames('ui-nav-navitems')}>
{props.children}
</div>
</GridCol>
</GridRow>
</GridContainer>
</div>
);
Nav.propTypes = {
fixed: React.PropTypes.bool.isRequired,
inverse: React.PropTypes.bool.isRequired,
children: React.PropTypes.node,
};
Nav.defaultProps = {
fixed: false,
inverse: false,
};
export default Nav;
|
Reorganize the code a bit. | var express = require('express');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var yargs = require('yargs');
var args = yargs
.alias('p', 'production')
.argv;
var app = new express();
var port = 8000;
process.env.NODE_ENV = args.production ? 'production' : 'development';
console.log('NODE_ENV => ', process.env.NODE_ENV);
// In development mode serve the scripts using webpack-dev-middleware
if (process.env.NODE_ENV === 'development') {
var config = require('../../webpack.config');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
} else {
app.use('/dist', express.static('dist', {maxAge: '200d'}));
}
app.use('/assets', express.static('assets', {maxAge: '200d'}));
app.get("*", function(req, res) {
res.sendFile(__dirname + '/index.html');
})
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port);
}
})
| var express = require('express');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var yargs = require('yargs');
var args = yargs
.alias('p', 'production')
.argv;
process.env.NODE_ENV = args.production ? 'production' : 'development';
console.log('NODE_ENV => ', process.env.NODE_ENV);
var app = new express();
var port = 8000;
// In development mode serve the scripts using webpack-dev-middleware
if (process.env.NODE_ENV === 'development') {
var config = require('../../webpack.config');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
} else {
app.use('/dist', express.static('dist', {maxAge: '200d'}));
}
app.use('/assets', express.static('assets', {maxAge: '200d'}));
app.get("*", function(req, res) {
res.sendFile(__dirname + '/index.html');
})
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port);
}
})
|
Use clearfix instead of overflow | ;(function() {
var templates = {
form: '\
<form class="form-horizontal">{{fieldsets}}</form>\
',
fieldset: '\
<fieldset>\
{{legend}}\
{{fields}}\
</fieldset>\
',
field: '\
<div class="control-group">\
<label class="control-label" for="{{id}}">{{title}}</label>\
<div class="controls">\
<div class="input-xlarge">{{editor}}</div>\
<div class="help-block">{{help}}</div>\
</div>\
</div>\
',
simpleList: '\
<ul class="unstyled clearfix">{{items}}</ul>\
<button class="btn" style="margin-top: -10px" data-action="add">Add</div>\
',
simpleListItem: '\
<li class="clearfix" style="margin-bottom: 5px;">\
<div class="pull-left">{{editor}}</div>\
<button class="btn" style="margin-left: 4px" data-action="remove">x</button>\
</li>\
'
};
var classNames = {
error: 'error'
};
Backbone.Form.helpers.setTemplates(templates, classNames);
})();
| ;(function() {
var templates = {
form: '\
<form class="form-horizontal">{{fieldsets}}</form>\
',
fieldset: '\
<fieldset>\
{{legend}}\
{{fields}}\
</fieldset>\
',
field: '\
<div class="control-group">\
<label class="control-label" for="{{id}}">{{title}}</label>\
<div class="controls">\
<div class="input-xlarge">{{editor}}</div>\
<div class="help-block">{{help}}</div>\
</div>\
</div>\
',
simpleList: '\
<ul class="unstyled" style="overflow: hidden">{{items}}</ul>\
<button class="btn" data-action="add">Add</div>\
',
simpleListItem: '\
<li style="margin-bottom: 5px; overflow: hidden">\
<div class="pull-left">{{editor}}</div>\
<button class="btn" style="margin-left: 4px" data-action="remove">x</button>\
</li>\
'
};
var classNames = {
error: 'error'
};
Backbone.Form.helpers.setTemplates(templates, classNames);
})();
|
Support for testing through xip.io | import Resolver from 'resolver';
import routerMap from 'bibliaolvaso/router';
var App = Ember.Application.create({
//LOG_STACKTRACE_ON_DEPRECATION: true,
//LOG_BINDINGS: true,
LOG_TRANSITIONS: true,
//LOG_TRANSITIONS_INTERNAL: false,
LOG_VIEW_LOOKUPS: true,
LOG_ACTIVE_GENERATION: true,
modulePrefix: 'bibliaolvaso',
Resolver: Resolver
});
App.Router.map(routerMap);
App.Router.reopen({
location: 'history'
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: typeof DIST === 'undefined' ? 'http://' + location.hostname.replace('bibliaolvaso', 'bibliaolvaso-api') : 'http://api.bibliaolvaso.hu'
});
export default App;
| import Resolver from 'resolver';
import routerMap from 'bibliaolvaso/router';
var App = Ember.Application.create({
//LOG_STACKTRACE_ON_DEPRECATION: true,
//LOG_BINDINGS: true,
LOG_TRANSITIONS: true,
//LOG_TRANSITIONS_INTERNAL: false,
LOG_VIEW_LOOKUPS: true,
LOG_ACTIVE_GENERATION: true,
modulePrefix: 'bibliaolvaso',
Resolver: Resolver
});
App.Router.map(routerMap);
App.Router.reopen({
location: 'history'
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: typeof DIST === 'undefined' ? 'http://bibliaolvaso-api.dev' : 'http://api.bibliaolvaso.hu'
});
export default App;
|
Support for Ember 1.9's container API after `store:application` refactor. | /**
Configures a registry for use with an Ember-Data
store.
@method initializeStore
@param {Ember.ApplicationInstance} applicationOrRegistry
*/
export default function initializeStoreService(applicationOrRegistry) {
var registry, container;
if (applicationOrRegistry.registry && applicationOrRegistry.container) {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
registry = applicationOrRegistry.registry;
container = applicationOrRegistry.container;
} else {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registy. This
// case allows ED to support Ember pre 1.12
registry = applicationOrRegistry;
if (registry.container) { // Support Ember 1.10 - 1.11
container = registry.container();
} else { // Support Ember 1.9
container = registry;
}
}
// Eagerly generate the store so defaultStore is populated.
var store = container.lookup('store:application');
registry.register('service:store', store, { instantiate: false });
}
| /**
Configures a registry for use with an Ember-Data
store.
@method initializeStore
@param {Ember.ApplicationInstance} applicationOrRegistry
*/
export default function initializeStoreService(applicationOrRegistry) {
var registry, container;
if (applicationOrRegistry.registry && applicationOrRegistry.container) {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
registry = applicationOrRegistry.registry;
container = applicationOrRegistry.container;
} else {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registy. This
// case allows ED to support Ember pre 1.12
registry = applicationOrRegistry;
container = registry.container();
}
// Eagerly generate the store so defaultStore is populated.
var store = container.lookup('store:application');
registry.register('service:store', store, { instantiate: false });
}
|
Make IntComparator a bit more direct | // Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package utils
// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
// negative , if a < b
// zero , if a == b
// positive , if a > b
type Comparator func(a, b interface{}) int
// IntComparator provides a basic comparison on ints
func IntComparator(a, b interface{}) int {
return a.(int) - b.(int)
}
// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
s1 := a.(string)
s2 := b.(string)
min := len(s2)
if len(s1) < len(s2) {
min = len(s1)
}
diff := 0
for i := 0; i < min && diff == 0; i++ {
diff = int(s1[i]) - int(s2[i])
}
if diff == 0 {
diff = len(s1) - len(s2)
}
if diff < 0 {
return -1
}
if diff > 0 {
return 1
}
return 0
}
| // Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package utils
// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
// negative , if a < b
// zero , if a == b
// positive , if a > b
type Comparator func(a, b interface{}) int
// IntComparator provides a basic comparison on ints
func IntComparator(a, b interface{}) int {
aInt := a.(int)
bInt := b.(int)
switch {
case aInt > bInt:
return 1
case aInt < bInt:
return -1
default:
return 0
}
}
// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
s1 := a.(string)
s2 := b.(string)
min := len(s2)
if len(s1) < len(s2) {
min = len(s1)
}
diff := 0
for i := 0; i < min && diff == 0; i++ {
diff = int(s1[i]) - int(s2[i])
}
if diff == 0 {
diff = len(s1) - len(s2)
}
if diff < 0 {
return -1
}
if diff > 0 {
return 1
}
return 0
}
|
Fix error when unmuting a domain without listing muted domains first | import {
DOMAIN_BLOCKS_FETCH_SUCCESS,
DOMAIN_BLOCKS_EXPAND_SUCCESS,
DOMAIN_UNBLOCK_SUCCESS,
} from '../actions/domain_blocks';
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet } from 'immutable';
const initialState = ImmutableMap({
blocks: ImmutableMap({
items: ImmutableOrderedSet(),
}),
});
export default function domainLists(state = initialState, action) {
switch(action.type) {
case DOMAIN_BLOCKS_FETCH_SUCCESS:
return state.setIn(['blocks', 'items'], ImmutableOrderedSet(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_BLOCKS_EXPAND_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.union(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_UNBLOCK_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.delete(action.domain));
default:
return state;
}
};
| import {
DOMAIN_BLOCKS_FETCH_SUCCESS,
DOMAIN_BLOCKS_EXPAND_SUCCESS,
DOMAIN_UNBLOCK_SUCCESS,
} from '../actions/domain_blocks';
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet } from 'immutable';
const initialState = ImmutableMap({
blocks: ImmutableMap(),
});
export default function domainLists(state = initialState, action) {
switch(action.type) {
case DOMAIN_BLOCKS_FETCH_SUCCESS:
return state.setIn(['blocks', 'items'], ImmutableOrderedSet(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_BLOCKS_EXPAND_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.union(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_UNBLOCK_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.delete(action.domain));
default:
return state;
}
};
|
Add an error message for no user login found | /*
* Copyright 2015 Ryan Gilera.
*
* 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.github.daytron.revworks.data;
/**
* Collection of error messages.
*
* @author Ryan Gilera
*/
public enum ErrorMsg {
INVALID_INPUT_CAPTION("Invalid input!"),
SIGNIN_FAILED_CAPTION("Sign-In failed!"),
NO_USER_SIGNIN("No login user found. The session has been reset. ");
private final String text;
private ErrorMsg(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
| /*
* Copyright 2015 Ryan Gilera.
*
* 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.github.daytron.revworks.data;
/**
* Collection of error messages.
*
* @author Ryan Gilera
*/
public enum ErrorMsg {
INVALID_INPUT_CAPTION("Invalid input!"),
SIGNIN_FAILED_CAPTION("Sign-In failed!");
private final String text;
private ErrorMsg(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
|
Reshape transformers to 2D matrix | import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
| import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray: transformed = np.array(transformed)
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
|
Fix wrong properties type used | package protocolsupport.protocol.utils.spoofedata;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.function.Function;
import org.bukkit.Bukkit;
import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;
import com.google.gson.reflect.TypeToken;
import protocolsupport.api.utils.ProfileProperty;
import protocolsupport.utils.Utils;
public class PaperSpoofedDataParser implements Function<String, SpoofedData> {
protected static final Type properties_type = new TypeToken<Collection<ProfileProperty>>() {}.getType();
@Override
public SpoofedData apply(String hostname) {
if (PlayerHandshakeEvent.getHandlerList().getRegisteredListeners().length != 0) {
PlayerHandshakeEvent handshakeEvent = new PlayerHandshakeEvent(hostname, false);
Bukkit.getPluginManager().callEvent(handshakeEvent);
if (!handshakeEvent.isCancelled()) {
if (handshakeEvent.isFailed()) {
return new SpoofedData(handshakeEvent.getFailMessage());
}
return new SpoofedData(
handshakeEvent.getServerHostname(),
handshakeEvent.getSocketAddressHostname(),
handshakeEvent.getUniqueId(),
Utils.GSON.fromJson(handshakeEvent.getPropertiesJson(), properties_type)
);
}
}
return null;
}
}
| package protocolsupport.protocol.utils.spoofedata;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.function.Function;
import org.bukkit.Bukkit;
import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;
import com.destroystokyo.paper.profile.ProfileProperty;
import com.google.gson.reflect.TypeToken;
import protocolsupport.utils.Utils;
public class PaperSpoofedDataParser implements Function<String, SpoofedData> {
protected static final Type properties_type = new TypeToken<Collection<ProfileProperty>>() {}.getType();
@Override
public SpoofedData apply(String hostname) {
if (PlayerHandshakeEvent.getHandlerList().getRegisteredListeners().length != 0) {
PlayerHandshakeEvent handshakeEvent = new PlayerHandshakeEvent(hostname, false);
Bukkit.getPluginManager().callEvent(handshakeEvent);
if (!handshakeEvent.isCancelled()) {
if (handshakeEvent.isFailed()) {
return new SpoofedData(handshakeEvent.getFailMessage());
}
return new SpoofedData(
handshakeEvent.getServerHostname(),
handshakeEvent.getSocketAddressHostname(),
handshakeEvent.getUniqueId(),
Utils.GSON.fromJson(handshakeEvent.getPropertiesJson(), properties_type)
);
}
}
return null;
}
}
|
Fix capitalization in test path | import cdent.test
import cdent.parser.cdent.yaml
import cdent.parser.perl6
class TestPythonParser(cdent.test.TestCase):
def test_parse_perl6(self):
parser = cdent.parser.perl6.Parser()
# parser.debug = True
input = file('tests/modules/World.cd.pm6', 'r').read()
parser.open(input)
try:
ast = parser.parse()
except cdent.parser.ParseError, err:
print err
return
exit(1)
parser = cdent.parser.cdent.yaml.Parser()
input = file('tests/modules/world.cd.yaml', 'r').read()
parser.open(input)
expected = parser.parse()
self.assertEqual(ast.__class__.__name__, expected.__class__.__name__)
if __name__ == '__main__':
cdent.test.main()
| import cdent.test
import cdent.parser.cdent.yaml
import cdent.parser.perl6
class TestPythonParser(cdent.test.TestCase):
def test_parse_perl6(self):
parser = cdent.parser.perl6.Parser()
# parser.debug = True
input = file('tests/modules/world.cd.pm6', 'r').read()
parser.open(input)
try:
ast = parser.parse()
except cdent.parser.ParseError, err:
print err
return
exit(1)
parser = cdent.parser.cdent.yaml.Parser()
input = file('tests/modules/world.cd.yaml', 'r').read()
parser.open(input)
expected = parser.parse()
self.assertEqual(ast.__class__.__name__, expected.__class__.__name__)
if __name__ == '__main__':
cdent.test.main()
|
Add pimg.tw production url spec | var webdriverio = require('webdriverio'),
assert = require('assert');
describe('PIXNET 大首頁', () => {
it('標題應為品牌字', () => {
const title = browser.url('https://www.pixnet.net').getTitle()
assert.equal(title, '痞客邦 PIXNET')
})
it('焦點區塊圖片應正常顯示',function() {
var imgs = browser
.url('https://www.pixnet.net/')
.getElementSize('#feature-box-ul li img');
imgs.map(function (img) {
assert(590 === img.width);
assert(393 === img.height);
});
});
it('焦點區塊圖片網址應為 pimg.tw 正式網域',function() {
var imgUrls = browser
.url('https://www.pixnet.net/')
.getAttribute('#feature-box-ul li img', 'src');
imgUrls.map(function (url) {
assert(url.match(/pimg.tw\//));
});
});
}) | var webdriverio = require('webdriverio'),
assert = require('assert');
describe('PIXNET 大首頁', () => {
it('標題應為品牌字', () => {
const title = browser.url('https://www.pixnet.net').getTitle()
assert.equal(title, '痞客邦 PIXNET')
})
it('焦點區塊圖片應正常顯示',function() {
var imgs = browser
.url('https://www.pixnet.net/')
.getElementSize('#feature-box-ul li img');
imgs.map(function (img) {
assert(590 === img.width);
assert(393 === img.height);
});
});
}) |
Replace deprecated usage of 'DynamicRelationshipType' | /*
* Copyright 2015 Delft University of Technology
*
* 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 science.atlarge.graphalytics.neo4j;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.RelationshipType;
/**
* Helper class containing constants used throughout the Neo4j implementation.
*
* @author Tim Hegeman
*/
public final class Neo4jConfiguration {
public static final RelationshipType EDGE = RelationshipType.withName("EDGE");
public static final String ID_PROPERTY = "VID";
public enum VertexLabelEnum implements Label {
Vertex
}
/** Class contains only static values, so no instance required. */
private Neo4jConfiguration() { }
}
| /*
* Copyright 2015 Delft University of Technology
*
* 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 science.atlarge.graphalytics.neo4j;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.RelationshipType;
/**
* Helper class containing constants used throughout the Neo4j implementation.
*
* @author Tim Hegeman
*/
public final class Neo4jConfiguration {
public static final RelationshipType EDGE = DynamicRelationshipType.withName("EDGE");
public static final String ID_PROPERTY = "VID";
public enum VertexLabelEnum implements Label {
Vertex
}
/** Class contains only static values, so no instance required. */
private Neo4jConfiguration() { }
}
|
Comment out s3 settings. It was breaking admin static file serve | from project.settings_common import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# CACHE
from memcacheify import memcacheify
CACHES = memcacheify()
MIDDLEWARE_CLASSES += (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
# Google cloud for static files
STATIC_URL = 'http://commondatastorage.googleapis.com/lobbyingph/'
# AWS s3 for static files
#STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
#STATIC_URL = 'https://s3.amazonaws.com/lobbyingph/''
#AWS_ACCESS_KEY_ID = os.environ['AWS_KEY_ID']
#AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET']
#AWS_STORAGE_BUCKET_NAME = 'lobbyingph'
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')} | from project.settings_common import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# CACHE
from memcacheify import memcacheify
CACHES = memcacheify()
MIDDLEWARE_CLASSES += (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
#STATIC_URL = 'https://s3.amazonaws.com/lobbyingph/'
STATIC_URL = 'http://commondatastorage.googleapis.com/lobbyingph/'
AWS_ACCESS_KEY_ID = os.environ['AWS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET']
AWS_STORAGE_BUCKET_NAME = 'lobbyingph'
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')} |
Update the PyPI version to 0.2.25. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.25',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.24',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Fix wrong variable name in RecoverMiddleware | package middleware
import (
"net/http"
nextSkyerr "github.com/skygeario/skygear-server/pkg/core/skyerr"
"github.com/skygeario/skygear-server/pkg/server/skyerr"
)
// RecoverHandler provides an interface to handle recovered panic error
type RecoverHandler func(http.ResponseWriter, *http.Request, skyerr.Error)
// RecoverMiddleware recover from panic
type RecoverMiddleware struct {
RecoverHandler RecoverHandler
}
func (m RecoverMiddleware) Handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
err := nextSkyerr.ErrorFromRecoveringPanic(rec)
if m.RecoverHandler != nil {
m.RecoverHandler(w, r, err)
}
}
}()
next.ServeHTTP(w, r)
})
}
| package middleware
import (
"net/http"
nextSkyerr "github.com/skygeario/skygear-server/pkg/core/skyerr"
"github.com/skygeario/skygear-server/pkg/server/skyerr"
)
// RecoverHandler provides an interface to handle recovered panic error
type RecoverHandler func(http.ResponseWriter, *http.Request, skyerr.Error)
// RecoverMiddleware recover from panic
type RecoverMiddleware struct {
RecoverHandler RecoverHandler
}
func (m RecoverMiddleware) Handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); r != nil {
err := nextSkyerr.ErrorFromRecoveringPanic(rec)
if m.RecoverHandler != nil {
m.RecoverHandler(w, r, err)
}
}
}()
next.ServeHTTP(w, r)
})
}
|
Add stacklevel=2 to make calling code clear | """For backward compatibility, expose main functions from
``setuptools.config.setupcfg``
"""
import warnings
from functools import wraps
from textwrap import dedent
from typing import Callable, TypeVar, cast
from .._deprecation_warning import SetuptoolsDeprecationWarning
from . import setupcfg
Fn = TypeVar("Fn", bound=Callable)
__all__ = ('parse_configuration', 'read_configuration')
def _deprecation_notice(fn: Fn) -> Fn:
@wraps(fn)
def _wrapper(*args, **kwargs):
msg = f"""\
As setuptools moves its configuration towards `pyproject.toml`,
`{__name__}.{fn.__name__}` became deprecated.
For the time being, you can use the `{setupcfg.__name__}` module
to access a backward compatible API, but this module is provisional
and might be removed in the future.
"""
warnings.warn(dedent(msg), SetuptoolsDeprecationWarning, stacklevel=2)
return fn(*args, **kwargs)
return cast(Fn, _wrapper)
read_configuration = _deprecation_notice(setupcfg.read_configuration)
parse_configuration = _deprecation_notice(setupcfg.parse_configuration)
| """For backward compatibility, expose main functions from
``setuptools.config.setupcfg``
"""
import warnings
from functools import wraps
from textwrap import dedent
from typing import Callable, TypeVar, cast
from .._deprecation_warning import SetuptoolsDeprecationWarning
from . import setupcfg
Fn = TypeVar("Fn", bound=Callable)
__all__ = ('parse_configuration', 'read_configuration')
def _deprecation_notice(fn: Fn) -> Fn:
@wraps(fn)
def _wrapper(*args, **kwargs):
msg = f"""\
As setuptools moves its configuration towards `pyproject.toml`,
`{__name__}.{fn.__name__}` became deprecated.
For the time being, you can use the `{setupcfg.__name__}` module
to access a backward compatible API, but this module is provisional
and might be removed in the future.
"""
warnings.warn(dedent(msg), SetuptoolsDeprecationWarning)
return fn(*args, **kwargs)
return cast(Fn, _wrapper)
read_configuration = _deprecation_notice(setupcfg.read_configuration)
parse_configuration = _deprecation_notice(setupcfg.parse_configuration)
|
Allow Guests to view Articles | 'use strict';
// Setting up route
angular.module('articles').config(['$stateProvider',
function ($stateProvider) {
// Articles state routing
$stateProvider
.state('articles', {
abstract: true,
url: '/articles',
template: '<ui-view/>'
})
.state('articles.list', {
url: '',
templateUrl: 'modules/articles/views/list-articles.client.view.html'
})
.state('articles.create', {
url: '/create',
templateUrl: 'modules/articles/views/create-article.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('articles.view', {
url: '/:articleId',
templateUrl: 'modules/articles/views/view-article.client.view.html'
})
.state('articles.edit', {
url: '/:articleId/edit',
templateUrl: 'modules/articles/views/edit-article.client.view.html',
data: {
roles: ['user', 'admin']
}
});
}
]);
| 'use strict';
// Setting up route
angular.module('articles').config(['$stateProvider',
function ($stateProvider) {
// Articles state routing
$stateProvider
.state('articles', {
abstract: true,
url: '/articles',
template: '<ui-view/>',
data: {
roles: ['user', 'admin']
}
})
.state('articles.list', {
url: '',
templateUrl: 'modules/articles/views/list-articles.client.view.html'
})
.state('articles.create', {
url: '/create',
templateUrl: 'modules/articles/views/create-article.client.view.html'
})
.state('articles.view', {
url: '/:articleId',
templateUrl: 'modules/articles/views/view-article.client.view.html'
})
.state('articles.edit', {
url: '/:articleId/edit',
templateUrl: 'modules/articles/views/edit-article.client.view.html'
});
}
]);
|
Change from 408 to 503 since it is a server error | function wrap(res, fn) {
return function(...args) {
if (res.timedout) {
return res;
} else {
return fn.apply(res, args);
}
};
}
export default (timeoutValue) => {
return (req, res, next) => {
const {send, sendStatus, status} = res;
res.setTimeout(timeoutValue);
res.on('timeout', () => {
res.timedout = true;
if (!res.headersSent) {
res.statusCode = 503;
res.type('txt');
send.apply(res, ['Request Timeout']);
}
});
res.send = wrap(res, send);
res.sendStatus = wrap(res, sendStatus);
res.status = wrap(res, status);
next();
};
}
| function wrap(res, fn) {
return function(...args) {
if (res.timedout) {
return res;
} else {
return fn.apply(res, args);
}
};
}
export default (timeoutValue) => {
return (req, res, next) => {
const {send, sendStatus, status} = res;
res.setTimeout(timeoutValue);
res.on('timeout', () => {
res.timedout = true;
if (!res.headersSent) {
res.statusCode = 408;
res.type('txt');
send.apply(res, ['Request Timeout']);
}
});
res.send = wrap(res, send);
res.sendStatus = wrap(res, sendStatus);
res.status = wrap(res, status);
next();
};
} |
Make STORAGE_KEY work when using CookieStorage
Unfortunately PHP will convert **dot**s into underscore when parsing cookie names! So we have to remove dots in our `STORAKE_KEY`s so that is possible to use a CookieStorage.
[The full list of field-name characters that PHP converts to _](http://ca.php.net/manual/en/language.variables.external.php#81080)
[A random blog post](http://harrybailey.com/2009/04/dots-arent-allowed-in-php-cookie-names/) | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Currency\Context;
/**
* Interface to be implemented by the service providing the currently used
* currency.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface CurrencyContextInterface
{
// Key used to store the currency in storage.
const STORAGE_KEY = '_sylius_currency';
/**
* Get the default currency.
*
* @return string
*/
public function getDefaultCurrency();
/**
* Get the currently active currency.
*
* @return string
*/
public function getCurrency();
/**
* Set the currently active currency.
*
* @param string $currency
*/
public function setCurrency($currency);
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Currency\Context;
/**
* Interface to be implemented by the service providing the currently used
* currency.
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface CurrencyContextInterface
{
// Key used to store the currency in storage.
const STORAGE_KEY = '_sylius.currency';
/**
* Get the default currency.
*
* @return string
*/
public function getDefaultCurrency();
/**
* Get the currently active currency.
*
* @return string
*/
public function getCurrency();
/**
* Set the currently active currency.
*
* @param string $currency
*/
public function setCurrency($currency);
}
|
Check that posts exist before applying the resizeObserver | import $ from "jquery";
import Sugar from "../../sugar";
/**
* Handlers for scripted embed (social) quirks
*/
$(Sugar).bind("ready", function(){
const postsContainer = document.querySelector(".posts");
// Initialize twitter embeds when new posts load or previewed
$(Sugar).bind("postsloaded", function(event, posts) {
if (posts.length && window.twttr && window.twttr.widgets) {
window.twttr.widgets.load(posts[0].parentNode);
}
});
if (postsContainer) {
let scrollHeightCache = document.documentElement.scrollHeight;
let scrollYCache = window.scrollY;
const resizeObserver = new ResizeObserver(function (entries) {
entries.forEach(function () {
if (scrollYCache !== window.scrollY) {
// Chrome updates the scroll position, but not the scroll!
window.scrollTo(window.scrollX, window.scrollY);
} else if (document.documentElement.scrollHeight !== scrollHeightCache) {
const scrollYBy = document.documentElement.scrollHeight - scrollHeightCache;
window.scrollBy(0, scrollYBy);
}
scrollYCache = window.scrollY;
scrollHeightCache = document.documentElement.scrollHeight;
});
});
resizeObserver.observe(postsContainer);
}
});
| import $ from "jquery";
import Sugar from "../../sugar";
/**
* Handlers for scripted embed (social) quirks
*/
$(Sugar).bind("ready", function(){
// Initialize twitter embeds when new posts load or previewed
$(Sugar).bind("postsloaded", function(event, posts) {
if (posts.length && window.twttr && window.twttr.widgets) {
window.twttr.widgets.load(posts[0].parentNode);
}
});
var scrollHeightCache = document.documentElement.scrollHeight;
var scrollYCache = window.scrollY;
const resizeObserver = new ResizeObserver(function (entries) {
entries.forEach(function () {
if (scrollYCache !== window.scrollY) {
// Chrome updates the scroll position, but not the scroll!
window.scrollTo(window.scrollX, window.scrollY);
} else if (document.documentElement.scrollHeight !== scrollHeightCache) {
var scrollYBy = document.documentElement.scrollHeight - scrollHeightCache;
window.scrollBy(0, scrollYBy);
}
scrollYCache = window.scrollY;
scrollHeightCache = document.documentElement.scrollHeight;
});
});
resizeObserver.observe(document.querySelector(".posts"));
});
|
Change page size of discuss page from 3 to 6.
git-svn-id: e1a96f6b7015dfe5b5e86c875acd3ba0869cf04b@103 afa44554-0db9-64d6-dc80-ec3199b23f77 | <?php
# Directory where the Sprinkles code, and the caches, reside.
$sprinkles_dir = dirname(__FILE__);
# API root URL and caching directory
$api_root = 'http://api.getsatisfaction.com/';
$mysql_username = '';
$mysql_password = '';
# Configure this if you need to talk to a MySQL database on another machine
# or use a nonstandard port. The default should normally work.
# (FIXME: this doesn't apparently do anything.)
$mysql_connect_params = 'localhost:3306';
$max_logo_size = 65535;
# page limits
$submit_suggestions = 3;
$helpstart_topic_count = 5;
$discuss_topic_page_limit = 6;
$related_topics_count = 4;
$max_top_topic_tags = 5;
# $preview_after_log determines whether the user should have a chance to
# preview a topic for submission, after being sent to the Get Satisfaction
# authorization page and before actually posting the topic.
$preview_after_login = true;
?> | <?php
# Directory where the Sprinkles code, and the caches, reside.
$sprinkles_dir = dirname(__FILE__);
# API root URL and caching directory
$api_root = 'http://api.getsatisfaction.com/';
$mysql_username = '';
$mysql_password = '';
# Configure this if you need to talk to a MySQL database on another machine
# or use a nonstandard port. The default should normally work.
# (FIXME: this doesn't apparently do anything.)
$mysql_connect_params = 'localhost:3306';
$max_logo_size = 65535;
# page limits
$submit_suggestions = 3;
$helpstart_topic_count = 5;
$discuss_topic_page_limit = 3;
$related_topics_count = 4;
$max_top_topic_tags = 5;
# $preview_after_log determines whether the user should have a chance to
# preview a topic for submission, after being sent to the Get Satisfaction
# authorization page and before actually posting the topic.
$preview_after_login = true;
?> |
Call done() only if it has been supplied. |
function handle( req, res, done )
{
if( !req.flick ) {
return done ? done() : undefined;
}
var payload = req.flick.payload,
repository = payload.repository.owner.name + '/' + payload.repository.name,
index = 0,
self = this;
function next( err )
{
var handler = self.stack[ index++ ];
if( !handler || err ) {
return done( err );
}
if( !~[ '*', repository ].indexOf( handler.repository ) ) {
return next();
}
handler.handle( req, res, next );
}
next();
}
exports.handle = handle;
function use( repository, fn )
{
if( !fn ) {
fn = repository;
repository = '*';
}
this.stack.push( {
repository: repository,
handle: fn
} );
}
exports.use = use;
|
function handle( req, res, done )
{
if( !req.flick ) {
return done();
}
var payload = req.flick.payload,
repository = payload.repository.owner.name + '/' + payload.repository.name,
index = 0,
self = this;
function next( err )
{
var handler = self.stack[ index++ ];
if( !handler || err ) {
return done( err );
}
if( !~[ '*', repository ].indexOf( handler.repository ) ) {
return next();
}
handler.handle( req, res, next );
}
next();
}
exports.handle = handle;
function use( repository, fn )
{
if( !fn ) {
fn = repository;
repository = '*';
}
this.stack.push( {
repository: repository,
handle: fn
} );
}
exports.use = use;
|
Check that scenarios works with xhr | // @TODO Test Server's config
import test from 'tape';
import { Database, Router, Server } from '../../src';
const xhrRequest = (url) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
}
export const serverSpec = () => {
test('Server # use database', (assert) => {
assert.plan(2);
const myDB = new Database();
const router = new Router();
const server = new Server();
router.get('/posts', (request, db) => {
assert.ok(db == myDB, 'The passed db is the correct one');
});
server.use(myDB);
server.use(router);
fetch('/posts');
xhrRequest('/posts');
});
test('Server # use router', (assert) => {
const router = new Router();
const server = new Server();
router.get('/comments', _ => {
assert.fail('Should not reach this handler since the request is fired before "server.use"');
});
router.get('/users', _ => {
assert.ok(true, 'It must only enter in this handler since the request has been triggered after the registration');
assert.end();
});
fetch('/comments');
server.use(router);
fetch('/users');
});
};
| import test from 'tape';
import { Database, Router, Server } from '../../src';
//
// TODO: Check the same with XHR
//
export const serverSpec = () => {
// @TODO Test Server's config
test('Server # use database', (assert) => {
const myDB = new Database();
const router = new Router();
const server = new Server();
router.get('/posts', (request, db) => {
assert.ok(db == myDB, 'The passed db is the correct one');
assert.end();
});
server.use(myDB);
server.use(router);
fetch('/posts');
});
test('Server # use router', (assert) => {
const router = new Router();
const server = new Server();
router.get('/comments', _ => {
assert.fail('Should not reach this handler since the request is fired before "server.use"');
});
router.get('/users', _ => {
assert.ok(true, 'It must only enter in this handler since the request has been triggered after the registration');
assert.end();
});
fetch('/comments');
server.use(router);
fetch('/users');
});
};
|
Add test for finalize method. | #! /usr/bin/env python
import os
import pytest
from pymt import models
@pytest.mark.parametrize("cls", models.__all__)
def test_model_setup(cls):
model = models.__dict__[cls]()
args = model.setup()
assert os.path.isfile(os.path.join(args[1], args[0]))
@pytest.mark.parametrize("cls", models.__all__)
def test_model_initialize(cls):
model = models.__dict__[cls]()
args = model.setup()
model.initialize(*args)
assert model.initdir == args[1]
assert model._initialized
@pytest.mark.parametrize("cls", models.__all__)
def test_model_update(cls):
model = models.__dict__[cls]()
model.initialize(*model.setup())
model.update()
assert model.get_current_time() > model.get_start_time()
@pytest.mark.parametrize("cls", models.__all__)
def test_model_finalize(cls):
model = models.__dict__[cls]()
model.initialize(*model.setup())
model.finalize()
| #! /usr/bin/env python
import os
import pytest
from pymt import models
@pytest.mark.parametrize("cls", models.__all__)
def test_model_setup(cls):
model = models.__dict__[cls]()
args = model.setup()
assert os.path.isfile(os.path.join(args[1], args[0]))
@pytest.mark.parametrize("cls", models.__all__)
def test_model_initialize(cls):
model = models.__dict__[cls]()
args = model.setup()
model.initialize(*args)
assert model.initdir == args[1]
assert model._initialized
@pytest.mark.parametrize("cls", models.__all__)
def test_model_irf(cls):
model = models.__dict__[cls]()
model.initialize(*model.setup())
model.update()
assert model.get_current_time() > model.get_start_time()
model.finalize()
|
Fix scheduled import option syntax
Confirmed that this is the correct syntax. Otherwise, it complains
about the command not being found. | <?php
namespace App\Console\Commands\Import;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class ImportScheduleDaily extends BaseCommand
{
protected $signature = 'import:daily';
protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';
public function handle()
{
$this->call('import:collections');
$this->call('import:collections-delete');
$this->call('import:events-ticketed-full', ['--yes' => 'default']);
$this->call('import:mobile');
$this->call('import:products-full', ['--yes' => 'default']);
$this->call('import:web');
$this->call('import:digital-labels');
// EventOccurrence is not included in import:web to avoid duplication
$this->call('import:web-full', [
'--yes' => 'default',
'endpoint' => 'events/occurrences'
]);
}
}
| <?php
namespace App\Console\Commands\Import;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class ImportScheduleDaily extends BaseCommand
{
protected $signature = 'import:daily';
protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';
public function handle()
{
$this->call('import:collections');
$this->call('import:collections-delete');
$this->call('import:events-ticketed-full', ['--yes' => 'default']);
$this->call('import:mobile');
$this->call('import:products-full --yes');
$this->call('import:web');
$this->call('import:digital-labels');
// EventOccurrence is not included in import:web to avoid duplication
$this->call('import:web-full events/occurrences --yes');
}
}
|
Add "passwordinput" to class_converter, because it needs the textInput class too. | from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload",
"passwordinput":"passwordinput textInput"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
| from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
|
Add @DoNotInstrument to Flac extension test
PiperOrigin-RevId: 370739641 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.ext.flac;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.DefaultRenderersFactoryAsserts;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.internal.DoNotInstrument;
/** Unit test for {@link DefaultRenderersFactoryTest} with {@link LibflacAudioRenderer}. */
@RunWith(AndroidJUnit4.class)
@DoNotInstrument
public final class DefaultRenderersFactoryTest {
@Test
public void createRenderers_instantiatesFlacRenderer() {
DefaultRenderersFactoryAsserts.assertExtensionRendererCreated(
LibflacAudioRenderer.class, C.TRACK_TYPE_AUDIO);
}
}
| /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.ext.flac;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.DefaultRenderersFactoryAsserts;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Unit test for {@link DefaultRenderersFactoryTest} with {@link LibflacAudioRenderer}. */
@RunWith(AndroidJUnit4.class)
public final class DefaultRenderersFactoryTest {
@Test
public void createRenderers_instantiatesFlacRenderer() {
DefaultRenderersFactoryAsserts.assertExtensionRendererCreated(
LibflacAudioRenderer.class, C.TRACK_TYPE_AUDIO);
}
}
|
[FEATURE] Add tax percent to stripe subscriptions | <?php
/**
* Stripe Create Subscription Request.
*/
namespace Omnipay\Stripe\Message;
/**
* Stripe Create Subscription Request
*
* @see Omnipay\Stripe\Gateway
* @link https://stripe.com/docs/api/php#create_subscription
*/
class CreateSubscriptionRequest extends AbstractRequest
{
/**
* Get the plan ID
*
* @return string
*/
public function getPlan()
{
return $this->getParameter('plan');
}
/**
* Set the plan ID
*
* @return CreateSubscriptionRequest provides a fluent interface.
*/
public function setPlan($value)
{
return $this->setParameter('plan', $value);
}
public function getData()
{
$this->validate('customerReference', 'plan');
$data = array(
'plan' => $this->getPlan()
);
if (isset($this->parameters->has('tax_percent'))) {
$data['tax_percent'] = (float)$this->getParameter('tax_percent');
}
return $data;
}
public function getEndpoint()
{
return $this->endpoint.'/customers/'.$this->getCustomerReference().'/subscriptions';
}
}
| <?php
/**
* Stripe Create Subscription Request.
*/
namespace Omnipay\Stripe\Message;
/**
* Stripe Create Subscription Request
*
* @see Omnipay\Stripe\Gateway
* @link https://stripe.com/docs/api/php#create_subscription
*/
class CreateSubscriptionRequest extends AbstractRequest
{
/**
* Get the plan ID
*
* @return string
*/
public function getPlan()
{
return $this->getParameter('plan');
}
/**
* Set the plan ID
*
* @return CreateSubscriptionRequest provides a fluent interface.
*/
public function setPlan($value)
{
return $this->setParameter('plan', $value);
}
public function getData()
{
$this->validate('customerReference', 'plan');
$data = array(
'plan' => $this->getPlan()
);
return $data;
}
public function getEndpoint()
{
return $this->endpoint.'/customers/'.$this->getCustomerReference().'/subscriptions';
}
}
|
Update tracker store test for 0.7.5 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from rasa_core.channels import UserMessage
from rasa_core.domain import TemplateDomain
from rasa_core.events import SlotSet
from rasa_core.tracker_store import InMemoryTrackerStore
domain = TemplateDomain.load("data/test_domains/default_with_topic.yml")
def test_get_or_create():
slot_key = 'location'
slot_val = 'Easter Island'
store = InMemoryTrackerStore(domain)
tracker = store.get_or_create_tracker(UserMessage.DEFAULT_SENDER_ID)
ev = SlotSet(slot_key, slot_val)
tracker.update(ev)
assert tracker.get_slot(slot_key) == slot_val
store.save(tracker)
again = store.get_or_create_tracker(UserMessage.DEFAULT_SENDER_ID)
assert again.get_slot(slot_key) == slot_val
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from rasa_core.channels import UserMessage
from rasa_core.domain import TemplateDomain
from rasa_core.events import SlotSet
from rasa_core.tracker_store import InMemoryTrackerStore
domain = TemplateDomain.load("data/test_domains/default_with_topic.yml")
def test_get_or_create():
slot_key = 'location'
slot_val = 'Easter Island'
store = InMemoryTrackerStore(domain)
tracker = store.get_or_create_tracker(UserMessage.DEFAULT_SENDER)
ev = SlotSet(slot_key, slot_val)
tracker.update(ev)
assert tracker.get_slot(slot_key) == slot_val
store.save(tracker)
again = store.get_or_create_tracker(UserMessage.DEFAULT_SENDER)
assert again.get_slot(slot_key) == slot_val
|
Remove redundant service declaration in exeengine services | package org.gemoc.gemoc_language_workbench.api.core;
import java.util.Set;
import org.gemoc.execution.engine.trace.gemoc_execution_trace.LogicalStep;
import org.gemoc.gemoc_language_workbench.api.core.EngineStatus.RunStatus;
import org.gemoc.gemoc_language_workbench.api.engine_addon.IEngineAddon;
public interface IExecutionEngine extends IBasicExecutionEngine{
public abstract IExecutionContext getExecutionContext();
public abstract EngineStatus getEngineStatus();
public abstract RunStatus getRunningStatus();
public abstract void notifyEngineAboutToStart();
public abstract void notifyEngineStarted();
public abstract void notifyAboutToStop();
public abstract void notifyEngineStopped();
public abstract void notifyEngineAboutToDispose();
public abstract void notifyAboutToExecuteLogicalStep(LogicalStep l);
public abstract void notifyLogicalStepExecuted(LogicalStep l);
public abstract <T extends IEngineAddon> boolean hasAddon(Class<T> type);
public abstract <T extends IEngineAddon> T getAddon(Class<T> type);
public abstract void setEngineStatus(RunStatus stopped);
} | package org.gemoc.gemoc_language_workbench.api.core;
import java.util.Set;
import org.gemoc.execution.engine.trace.gemoc_execution_trace.LogicalStep;
import org.gemoc.gemoc_language_workbench.api.core.EngineStatus.RunStatus;
import org.gemoc.gemoc_language_workbench.api.engine_addon.IEngineAddon;
public interface IExecutionEngine extends IBasicExecutionEngine{
public abstract IExecutionContext getExecutionContext();
public abstract EngineStatus getEngineStatus();
public abstract RunStatus getRunningStatus();
public abstract void notifyEngineAboutToStart();
public abstract void notifyEngineStarted();
public abstract void notifyAboutToStop();
public abstract void notifyEngineStopped();
public abstract void notifyEngineAboutToDispose();
public abstract void notifyAboutToExecuteLogicalStep(LogicalStep l);
public abstract void notifyLogicalStepExecuted(LogicalStep l);
public abstract <T extends IEngineAddon> boolean hasAddon(Class<T> type);
public abstract <T extends IEngineAddon> T getAddon(Class<T> type);
public abstract <T extends IEngineAddon> Set<T> getAddonsTypedBy(Class<T> type);
public abstract void setEngineStatus(RunStatus stopped);
} |
Use inner data array of response | var app = angular.module('plugD', [
'angularUtils.directives.dirPagination'
]);
app.controller("PluginController",function(){
});
app.directive("pluginList", ['$http',function($http){
return {
restrict:"E",
templateUrl:"partials/plugin-list.html",
controller: function($http){
var self = this;
self.filter = {gmod:"", term:"", perPage:5};
self.sortKey = "name";
self.order ='+';
$http.get('api/plugins.json')
.then(function(data){
self.plugins = data:data;
}, function(data){
// todo: error
});
},
controllerAs:"plug"
}
}]);
| var app = angular.module('plugD', [
'angularUtils.directives.dirPagination'
]);
app.controller("PluginController",function(){
});
app.directive("pluginList", ['$http',function($http){
return {
restrict:"E",
templateUrl:"partials/plugin-list.html",
controller: function($http){
var self = this;
self.filter = {gmod:"", term:"", perPage:5};
self.sortKey = "name";
self.order ='+';
$http.get('api/plugins.json')
.then(function(data){
self.plugins = data;
}, function(data){
// todo: error
});
},
controllerAs:"plug"
}
}]);
|
Fix bug with not calling verify | var venmo = Venmo(1424);
function signin() {
if (venmo.isAuthorized()) {
$('#signin').addClass('is-hidden');
picture();
}
$('.signin-button').click(function () {
venmo.authorize();
});
}
function picture() {
$('#picture').removeClass('is-hidden');
$('.signin-submit').click(function () {
$.ajax({
url: '/upload',
data: new FormData($('#image-upload')[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (receipt) {
$('#picture').addClass('is-hidden');
verify(receipt.items);
}
});
});
}
function verify(receipt) {
$('#verify').removeClass('is-hidden');
}
signin(); | var venmo = Venmo(1424);
function signin() {
if (venmo.isAuthorized()) {
$('#signin').addClass('is-hidden');
picture();
}
$('.signin-button').click(function () {
venmo.authorize();
});
}
function picture() {
$('#picture').removeClass('is-hidden');
$('.signin-submit').click(function () {
$.ajax({
url: '/upload',
data: new FormData($('#image-upload')[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (receipt) {
$('#picture').addClass('is-hidden');
}
});
});
}
function verify(receipt) {
$('#verify').removeClass('is-hidden');
console.log(receipt);
}
signin(); |
Fix missing translations in ballot form | from colander import Length
from deform.widget import Select2Widget, TextAreaWidget
from ekklesia_common.contract import Form, Schema, int_property, json_property, string_property
from ekklesia_common.translation import _
class BallotSchema(Schema):
name = string_property(title=_('name'), validator=Length(min=2, max=23), missing='')
election = int_property(title=_('election_positions'), missing=0)
result = json_property(title=_('voting_result'), missing={})
area_id = int_property(title=_('subject_area'), missing=None)
voting_id = int_property(title=_('voting_phase'), missing=None)
proposition_type_id = int_property(title=_('proposition_type'), missing=None)
class BallotForm(Form):
def __init__(self, request, action):
super().__init__(BallotSchema(), request, action, buttons=("submit", ))
def prepare_for_render(self, items_for_selects):
widgets = {
'result': TextAreaWidget(rows=4),
'area_id': Select2Widget(values=items_for_selects['area']),
'voting_id': Select2Widget(values=items_for_selects['voting']),
'proposition_type_id': Select2Widget(values=items_for_selects['proposition_type'])
}
self.set_widgets(widgets)
| from colander import Length
from deform.widget import Select2Widget, TextAreaWidget
from ekklesia_common.contract import Form, Schema, int_property, json_property, string_property
from ekklesia_common.translation import _
class BallotSchema(Schema):
name = string_property(title=_('name'), validator=Length(min=2, max=23), missing='')
election = int_property(title=_('election_positions'), missing=0)
result = json_property(title=_('voting_result'), missing={})
area_id = int_property(title=_('subject_area'), missing=None)
voting_id = int_property(title=('voting_phase'), missing=None)
proposition_type_id = int_property(title=('proposition_type'), missing=None)
class BallotForm(Form):
def __init__(self, request, action):
super().__init__(BallotSchema(), request, action, buttons=("submit", ))
def prepare_for_render(self, items_for_selects):
widgets = {
'result': TextAreaWidget(rows=4),
'area_id': Select2Widget(values=items_for_selects['area']),
'voting_id': Select2Widget(values=items_for_selects['voting']),
'proposition_type_id': Select2Widget(values=items_for_selects['proposition_type'])
}
self.set_widgets(widgets)
|
Make lift manual control 75% speed | 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() {
double input = squareInput(Robot.oi.operatorPad.getRightY()) * 0.75;
Robot.lift.manualControl(-input);
}
// Square the value of the input while preserving its sign
private double squareInput(double input) {
boolean negative = input < 0;
input = input * input;
if (negative) {
input = -input;
}
return input;
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
// This is the Lift's default command.
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() {
double input = squareInput(Robot.oi.operatorPad.getRightY());
Robot.lift.manualControl(-input);
}
// Square the value of the input while preserving its sign
private double squareInput(double input) {
boolean negative = input < 0;
input = input * input;
if (negative) {
input = -input;
}
return input;
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
// This is the Lift's default command.
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() {
}
}
|
FIx the typo of showMonthlyIncomesAmount | import { get } from 'lodash';
import { calculateCurrentEvents } from '../../lib/events';
import { getEbudgie } from './ebudgie';
export const showMonthlyIncomesAmount = async (page_scoped_id, reply) => {
try {
const ebudgie = await getEbudgie(page_scoped_id, reply);
if (!ebudgie) {
return;
}
const incomes = get(ebudgie, 'incomes', []);
const currency = get(ebudgie, 'currency', '$');
const amount = calculateCurrentEvents(incomes);
await reply({
text: `Your current salary is: ${amount}${currency}`
});
} catch (e) {
console.log('Error during showing salary', e);
await reply({
text: 'Something went wrong. Please try again.'
});
}
};
| import { get } from 'lodash';
import { calculateCurrentEvents } from '../../lib/events';
import { getEbudgie } from './ebudgie';
export const showMontlyIncomesAmount = async (page_scoped_id, reply) => {
try {
const ebudgie = await getEbudgie(page_scoped_id, reply);
if (!ebudgie) {
return;
}
const incomes = get(ebudgie, 'incomes', []);
const currency = get(ebudgie, 'currency', '$');
const amount = calculateCurrentEvents(incomes);
await reply({
text: `Your current salary is: ${amount}${currency}`
});
} catch (e) {
console.log('Error during showing salary', e);
await reply({
text: 'Something went wrong. Please try again.'
});
}
};
|
Revert removal of host information in Heartbeat.
Effectively, the host for all heartbeats was the empty string. There is
a strong possibility this caused errors when initializing a
blockchain. | package swarm
import (
"common"
"encoding/json"
)
type Heartbeat struct {
Id string
Blockchain string
Host string
ParentBlock string
EntropyStage1 string
EntropyStage2 string
FileProofStage1 string
FileProofStage2 string
}
func NewHeartbeat(prevState *Block, Host, Stage1, Stage2 string) (h *Heartbeat) {
h = new(Heartbeat)
h.Blockchain = prevState.SwarmId()
h.Host = Host
h.EntropyStage1 = Stage1
h.EntropyStage2 = Stage2
h.Id, _ = common.RandomString(8)
h.ParentBlock = prevState.Id
return
}
func (h *Heartbeat) SwarmId() string {
return h.Blockchain
}
func (h *Heartbeat) UpdateId() string {
return h.Id
}
func (h *Heartbeat) Type() string {
return "Heartbeat"
}
func (h *Heartbeat) MarshalString() string {
w, err := json.Marshal(h)
if err != nil {
panic("Unable to marshal HeartBeatTransaction, this should not happen" + err.Error())
}
return string(w)
}
func (h *Heartbeat) GetStage2() string {
return h.EntropyStage2
}
func VerifyHeartBeat(prevBlock *Block, h *Heartbeat) {
// Just return true for now
// DANGEROUS
return
}
| package swarm
import (
"common"
"encoding/json"
)
type Heartbeat struct {
Id string
Blockchain string
Host string
ParentBlock string
EntropyStage1 string
EntropyStage2 string
FileProofStage1 string
FileProofStage2 string
}
func NewHeartbeat(prevState *Block, Host, Stage1, Stage2 string) (h *Heartbeat) {
h = new(Heartbeat)
h.Blockchain = prevState.SwarmId()
h.EntropyStage1 = Stage1
h.EntropyStage2 = Stage2
h.Id, _ = common.RandomString(8)
h.ParentBlock = prevState.Id
return
}
func (h *Heartbeat) SwarmId() string {
return h.Blockchain
}
func (h *Heartbeat) UpdateId() string {
return h.Id
}
func (h *Heartbeat) Type() string {
return "Heartbeat"
}
func (h *Heartbeat) MarshalString() string {
w, err := json.Marshal(h)
if err != nil {
panic("Unable to marshal HeartBeatTransaction, this should not happen" + err.Error())
}
return string(w)
}
func (h *Heartbeat) GetStage2() string {
return h.EntropyStage2
}
func VerifyHeartBeat(prevBlock *Block, h *Heartbeat) {
// Just return true for now
// DANGEROUS
return
}
|
Print more explicit error reports for input file parsing | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except ValueError as e:
sys.exit('ValueError in {}: {}'.format(inFn, e))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
| #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
|
Fix referring to wrong base | import base from './base'
import get from 'lodash/get'
import isFunction from 'lodash/isFunction'
// TODO: Allow pass object as parameter
/**
* A simple module to quickly convert nodejs module to Magnet module
* @param {[function, object]} module Module to be converted
* @param {string} options.namespace Namespace to occupy, same for app[namespace], config[namespace]
* @param {string} options.initializer Initialize function
* @param {[array, function]} options.params Will pass to initializer
* @return void
*/
export default function convert (module, { namespace, initializer, params }) {
return class MagnetModule extends base {
async setup () {
const config = this.app.config[namespace]
let moduleParams = []
if (isFunction(params)) {
moduleParams = [params(config)]
} else if (Array.isArray(params)) {
for (const param of params) {
if (param.startsWith('config.')) {
const configKey = param.replace('config.', '')
moduleParams.push(get(config, configKey))
}
}
} else {
this.log.warn('Params is not recognized')
}
const initialize = module[initializer] || module
this.app[namespace] = initialize(...moduleParams)
}
}
}
| import base from 'magnet-core/dist/base'
import get from 'lodash/get'
import isFunction from 'lodash/isFunction'
// TODO: Allow pass object as parameter
/**
* A simple module to quickly convert nodejs module to Magnet module
* @param {[function, object]} module Module to be converted
* @param {string} options.namespace Namespace to occupy, same for app[namespace], config[namespace]
* @param {string} options.initializer Initialize function
* @param {[array, function]} options.params Will pass to initializer
* @return void
*/
export default function convert (module, { namespace, initializer, params }) {
return class MagnetModule extends base {
async setup () {
const config = this.app.config[namespace]
let moduleParams = []
if (isFunction(params)) {
moduleParams = [params(config)]
} else if (Array.isArray(params)) {
for (const param of params) {
if (param.startsWith('config.')) {
const configKey = param.replace('config.', '')
moduleParams.push(get(config, configKey))
}
}
} else {
this.log.warn('Params is not recognized')
}
const initialize = module[initializer] || module
this.app[namespace] = initialize(...moduleParams)
}
}
}
|
Fix spelling error in module | const Tweet = require('../models/tweet')
const controllerUtils = require('./controller-utils')
const specificTweetsController = function (req, res) {
if (!req.params.name) {
res.status(400).send('Invalid trend name')
return
}
let query
if (!req.query.max_id) {
query = {trend: req.params.name}
} else {
// If max_id is provided, ensure that it is valid
if(!controllerUtils.isNumeric(req.query.max_id)) {
res.status(400).send('Invalid max_id parameter')
return
}
options = {trend: req.params.name, _id: {$gt: res.query.max_id}}
}
Tweet.find(query, (err, tweets) => {
if (err) {
res.status(500).send('Internal error while retreiving tweets')
} else {
res.type('application/json')
res.send(tweets)
}
})
}
module.exports = specificTweetsController
| const Tweet = require('../models/tweet')
const controllerUtils = require('./controllerUtils')
const specificTweetsController = function (req, res) {
if (!req.params.name) {
res.status(400).send('Invalid trend name')
return
}
let query
if (!req.query.max_id) {
query = {trend: req.params.name}
} else {
// If max_id is provided, ensure that it is valid
if(!controllerUtils.isNumeric(req.query.max_id)) {
res.status(400).send('Invalid max_id parameter')
return
}
options = {trend: req.params.name, _id: {$gt: res.query.max_id}}
}
Tweet.find(query, (err, tweets) => {
if (err) {
res.status(500).send('Internal error while retreiving tweets')
} else {
res.type('application/json')
res.send(tweets)
}
})
}
module.exports = specificTweetsController
|
Make nose and sphinx optional dependencies. | from setuptools import setup, find_packages
setup(name='dcmstack',
description='Stack DICOM images into volumes',
version='0.6.dev',
author='Brendan Moloney',
author_email='moloney@ohsu.edu',
packages=find_packages('src'),
package_dir = {'':'src'},
install_requires=['pydicom >= 0.9.7',
'nibabel',
],
extras_require = {
'doc': ["sphinx"],
'test': ["nose"],
},
entry_points = {'console_scripts' : \
['dcmstack = dcmstack.dcmstack_cli:main',
'nitool = dcmstack.nitool_cli:main',
],
},
test_suite = 'nose.collector'
)
| from setuptools import setup, find_packages
setup(name='dcmstack',
description='Stack DICOM images into volumes',
version='0.6.dev',
author='Brendan Moloney',
author_email='moloney@ohsu.edu',
packages=find_packages('src'),
package_dir = {'':'src'},
install_requires=['pydicom >= 0.9.7',
'nibabel',
'nose',
],
entry_points = {'console_scripts' : \
['dcmstack = dcmstack.dcmstack_cli:main',
'nitool = dcmstack.nitool_cli:main',
],
},
test_suite = 'nose.collector'
)
|
:rocket: Change Vaccine was_applied widget to RadioSelect | import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
class AdmissionNoteForm(forms.ModelForm):
class Meta:
model = AdmissionNote
fields = [
'id_gal_origin',
]
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = [
'name',
]
class FluVaccineForm(forms.ModelForm):
class Meta:
model = FluVaccine
fields = [
'was_applied',
]
widgets = {
'was_applied': forms.RadioSelect(
choices=(
(True, "Sim"), (False, "Não"), (None, "Ignorado"),
),
),
}
| import datetime #for checking renewal date range.
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import (Patient, AdmissionNote, FluVaccine,
CollectionType, CollectedSample,
Symptom, ObservedSymptom,
)
class AdmissionNoteForm(forms.ModelForm):
class Meta:
model = AdmissionNote
fields = [
'id_gal_origin',
]
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = [
'name',
]
class FluVaccineForm(forms.ModelForm):
class Meta:
model = FluVaccine
fields = [
'was_applied',
]
|
Fix empty message case in integration test. | package cloudwatch
import (
"math/rand"
"testing"
"time"
"github.com/Pallinder/go-randomdata"
"github.com/gliderlabs/logspout/router"
)
const NumMessages = 250000
func TestCloudWatchAdapter(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode.")
}
route := &router.Route{Address: "logspout-cloudwatch"}
messages := make(chan *router.Message)
adapter, err := NewAdapter(route)
if err != nil {
t.Error(err)
return
}
go adapter.Stream(messages)
for i := 0; i < NumMessages; i++ {
messages <- createMessage()
}
close(messages)
}
func createMessage() *router.Message {
data := ""
timestamp := time.Now()
random := rand.Intn(100)
if random != 0 {
data = randomdata.Paragraph()
}
return &router.Message{Data: data, Time: timestamp}
}
| package cloudwatch
import (
"math/rand"
"testing"
"time"
"github.com/Pallinder/go-randomdata"
"github.com/gliderlabs/logspout/router"
)
const NumMessages = 25000000
func TestCloudWatchAdapter(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode.")
}
route := &router.Route{Address: "logspout-cloudwatch"}
messages := make(chan *router.Message)
adapter, err := NewAdapter(route)
if err != nil {
t.Error(err)
return
}
go adapter.Stream(messages)
for i := 0; i < NumMessages; i++ {
messages <- createMessage()
}
close(messages)
}
func createMessage() *router.Message {
data := ""
timestamp := time.Now()
random := rand.Intn(100)
if random == 0 {
data = randomdata.Paragraph()
}
return &router.Message{Data: data, Time: timestamp}
}
|
Remove typ filter from dashboard | import django_filters
from django.utils.translation import ugettext_lazy as _
from adhocracy4.filters import widgets as filters_widgets
from adhocracy4.filters.filters import DefaultsFilterSet
from adhocracy4.filters.filters import FreeTextFilter
from adhocracy4.projects.models import Project
from meinberlin.apps.projects import views
class FreeTextFilterWidget(filters_widgets.FreeTextFilterWidget):
label = _('Search')
class DashboardProjectFilterSet(DefaultsFilterSet):
defaults = {
'is_archived': 'false'
}
ordering = django_filters.OrderingFilter(
choices=(
('-created', _('Most recent')),
),
empty_label=None,
widget=views.OrderingWidget,
)
search = FreeTextFilter(
widget=FreeTextFilterWidget,
fields=['name']
)
is_archived = django_filters.BooleanFilter(
widget=views.ArchivedWidget
)
created = django_filters.NumberFilter(
name='created',
lookup_expr='year',
widget=views.YearWidget,
)
class Meta:
model = Project
fields = ['search', 'is_archived', 'created']
| import django_filters
from django.utils.translation import ugettext_lazy as _
from adhocracy4.filters import widgets as filters_widgets
from adhocracy4.filters.filters import DefaultsFilterSet
from adhocracy4.filters.filters import FreeTextFilter
from adhocracy4.projects.models import Project
from meinberlin.apps.projects import views
class FreeTextFilterWidget(filters_widgets.FreeTextFilterWidget):
label = _('Search')
class DashboardProjectFilterSet(DefaultsFilterSet):
defaults = {
'is_archived': 'false'
}
ordering = django_filters.OrderingFilter(
choices=(
('-created', _('Most recent')),
),
empty_label=None,
widget=views.OrderingWidget,
)
search = FreeTextFilter(
widget=FreeTextFilterWidget,
fields=['name']
)
is_archived = django_filters.BooleanFilter(
widget=views.ArchivedWidget
)
created = django_filters.NumberFilter(
name='created',
lookup_expr='year',
widget=views.YearWidget,
)
typ = django_filters.CharFilter(
widget=views.TypeWidget,
)
class Meta:
model = Project
fields = ['search', 'is_archived', 'created', 'typ']
|
Update the PyPI version to 8.1.0. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='8.1.0',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='8.0.2',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Remove dependency_links as it seems to be ignored.
I also added ppp_datamodel to Pypi so it is not needed anymore. | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_core',
version='0.1',
description='Core/router of the PPP framework',
url='https://github.com/ProjetPP/PPP-Core',
author='Valentin Lorentz',
author_email='valentin.lorentz+ppp@ens-lyon.org',
license='MIT',
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Development Status :: 1 - Planning',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
],
install_requires=[
'requests',
'ppp_datamodel',
],
packages=[
'ppp_core',
],
)
| #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_core',
version='0.1',
description='Core/router of the PPP framework',
url='https://github.com/ProjetPP/PPP-Core',
author='Valentin Lorentz',
author_email='valentin.lorentz+ppp@ens-lyon.org',
license='MIT',
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Development Status :: 1 - Planning',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
],
install_requires=[
'requests',
'ppp_datamodel',
],
dependency_links=[
'git+https://github.com/ProjetPP/PPP-datamodel-Python.git',
],
packages=[
'ppp_core',
],
)
|
Update osa_differ minimum version to 0.3.8
In order to support the use of PR refspecs, we
need to use 0.3.8 and above. | #!/usr/bin/env python
#
# Copyright 2014 Major Hayden
#
# 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.
#
"""Install rpc_differ."""
import sys
from setuptools import setup
required_packages = [
"GitPython",
"jinja2",
"osa_differ>=0.3.8",
"requests"
]
if sys.version_info < (2, 7):
required_packages.append("importlib")
setup(
name='rpc_differ',
version='0.3.7',
author='Major Hayden',
author_email='major@mhtx.net',
description="Find changes between RPC-OpenStack revisions",
install_requires=required_packages,
packages=['rpc_differ'],
include_package_data=True,
url='https://github.com/rcbops/rpc_differ',
entry_points='''
[console_scripts]
rpc-differ = rpc_differ.rpc_differ:run_rpc_differ
'''
)
| #!/usr/bin/env python
#
# Copyright 2014 Major Hayden
#
# 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.
#
"""Install rpc_differ."""
import sys
from setuptools import setup
required_packages = [
"GitPython",
"jinja2",
"osa_differ>=0.3.6",
"requests"
]
if sys.version_info < (2, 7):
required_packages.append("importlib")
setup(
name='rpc_differ',
version='0.3.6',
author='Major Hayden',
author_email='major@mhtx.net',
description="Find changes between RPC-OpenStack revisions",
install_requires=required_packages,
packages=['rpc_differ'],
include_package_data=True,
url='https://github.com/rcbops/rpc_differ',
entry_points='''
[console_scripts]
rpc-differ = rpc_differ.rpc_differ:run_rpc_differ
'''
)
|
FIX to Exception in thread "hornetq-expiry-reaper-thread" java.lang.OutOfMemoryError: unable to create new native thread | package rs.pelotas.tracker.core;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.ws.rs.ApplicationPath;
import rs.pelotas.arch.batch.JobScheduler;
import rs.pelotas.arch.core.BaseApplication;
import rs.pelotas.tracker.batch.PositionJob;
/**
*
* @author Rafael Guterres
*/
@ApplicationPath("/api")
public class Application extends BaseApplication {
@Inject
JobScheduler scheduler;
@Inject
Logger logger;
@Override
public JobScheduler getScheduler() {
return scheduler;
}
@Override
public Logger getLogger() {
return logger;
}
@PostConstruct
@Override
protected void init() {
//TODO: implementar annotation para agendamento automatico
//scheduler.addJob(new PositionJob());
//scheduler.scheduleJobs();
}
} | package rs.pelotas.tracker.core;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.ws.rs.ApplicationPath;
import rs.pelotas.arch.batch.JobScheduler;
import rs.pelotas.arch.core.BaseApplication;
import rs.pelotas.tracker.batch.PositionJob;
/**
*
* @author Rafael Guterres
*/
@ApplicationPath("/api")
public class Application extends BaseApplication {
@Inject
JobScheduler scheduler;
@Inject
Logger logger;
@Override
public JobScheduler getScheduler() {
return scheduler;
}
@Override
public Logger getLogger() {
return logger;
}
@PostConstruct
@Override
protected void init() {
//TODO: implementar annotation para agendamento automatico
scheduler.addJob(new PositionJob());
scheduler.scheduleJobs();
}
} |
Add ability to close sidebar by clicking outside | var sidebarOpen = false;
var menuText = ["Menu", "Close"];
var menuElement = document.querySelector(".menu-link");
var sidebarElement = document.querySelector(".sidebar");
var mainElement = document.querySelector("main");
var headerElement = document.querySelector("header");
var rAF;
mainElement.addEventListener( "click", toggleSidebar, true );
menuElement.addEventListener( "click", toggleSidebar, false );
window.addEventListener( "hashchange", toggleSidebar, false );
function toggleSidebar ( event ) {
// Don't toggle when there's nothing to hide.
if (event.type === "hashchange" && !sidebarOpen) return;
if (event.currentTarget === mainElement && !sidebarOpen) return;
sidebarOpen = (!sidebarOpen);
cancelAnimationFrame(rAF);
rAF = requestAnimationFrame(function () {
sidebarElement.classList.toggle( "sidebar-open" );
headerElement.classList.toggle( "hidden" );
menuElement.textContent = menuText[(sidebarOpen ? 1 : 0)];
});
} | var sidebarOpen = false;
var menuText = ["Menu", "Close"];
var menuElement = document.querySelector(".menu-link");
var sidebarElement = document.querySelector(".sidebar");
var headerElement = document.querySelector("header");
var rAF;
menuElement.addEventListener( "click", toggleSidebar, false );
window.addEventListener( "hashchange", toggleSidebar, false );
function toggleSidebar ( event ) {
// Don't toggle when there's nothing to hide.
if (event.type === "hashchange" && !sidebarOpen) return;
sidebarOpen = (!sidebarOpen);
cancelAnimationFrame(rAF);
rAF = requestAnimationFrame(function () {
sidebarElement.classList.toggle( "sidebar-open" );
headerElement.classList.toggle( "hidden" );
menuElement.textContent = menuText[(sidebarOpen ? 1 : 0)];
});
} |
Fix typo in compiler pass | <?php
namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Dependency injection container compiler pass to register markup validation
* processors. It finds all services having the "markup_validator.processor"
* tag and adds them to the validator
*
* @author Antoine Hérault <antoine.herault@gmail.com>
*/
class RegisterProcessorsPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
if (isset($attributes[0]['alias'])) {
$container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
}
}
}
}
| <?php
namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Dependency injection container compiler pass to register markup validation
* processors. It finds all services having the "markup_validator.processor"
* tag and adds them to the validator
*
* @author Antoine Hérault <antoine.herault@gmail.com>
*/
class RegisterValidatorsPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
if (isset($attributes[0]['alias'])) {
$container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
}
}
}
}
|
Add test for relative paths in Windows | <?php
/**
* PHP Version 5.3
*
* @copyright (c) 2015 brian ridley
* @author brian ridley <ptlis@ptlis.net>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ptlis\ShellCommand\Test\Integration\Environment;
use ptlis\ShellCommand\WindowsEnvironment;
class WindowsEnvironmentTest extends \PHPUnit_Framework_TestCase
{
public function testFullyQualified()
{
$command = __DIR__ . '\..\..\commands\windows\test.bat';
$env = new WindowsEnvironment();
if (!in_array(PHP_OS, $env->getSupportedList())) {
$this->markTestSkipped('Tests requires Windows operating system');
}
$valid = $env->validateCommand($command);
$this->assertSame(true, $valid);
}
public function testRelative()
{
$command = 'tests\commands\windows\test.bat';
$env = new WindowsEnvironment();
if (!in_array(PHP_OS, $env->getSupportedList())) {
$this->markTestSkipped('Tests requires Windows operating system');
}
$valid = $env->validateCommand($command);
$this->assertSame(true, $valid);
}
}
| <?php
/**
* PHP Version 5.3
*
* @copyright (c) 2015 brian ridley
* @author brian ridley <ptlis@ptlis.net>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ptlis\ShellCommand\Test\Integration\Environment;
use ptlis\ShellCommand\WindowsEnvironment;
class WindowsEnvironmentTest extends \PHPUnit_Framework_TestCase
{
public function testFullyQualified()
{
$command = __DIR__ . '/../../commands/windows/test.bat';
$env = new WindowsEnvironment();
if (!in_array(PHP_OS, $env->getSupportedList())) {
$this->markTestSkipped('Tests requires Windows operating system');
}
$valid = $env->validateCommand($command);
$this->assertSame(true, $valid);
}
}
|
Fix JSON input and JSON response. | "use strict";
var request = require("request");
function rCall(command, args, callback, options) {
var opts = options || {},
url,
method = Object.keys(args).length ? "POST" : "GET";
opts.server = opts.server || "https://public.opencpu.org";
opts.root = opts.root || "/ocpu";
url = opts.server + opts.root + command;
request({
method: method,
uri: url,
body: JSON.stringify(args),
headers: {
"Content-Type": "application/json"
}
}, function (err, response, data) {
err = err || response.statusCode === 400;
callback(err, JSON.parse(data));
});
}
exports.rCall = rCall;
| "use strict";
var request = require("request");
function rCall(command, args, callback, options) {
var opts = options || {},
url;
opts.server = opts.server || "https://public.opencpu.org";
opts.root = opts.root || "/ocpu";
url = opts.server + opts.root + command;
request({
method: Object.keys(args).length ? "POST" : "GET",
uri: url,
json: args,
headers: {
"Content-Type": "application/json"
}
}, function (err, response, data) {
err = err || response.statusCode === 400;
callback(err, data);
});
}
exports.rCall = rCall;
|
Change benchmark results color to magenta
as white on blue is barely visible in travis | const chalk = require('chalk');
function benchmarkResultsToConsole(suite){
console.log("\n");
console.log("==================");
console.log("Benchmark results:");
console.log("------------------");
var bench;
for(var testNo = 0; testNo < suite.length; testNo++){
bench = suite[testNo];
console.log(chalk.green.underline(bench.name) +
"\n Ops/sec: " + chalk.bold.magenta(bench.hz.toFixed(bench.hz < 100 ? 2 : 0)) +
chalk.dim(' ±' + bench.stats.rme.toFixed(2) + '% ') +
chalk.gray('Ran ' + bench.count + ' times in ' +
bench.times.cycle.toFixed(3) + ' seconds.'));
}
console.log("===================");
}
if (typeof exports !== "undefined") {
exports.benchmarkResultsToConsole = benchmarkResultsToConsole;
}
| const chalk = require('chalk');
function benchmarkResultsToConsole(suite){
console.log("\n");
console.log("==================");
console.log("Benchmark results:");
console.log("------------------");
var bench;
for(var testNo = 0; testNo < suite.length; testNo++){
bench = suite[testNo];
console.log(chalk.green.underline(bench.name) +
"\n Ops/sec: " + chalk.bold.bgBlue(bench.hz.toFixed(bench.hz < 100 ? 2 : 0)) +
chalk.dim(' ±' + bench.stats.rme.toFixed(2) + '% ') +
chalk.gray('Ran ' + bench.count + ' times in ' +
bench.times.cycle.toFixed(3) + ' seconds.'));
}
console.log("===================");
}
if (typeof exports !== "undefined") {
exports.benchmarkResultsToConsole = benchmarkResultsToConsole;
}
|
Reword use strict plugin so it's not such a blatant copy of the Banner Plugin anymore | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ConcatSource = require("webpack/node_modules/webpack-core/lib/ConcatSource");
function wrapComment(str) {
if(str.indexOf("\n") < 0) return "/*! " + str + " */";
return "/*!\n * " + str.split("\n").join("\n * ") + "\n */";
}
function UseStrictPlugin() {
}
module.exports = UseStrictPlugin;
UseStrictPlugin.prototype.apply = function(compiler) {
compiler.plugin("compilation", function(compilation) {
compilation.plugin("optimize-chunk-assets", function(chunks, callback) {
chunks.forEach(function(chunk) {
chunk.files.forEach(function(file) {
compilation.assets[file] = new ConcatSource("(function () {\n'use strict';\n", compilation.assets[file], "\n}());");
});
});
callback();
});
});
};
| /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ConcatSource = require("webpack/node_modules/webpack-core/lib/ConcatSource");
function wrapComment(str) {
if(str.indexOf("\n") < 0) return "/*! " + str + " */";
return "/*!\n * " + str.split("\n").join("\n * ") + "\n */";
}
function BannerPlugin(banner, options) {
}
module.exports = BannerPlugin;
BannerPlugin.prototype.apply = function(compiler) {
var banner = this.banner;
var entryOnly = this.entryOnly;
compiler.plugin("compilation", function(compilation) {
compilation.plugin("optimize-chunk-assets", function(chunks, callback) {
chunks.forEach(function(chunk) {
if(entryOnly && !chunk.initial) return;
chunk.files.forEach(function(file) {
compilation.assets[file] = new ConcatSource("(function () {\n'use strict';\n", compilation.assets[file], "\n}());");
});
});
callback();
});
});
};
|
Clear cookies if someone's got dodgy cookie info | import bcrypt
import hashlib
from pylons import response, request, url, config
from pylons import tmpl_context as c
from pylons.controllers.util import redirect
import porick.lib.helpers as h
from porick.model import db, User
def authenticate(username, password):
user = db.query(User).filter(User.username == username).first()
if not user:
return False
elif bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password:
set_auth_cookie(user)
return True
else:
clear_cookies()
return False
def authorize():
if not c.logged_in:
redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true'))
def set_auth_cookie(user):
auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'],
user.username,
user.level)).hexdigest()
response.set_cookie('auth', auth, max_age=2592000)
response.set_cookie('username', user.username, max_age=2592000)
response.set_cookie('level', str(user.level), max_age=2592000)
def clear_cookies():
response.delete_cookie('auth')
response.delete_cookie('username')
| import bcrypt
import hashlib
from pylons import response, request, url, config
from pylons import tmpl_context as c
from pylons.controllers.util import redirect
import porick.lib.helpers as h
from porick.model import db, User
def authenticate(username, password):
user = db.query(User).filter(User.username == username).first()
if not user:
return False
if bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password:
set_auth_cookie(user)
return True
return False
def authorize():
if not c.logged_in:
redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true'))
def set_auth_cookie(user):
auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'],
user.username,
user.level)).hexdigest()
response.set_cookie('auth', auth, max_age=2592000)
response.set_cookie('username', user.username, max_age=2592000)
response.set_cookie('level', str(user.level), max_age=2592000)
def clear_cookies():
response.delete_cookie('auth')
response.delete_cookie('username')
|
Fix in case s3boto is not installed | # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.staticfiles.finders import get_finders
from django.core.files.storage import FileSystemStorage
class SassFileStorage(FileSystemStorage):
def __init__(self, location=None, base_url=None, *args, **kwargs):
if location is None:
location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT)
if base_url is None:
base_url = settings.STATIC_URL
super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs)
try:
from storages.backends.s3boto3 import S3Boto3Storage
class SassS3Boto3Storage(S3Boto3Storage):
base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME)
except (AttributeError, ImportError):
pass
def find_file(path):
for finder in get_finders():
result = finder.find(path)
if result:
return result
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.staticfiles.finders import get_finders
from django.core.files.storage import FileSystemStorage
class SassFileStorage(FileSystemStorage):
def __init__(self, location=None, base_url=None, *args, **kwargs):
if location is None:
location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT)
if base_url is None:
base_url = settings.STATIC_URL
super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs)
try:
from storages.backends.s3boto3 import S3Boto3Storage
class SassS3Boto3Storage(S3Boto3Storage):
base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME)
except ImportError:
pass
def find_file(path):
for finder in get_finders():
result = finder.find(path)
if result:
return result
|
Update finder test to instantiate finder | 'use strict';
var test = require('tape');
var Finder = require('../lib/finder');
var finder = new Finder();
test('Finder', function(t) {
t.plan(6);
t.ok(finder, 'exports');
t.ok(finder.componentURL, 'exports componentURL');
var componentURL = finder.componentURL('foo:bar:baz:qux');
t.equals(componentURL, 'http://localhost:8357/foo/bar/baz/qux/qux.js');
var deps = finder.findDependencies({
tree: '<famous:view><famous:foo:bar famous:events:click="yaya"><la:lee:loo/></famous:foo:bar></famous:view>',
behaviors: {
'#foo': {
'famous:bla:bleep:bloop': true
}
}
});
t.deepEquals(deps, ['famous:view', 'famous:foo:bar', 'famous:events', 'la:lee:loo', 'famous:bla:bleep']);
var urls = finder.subcomponentURLs('foo:bar:baz', {
tree: 'sha.html',
behaviors: 'yay.js'
});
t.deepEquals(urls, { behaviors: 'http://localhost:8357/foo/bar/baz/yay.js', tree: 'http://localhost:8357/foo/bar/baz/sha.html' });
var type = finder.subcomponentType('bla/blee.js');
t.equals(type, 'js');
});
| 'use strict';
var test = require('tape');
var Finder = require('../lib/finder');
var finder = new Finder();
test('Finder', function(t) {
t.plan(6);
t.ok(finder, 'exports');
t.ok(finder.componentURL, 'exports componentURL');
var componentURL = finder.componentURL('foo:bar:baz:qux');
t.equals(componentURL, 'http://localhost:8357/foo/bar/baz/qux/qux.js');
var deps = finder.findDependencies({
tree: '<famous:view><famous:foo:bar famous:events:click="yaya"><la:lee:loo/></famous:foo:bar></famous:view>',
behaviors: {
'#foo': {
'famous:bla:bleep:bloop': true
}
}
});
t.deepEquals(deps, ['famous:view', 'famous:foo:bar', 'famous:events', 'la:lee:loo', 'famous:bla:bleep']);
var urls = finder.subcomponentURLs('foo:bar:baz', {
tree: 'sha.html',
behaviors: 'yay.js'
});
t.deepEquals(urls, { behaviors: 'http://localhost:8357/foo/bar/baz/yay.js', tree: 'http://localhost:8357/foo/bar/baz/sha.html' });
var type = finder.subcomponentType('bla/blee.js');
t.equals(type, 'js');
});
|
Remove last message after new sending | (function ($, Vue, marked) {
/* eslint-disable no-console */
'use strict';
Vue.filter('marked', marked);
new Vue({
el: '#mail-form',
data: {
busy: false,
text: '',
domain: '',
password: '',
mail: {
from: '',
to: '',
subject: '',
text: ''
}
},
methods: {
send: function () {
var that = this;
this.busy = true;
this.text = 'sending...';
$.post('/api/v1/' + this.domain + '/send', {
password: this.password,
from: this.mail.from,
to: this.mail.to,
subject: this.mail.subject,
text: this.mail.text
}).always(function (rep) {
console.log(arguments);
that.busy = false;
that.text = (rep && rep.responseJSON && rep.responseJSON.message || JSON.stringify(rep)) || 'no response';
});
}
}
});
/* eslint-enable no-console */
})(window.$, window.Vue, window.marked);
| (function ($, Vue, marked) {
/* eslint-disable no-console */
'use strict';
Vue.filter('marked', marked);
new Vue({
el: '#mail-form',
data: {
busy: false,
text: '',
domain: '',
password: '',
mail: {
from: '',
to: '',
subject: '',
text: ''
}
},
methods: {
send: function () {
var that = this;
this.busy = true;
$.post('/api/v1/' + this.domain + '/send', {
password: this.password,
from: this.mail.from,
to: this.mail.to,
subject: this.mail.subject,
text: this.mail.text
}).always(function (rep) {
console.log(arguments);
that.busy = false;
that.text = (rep && rep.responseJSON && rep.responseJSON.message || JSON.stringify(rep)) || 'no response';
});
}
}
});
/* eslint-enable no-console */
})(window.$, window.Vue, window.marked);
|
Update Apache Beam runtime dependencies | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='astivi@google.com',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==24.1.0', 'google-api-python-client==1.10.0',
'bloom-filter==1.3', 'google-cloud-core==1.3.0', 'google-cloud-bigquery==1.26.0',
'google-cloud-datastore==1.13.1', 'aiohttp==3.6.2'],
packages=setuptools.find_packages(),
)
| # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='astivi@google.com',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0', 'aiohttp==3.6.2'],
packages=setuptools.find_packages(),
)
|
Refactor template of `resetPassword` email | function greet(welcomeMsg) {
return function(user, url) {
var greeting = (user.profile && user.profile.name) ?
("Hello " + user.profile.name + ",") : "Hello,";
return `${greeting}
${welcomeMsg}, simply click the link below.
${url}
Thanks.
`;
};
}
/**
* @summary Options to customize emails sent from the Accounts system.
* @locus Server
* @importFromPackage accounts-base
*/
Accounts.emailTemplates = {
from: "Meteor Accounts <no-reply@meteor.com>",
siteName: Meteor.absoluteUrl().replace(/^https?:\/\//, '').replace(/\/$/, ''),
resetPassword: {
subject: function(user) {
return "How to reset your password on " + Accounts.emailTemplates.siteName;
},
text: greet("To reset your password")
},
verifyEmail: {
subject: function(user) {
return "How to verify email address on " + Accounts.emailTemplates.siteName;
},
text: greet("To verify your account email")
},
enrollAccount: {
subject: function(user) {
return "An account has been created for you on " + Accounts.emailTemplates.siteName;
},
text: greet("To start using the service")
}
};
| function greet(welcomeMsg) {
return function(user, url) {
var greeting = (user.profile && user.profile.name) ?
("Hello " + user.profile.name + ",") : "Hello,";
return `${greeting}
${welcomeMsg}, simply click the link below.
${url}
Thanks.
`;
};
}
/**
* @summary Options to customize emails sent from the Accounts system.
* @locus Server
* @importFromPackage accounts-base
*/
Accounts.emailTemplates = {
from: "Meteor Accounts <no-reply@meteor.com>",
siteName: Meteor.absoluteUrl().replace(/^https?:\/\//, '').replace(/\/$/, ''),
resetPassword: {
subject: function(user) {
return "How to reset your password on " + Accounts.emailTemplates.siteName;
},
text: function(user, url) {
var greeting = (user.profile && user.profile.name) ?
("Hello " + user.profile.name + ",") : "Hello,";
return `${greeting}
To reset your password, simply click the link below.
${url}
Thanks.
`;
}
},
verifyEmail: {
subject: function(user) {
return "How to verify email address on " + Accounts.emailTemplates.siteName;
},
text: greet("To verify your account email")
},
enrollAccount: {
subject: function(user) {
return "An account has been created for you on " + Accounts.emailTemplates.siteName;
},
text: greet("To start using the service")
}
};
|
Fix gunbanip wanting 2 arguments | package com.craftminecraft.bungee.bungeeban.command;
import com.craftminecraft.bungee.bungeeban.BanManager;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;
public class GUnbanIpCommand extends Command {
public GUnbanIpCommand() {
super("gunbanip", "bungeeban.command.gunbanip");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length != 1) {
sender.sendMessage(ChatColor.RED + "Wrong command format. <required> [optional]");
sender.sendMessage(ChatColor.RED + "/gunbanip <ip>");
return;
}
BanManager.gunban(args[0]);
sender.sendMessage(ChatColor.RED + args[0] + " has been unbanned");
}
}
| package com.craftminecraft.bungee.bungeeban.command;
import com.craftminecraft.bungee.bungeeban.BanManager;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;
public class GUnbanIpCommand extends Command {
public GUnbanIpCommand() {
super("gunbanip", "bungeeban.command.gunbanip");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length != 2) {
sender.sendMessage(ChatColor.RED + "Wrong command format. <required> [optional]");
sender.sendMessage(ChatColor.RED + "/gunbanip <ip>");
return;
}
BanManager.gunban(args[0]);
sender.sendMessage(ChatColor.RED + args[0] + " has been unbanned");
}
}
|
Fix bug when title didn't exist | function loadResource(url) {
return new Promise(function(resolve, reject){
var link = document.createElement('link');
link.setAttribute('rel', 'import');
link.setAttribute('href', url);
link.onload = function() {
resolve(url);
};
document.head.appendChild(link);
});
}
function setup(){
// Add fs-client
var fsClient = document.createElement('fs-client');
fsClient.setAttribute('client-id', 'a02j000000AhNBEAA3');
fsClient.setAttribute('redirect-uri', '/_fs-auth');
fsClient.setAttribute('environment', 'sandbox');
fsClient.setAttribute('save-access-token','');
document.body.appendChild(fsClient);
// Add fs-attach-record
var attach = document.createElement('fs-attach-record');
attach.setAttribute('person-id', 'KWCF-GK5');
attach.setAttribute('url', window.location.href);
var title = document.querySelector('h1');
if(title){
attach.setAttribute('title', title.textContent);
}
document.querySelector('#attach-to-tree').appendChild(attach);
}
loadResource(chrome.extension.getURL('components.html'))
.then(setup);
| console.log('fs attach record');
function loadResource(url) {
return new Promise(function(resolve, reject){
var link = document.createElement('link');
link.setAttribute('rel', 'import');
link.setAttribute('href', url);
link.onload = function() {
resolve(url);
};
document.head.appendChild(link);
});
}
function setup(){
// Add fs-client
var fsClient = document.createElement('fs-client');
fsClient.setAttribute('client-id', 'a02j000000AhNBEAA3');
fsClient.setAttribute('redirect-uri', '/_fs-auth');
fsClient.setAttribute('environment', 'sandbox');
fsClient.setAttribute('save-access-token','');
document.body.appendChild(fsClient);
// Add fs-attach-record
var attach = document.createElement('fs-attach-record');
attach.setAttribute('person-id', 'KWCF-GK5');
attach.setAttribute('url', window.location.href);
attach.setAttribute('title', document.querySelector('h1').textContent);
document.querySelector('#attach-to-tree').appendChild(attach);
}
loadResource(chrome.extension.getURL('components.html'))
.then(setup);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.