text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Make cargs and gargs truly optional | import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None):
xii_env = os.environ.copy()
for key, value in variables.items():
print("=> XII_" + key + " defined")
xii_env["XII_" + key] = value
call = ["xii", "--no-parallel", "--deffile", deffile, cmd]
print("calling `{}`".format(" ".join(call)))
process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env)
for line in process.stdout:
print("> " + line.rstrip(os.linesep))
if process.returncode != 0:
raise RuntimeError("running xii failed")
| import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None):
xii_env = os.environ.copy()
for key, value in variables.items():
print("=> XII_" + key + " defined")
xii_env["XII_" + key] = value
call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs]
print("calling `{}`".format(" ".join(filter(None, call))))
process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env)
for line in process.stdout:
print("> " + line.rstrip(os.linesep))
if process.returncode != 0:
raise RuntimeError("running xii failed")
|
Change project root variable in clean plugin | const CleanWebpackPlugin = require("clean-webpack-plugin")
const path = require("path")
const webpack = require("webpack")
const dist = path.join(process.cwd(), "public")
const src = path.join(process.cwd(), "src")
//module.exports = { dist, src }
module.exports = {
entry: [path.join(src, "index.js")],
module: {
rules: [
{
test: /\.(graphql|gql)?$/,
use: "raw-loader"
},
{
exclude: /node_modules/,
test: /\.js?$/,
use: [
{
loader: "babel-loader"
}
]
},
{
test: /\.y(a?)ml$/,
use: ["json-loader", "yaml-loader"]
}
]
},
node: {
__filename: true,
__dirname: true
},
output: { path: dist, filename: "server.js" },
plugins: [
new CleanWebpackPlugin(dist, {
root: process.cwd()
}),
new webpack.IgnorePlugin(/vertx/),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
target: "node"
}
| const CleanWebpackPlugin = require("clean-webpack-plugin")
const path = require("path")
const webpack = require("webpack")
const dist = path.join(process.cwd(), "public")
const src = path.join(process.cwd(), "src")
//module.exports = { dist, src }
module.exports = {
entry: [path.join(src, "index.js")],
module: {
rules: [
{
test: /\.(graphql|gql)?$/,
use: "raw-loader"
},
{
exclude: /node_modules/,
test: /\.js?$/,
use: [
{
loader: "babel-loader"
}
]
},
{
test: /\.y(a?)ml$/,
use: ["json-loader", "yaml-loader"]
}
]
},
node: {
__filename: true,
__dirname: true
},
output: { path: dist, filename: "server.js" },
plugins: [
new CleanWebpackPlugin(dist),
new webpack.IgnorePlugin(/vertx/),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
target: "node"
}
|
Update style guide highlight.js from 9.1.0 to 9.2.0 | /* global hljs */
Wee.fn.make('guide', {
/**
* Highlight code and bind click events
*
* @constructor
*/
_construct: function() {
var priv = this.$private;
// Setup syntax highlighting
priv.highlightCode();
// Bind code toggle and selection
$('ref:code').on('dblclick', function() {
priv.selectCode(this);
});
}
}, {
/**
* Load highlight.js assets and highlight code
*
* @private
*/
highlightCode: function() {
Wee.assets.load({
root: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/',
files: [
'highlight.min.js',
'styles/github.min.css'
],
success: function() {
hljs.initHighlightingOnLoad();
}
});
},
/**
* Select all content in a code block
*
* @private
* @param {HTMLElement} el - target code wrapper
*/
selectCode: function(el) {
var range = $._doc.createRange(),
sel = $._win.getSelection();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
}
}); | /* global hljs */
Wee.fn.make('guide', {
/**
* Highlight code and bind click events
*
* @constructor
*/
_construct: function() {
var priv = this.$private;
// Setup syntax highlighting
priv.highlightCode();
// Bind code toggle and selection
$('ref:code').on('dblclick', function() {
priv.selectCode(this);
});
}
}, {
/**
* Load highlight.js assets and highlight code
*
* @private
*/
highlightCode: function() {
Wee.assets.load({
root: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/',
files: [
'highlight.min.js',
'styles/github.min.css'
],
success: function() {
hljs.initHighlightingOnLoad();
}
});
},
/**
* Select all content in a code block
*
* @private
* @param {HTMLElement} el - target code wrapper
*/
selectCode: function(el) {
var range = $._doc.createRange(),
sel = $._win.getSelection();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
}
}); |
Revert "Removed Javascript from Markdown by adding display priority to def config."
This reverts commit 58e05f9625c60f8deba9ddf1c74dba73e8ea7dd1. | """Markdown Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.config import Config
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class MarkdownExporter(TemplateExporter):
"""
Exports to a markdown document (.md)
"""
def _file_extension_default(self):
return 'md'
def _template_file_default(self):
return 'markdown'
output_mimetype = 'text/markdown'
def _raw_mimetypes_default(self):
return ['text/markdown', 'text/html', '']
@property
def default_config(self):
c = Config({'ExtractOutputPreprocessor':{'enabled':True}})
c.merge(super(MarkdownExporter,self).default_config)
return c
| """Markdown Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.config import Config
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class MarkdownExporter(TemplateExporter):
"""
Exports to a markdown document (.md)
"""
def _file_extension_default(self):
return 'md'
def _template_file_default(self):
return 'markdown'
output_mimetype = 'text/markdown'
def _raw_mimetypes_default(self):
return ['text/markdown', 'text/html', '']
@property
def default_config(self):
c = Config({
'NbConvertBase': {
'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text']
},
'ExtractOutputPreprocessor': {
'enabled':True}
})
c.merge(super(MarkdownExporter,self).default_config)
return c
|
Fix something, something else is broken. | <?php
$config = require_once(dirname(__FILE__) .'/main.default.php');
return array_merge($config,
array(
'components' => array(
'db' => array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=ciims_test',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'schemaCachingDuration' => '3600',
'enableProfiling' => true,
),
),
'params' => array(
'yiiPath' => dirname(__FILE__) . '/../runtime/yii/framework/',
'encryptionKey' => 'ag93ba23r'
)
)
); | <?php return array_merge(require_once(dirname(__FILE__) .'/main.default.php'),
array(
'components' => array(
'db' => array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=ciims_test',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'schemaCachingDuration' => '3600',
'enableProfiling' => true,
),
),
'params' => array(
'yiiPath' => dirname(__FILE__) . '/../runtime/yii/framework/',
'encryptionKey' => 'ag93ba23r'
)
)
); |
Refresh a user from travis | <?php
declare(strict_types=1);
namespace WyriHaximus\Travis\Resource\Async;
use GuzzleHttp\Psr7\Request;
use React\Promise\PromiseInterface;
use WyriHaximus\Travis\Resource\User as BaseUser;
use function React\Promise\resolve;
class User extends BaseUser
{
public function refresh() : PromiseInterface
{
return $this->getTransport()->request('users/' . $this->id())->then(function ($json) {
return resolve($this->getTransport()->getHydrator()->hydrate('User', $json['user']));
});
}
public function sync(): PromiseInterface
{
return $this->getTransport()->requestPsr7(
new Request(
'POST',
$this->getTransport()->getBaseURL() . 'users/sync',
$this->getTransport()->getHeaders()
)
)->then(function () {
return $this->refresh();
});
}
}
| <?php
declare(strict_types=1);
namespace WyriHaximus\Travis\Resource\Async;
use GuzzleHttp\Psr7\Request;
use React\Promise\PromiseInterface;
use WyriHaximus\Travis\Resource\User as BaseUser;
class User extends BaseUser
{
public function refresh() : User
{
return $this->wait($this->callAsync('refresh'));
}
public function sync(): PromiseInterface
{
return $this->getTransport()->requestPsr7(
new Request(
'POST',
$this->getTransport()->getBaseURL() . 'users/sync',
$this->getTransport()->getHeaders()
)
)->then(function () {
return $this->refresh();
});
}
}
|
Rename `isRole` to `hasRole` and return true if SuperAdmin | <?php namespace GeneaLabs\LaravelGovernor\Traits;
use GeneaLabs\LaravelGovernor\Permission;
use GeneaLabs\LaravelGovernor\Role;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;
trait Governable
{
public function hasRole(string $name) : bool
{
$this->load('roles');
if ($this->roles->isEmpty()) {
return false;
}
$role = (new Role)
->where('name', $name)
->first();
if (! $role) {
return false;
}
return $this->roles->contains($role->name)
|| $this->roles->contains("SuperAdmin");
}
public function roles() : BelongsToMany
{
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_key');
}
public function getPermissionsAttribute() : Collection
{
$roleNames = $this->roles->pluck('name');
return (new Permission)->whereIn('role_key', $roleNames)->get();
}
}
| <?php namespace GeneaLabs\LaravelGovernor\Traits;
use GeneaLabs\LaravelGovernor\Permission;
use GeneaLabs\LaravelGovernor\Role;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;
trait Governable
{
public function isRole(string $name) : bool
{
$this->load('roles');
if ($this->roles->isEmpty()) {
return false;
}
$role = (new Role)
->where('name', $name)
->first();
if (! $role) {
return false;
}
return $this->roles->contains($role->name);
}
public function roles() : BelongsToMany
{
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_key');
}
public function getPermissionsAttribute() : Collection
{
$roleNames = $this->roles->pluck('name');
return (new Permission)->whereIn('role_key', $roleNames)->get();
}
}
|
Set scrolling duration to 0 | import React, { Component } from 'react';
import ChatMessage from './ChatMessage';
import Scroll from 'react-scroll';
class ChatMessageList extends Component {
getMessages = () => {
return this.props.messages.map((message, index) => {
return <ChatMessage key={index} message={message} person={message.from === 'me' ? this.props.me : this.props.partner} />;
});
}
scrollToBottom = () => {
var scroll = Scroll.animateScroll;
scroll.scrollToBottom({duration: 0});
}
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
render() {
return (
<ul>
{this.getMessages()}
</ul>
);
}
}
export default ChatMessageList;
| import React, { Component } from 'react';
import ChatMessage from './ChatMessage';
import Scroll from 'react-scroll';
class ChatMessageList extends Component {
getMessages = () => {
return this.props.messages.map((message, index) => {
return <ChatMessage key={index} message={message} person={message.from === 'me' ? this.props.me : this.props.partner} />;
});
}
scrollToBottom = () => {
var scroll = Scroll.animateScroll;
scroll.scrollToBottom();
}
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
render() {
return (
<ul>
{this.getMessages()}
</ul>
);
}
}
export default ChatMessageList;
|
Fix document path with urlEngine | (function () {
var cogClass = function () {};
cogClass.prototype.exec = function (params, request, response) {
var oops = this.sys.apiError;
var sys = this.sys;
var documentID = params.documentid;
var sql = 'SELECT documentID,title '
+ 'FROM documents '
+ 'JOIN titles USING(titleID) '
+ 'WHERE documentID=?';
sys.db.get(sql,[documentID],function(err,row){
if (err||!row||!row.documentID) {return oops(response,err,'event/getonedocument(1)')};
row.url = sys.urlEngine.hostpath() + '/attachments/' + documentID;
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(row));
});
}
exports.cogClass = cogClass;
})();
| (function () {
var cogClass = function () {};
cogClass.prototype.exec = function (params, request, response) {
var oops = this.sys.apiError;
var sys = this.sys;
var documentID = params.documentid;
var sql = 'SELECT documentID,title '
+ 'FROM documents '
+ 'JOIN titles USING(titleID) '
+ 'WHERE documentID=?';
sys.db.get(sql,[documentID],function(err,row){
if (err||!row||!row.documentID) {return oops(response,err,'event/getonedocument(1)')};
row.url = 'http://' + sys.proxy_hostname + sys.gslfrontpage_path + 'attachments/' + documentID;
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(row));
});
}
exports.cogClass = cogClass;
})();
|
Fix bug with Parameter Node not getting correct value | /*!
* @depends ../core/AudioletNode.js
*/
/**
* A type of AudioletNode designed to allow AudioletGroups to exactly replicate
* the behaviour of AudioletParameters. By linking one of the group's inputs
* to the ParameterNode's input, and calling `this.parameterName =
* parameterNode` in the group's constructor, `this.parameterName` will behave
* as if it were an AudioletParameter contained within an AudioletNode.
*
* **Inputs**
*
* - Parameter input
*
* **Outputs**
*
* - Parameter value
*
* **Parameters**
*
* - parameter The contained parameter. Linked to input 0.
*
* @constructor
* @extends AudioletNode
* @param {Audiolet} audiolet The audiolet object.
* @param {Number} value The initial static value of the parameter.
*/
var ParameterNode = function(audiolet, value) {
AudioletNode.call(this, audiolet, 1, 1);
this.parameter = new AudioletParameter(this, 0, value);
};
extend(ParameterNode, AudioletNode);
/**
* Process a block of samples
*/
ParameterNode.prototype.generate = function() {
this.outputs[0].samples[0] = this.parameter.getValue();
};
/**
* toString
*
* @return {String} String representation.
*/
ParameterNode.prototype.toString = function() {
return 'Parameter Node';
};
| /*!
* @depends ../core/AudioletNode.js
*/
/**
* A type of AudioletNode designed to allow AudioletGroups to exactly replicate
* the behaviour of AudioletParameters. By linking one of the group's inputs
* to the ParameterNode's input, and calling `this.parameterName =
* parameterNode` in the group's constructor, `this.parameterName` will behave
* as if it were an AudioletParameter contained within an AudioletNode.
*
* **Inputs**
*
* - Parameter input
*
* **Outputs**
*
* - Parameter value
*
* **Parameters**
*
* - parameter The contained parameter. Linked to input 0.
*
* @constructor
* @extends AudioletNode
* @param {Audiolet} audiolet The audiolet object.
* @param {Number} value The initial static value of the parameter.
*/
var ParameterNode = function(audiolet, value) {
AudioletNode.call(this, audiolet, 1, 1);
this.parameter = new AudioletParameter(this, 0, value);
};
extend(ParameterNode, AudioletNode);
/**
* Process a block of samples
*/
ParameterNode.prototype.generate = function() {
output.samples[0] = this.parameter.getValue();
};
/**
* toString
*
* @return {String} String representation.
*/
ParameterNode.prototype.toString = function() {
return 'Parameter Node';
};
|
Fix bug with user logout | <?php
namespace mrssoft\engine\controllers;
use mrssoft\engine\models\LoginForm;
use yii;
use yii\base\UserException;
use yii\web\MethodNotAllowedHttpException;
class AuthController extends \yii\web\Controller
{
public function actionLogin()
{
$model = new LoginForm();
if ($model->load(\Yii::$app->request->post()) && $model->login()) {
return $this->redirect('/' . $this->module->id);
}
$model->username = '';
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
public function actionLogout()
{
if (Yii::$app->request->isPost === false) {
throw new MethodNotAllowedHttpException();
}
if (Yii::$app->user->isGuest) {
throw new UserException('User not found.');
}
Yii::$app->user->logout();
$this->redirect('/' . $this->module->id);
}
} | <?php
namespace mrssoft\engine\controllers;
use mrssoft\engine\models\LoginForm;
use yii;
use yii\base\UserException;
use yii\web\MethodNotAllowedHttpException;
class AuthController extends \yii\web\Controller
{
public function actionLogin()
{
$model = new LoginForm();
if ($model->load(\Yii::$app->request->post()) && $model->login()) {
return $this->redirect('/' . $this->module->id);
}
$model->username = '';
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
public function actionLogout()
{
if (Yii::$app->request->isPost) {
throw new MethodNotAllowedHttpException();
}
if (Yii::$app->user->isGuest) {
throw new UserException('User not found.');
}
Yii::$app->user->logout();
$this->redirect('/' . $this->module->id);
}
} |
Remove python 3.6 only format strings | class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
local_addr_desc = 'IN IP4 {}'.format(self.local_addr[0])
self.payload = '\r\n'.join([
'v=0',
'o=user1 53655765 2353687637 {local_addr_desc}',
's=-',
't=0 0',
'i=aiortp media stream',
'm=audio {local_port} RTP/AVP 0 101 13',
'c={local_addr_desc}',
'a=rtpmap:0 PCMU/8000/1',
'a=rtpmap:101 telephone-event/8000',
'a=fmtp:101 0-15',
'a=ptime:{ptime}',
'a=sendrecv',
'',
]).format(local_addr_desc=local_addr_desc,
local_port=self.local_addr[1],
ptime=self.ptime)
def __str__(self):
return self.payload
| class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
local_addr_desc = f'IN IP4 {self.local_addr[0]}'
self.payload = '\r\n'.join([
'v=0',
f'o=user1 53655765 2353687637 {local_addr_desc}',
's=-',
't=0 0',
'i=aiortp media stream',
f'm=audio {self.local_addr[1]} RTP/AVP 0 101 13',
f'c={local_addr_desc}',
'a=rtpmap:0 PCMU/8000/1',
'a=rtpmap:101 telephone-event/8000',
'a=fmtp:101 0-15',
f'a=ptime:{self.ptime}',
'a=sendrecv',
'',
])
def __str__(self):
return self.payload
|
Add both build id / git commit sha via @hone | 'use strict';
let cli = require('heroku-cli-util');
let columnify = require('columnify');
module.exports = {
topic: 'builds',
needsAuth: true,
needsApp: true,
description: 'list builds',
help: 'List builds for a Heroku app',
run: cli.command(function (context, heroku) {
return heroku.request({
path: `/apps/${context.app}/builds`,
method: 'GET',
headers: {
'Range': 'created_at ..; order=desc;'
},
parseJSON: true
}).then(function (builds) {
var columnData = builds.slice(0, 10).map(function(build) {
return { created_at: build.created_at,
status: build.status,
id: build.id,
version: build.source_blob.version,
user: build.user.email
};
});
// TODO: use `max` directive in query to avoid the slice nonsense
// heroku-client currently breaks if one tries to do this
var columns = columnify(columnData, {
showHeaders: false
});
console.log(columns);
});
})
};
| 'use strict';
let cli = require('heroku-cli-util');
let columnify = require('columnify');
module.exports = {
topic: 'builds',
needsAuth: true,
needsApp: true,
description: 'list builds',
help: 'List builds for a Heroku app',
run: cli.command(function (context, heroku) {
return heroku.request({
path: `/apps/${context.app}/builds`,
method: 'GET',
headers: {
'Range': 'created_at ..; order=desc;'
},
parseJSON: true
}).then(function (builds) {
var columnData = builds.slice(0, 10).map(function(build) {
return { created_at: build.created_at,
status: build.status,
id: build.id,
user: build.user.email
};
});
// TODO: use `max` directive in query to avoid the slice nonsense
// heroku-client currently breaks if one tries to do this
var columns = columnify(columnData, {
showHeaders: false
});
console.log(columns);
});
})
};
|
Remove the match param to fix RCE. | from re import split as resplit
from typing import Callable, Union
from dmoj.result import CheckerResult
from dmoj.utils.unicode import utf8bytes
verdict = u"\u2717\u2713"
def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,
**kwargs) -> Union[CheckerResult, bool]:
process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output))))
judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output))))
if len(process_lines) > len(judge_lines):
return False
if not judge_lines:
return True
cases = [verdict[0]] * len(judge_lines)
count = 0
for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):
if process_line.strip() == judge_line.strip():
cases[i] = verdict[1]
count += 1
return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)),
''.join(cases) if feedback else "")
check.run_on_error = True # type: ignore
| from re import split as resplit
from typing import Callable, Union
from dmoj.result import CheckerResult
from dmoj.utils.unicode import utf8bytes
verdict = u"\u2717\u2713"
def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,
match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(),
**kwargs) -> Union[CheckerResult, bool]:
process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output))))
judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output))))
if len(process_lines) > len(judge_lines):
return False
if not judge_lines:
return True
if isinstance(match, str):
match = eval(match)
cases = [verdict[0]] * len(judge_lines)
count = 0
for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):
if match(process_line, judge_line):
cases[i] = verdict[1]
count += 1
return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)),
''.join(cases) if feedback else "")
check.run_on_error = True # type: ignore
|
fix: Add PyLintHandler to artifact manager | from __future__ import absolute_import, print_function
from .manager import Manager
from .checkstyle import CheckstyleHandler
from .coverage import CoverageHandler
from .pycodestyle import PyCodeStyleHandler
from .pylint import PyLintHandler
from .xunit import XunitHandler
manager = Manager()
manager.register(CheckstyleHandler, [
'checkstyle.xml', '*.checkstyle.xml'])
manager.register(CoverageHandler, [
'coverage.xml', '*.coverage.xml'])
manager.register(XunitHandler, [
'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml'])
manager.register(PyCodeStyleHandler, [
'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt'])
manager.register(PyLintHandler, [
'pylint.txt', '*.pylint.txt'])
| from __future__ import absolute_import, print_function
from .manager import Manager
from .checkstyle import CheckstyleHandler
from .coverage import CoverageHandler
from .pycodestyle import PyCodeStyleHandler
from .xunit import XunitHandler
manager = Manager()
manager.register(CheckstyleHandler, [
'checkstyle.xml', '*.checkstyle.xml'])
manager.register(CoverageHandler, [
'coverage.xml', '*.coverage.xml'])
manager.register(XunitHandler, [
'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml'])
manager.register(PyCodeStyleHandler, [
'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt'])
|
Patch for Event handler (second try) :)
Real patch for event handler... | "use babel";
import { Emitter } from 'atom'
export default class EventHandlerHelper
{
constructor()
{
this.emitter = new Emitter();
}
onClose(callback)
{
return this.emitter.on("maperwiki-wordcount-close",callback);
}
close()
{
this.emitter.emit("maperwiki-wordcount-close");
}
onViewWordcountFrame(callback)
{
return this.emitter.on("maperwiki-wordcount-visibility",callback);
}
viewWordcountFrame(visible)
{
this.emitter.emit("maperwiki-wordcount-visibility",visible);
}
onCloseExportPanel(callback)
{
return this.emitter.on("maperwiki-export-panel-close",callback);
}
closeExportPanel(visible)
{
this.emitter.emit("maperwiki-export-panel-close",visible);
}
onClear(callback)
{
return this.emitter.on("clear-control",callback);
}
clear()
{
this.emitter.emit("clear-control");
}
destroy()
{
this.emitter.clear();
this.emitter.dispose();
}
}
| "use babel";
import { Emitter } from 'atom'
export default class EventHandlerHelper
{
constructor()
{
this.emitter = new Emitter();
}
onClose(callback)
{
this.emitter.on("maperwiki-wordcount-close",callback);
}
close()
{
this.emitter.emit("maperwiki-wordcount-close");
}
onViewWordcountFrame(callback)
{
this.emitter.on("maperwiki-wordcount-visibility",callback);
}
viewWordcountFrame(visible)
{
this.emitter.emit("maperwiki-wordcount-visibility",visible);
}
onCloseExportPanel(callback)
{
this.emitter.on("maperwiki-export-panel-close",callback);
}
closeExportPanel(visible)
{
this.emitter.emit("maperwiki-export-panel-close",visible);
}
onClear(callback)
{
this.emitter.on("clear-control",callback);
}
clear()
{
this.emitter.emit("clear-control");
}
destroy()
{
this.emitter.clear();
this.emitter.dispose();
}
dispose()
{
this.destroy();
}
}
|
Remove a ref to now-gone sample_project. | from setuptools import setup, find_packages
setup(
name='django-crumbs',
version=__import__('crumbs').__version__,
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
include_package_data=True,
packages=find_packages(),
exclude_package_data={'': ['*.sql', '*.pyc']},
url='http://github.com/caktus/django-crumbs/',
license='BSD',
description='A pluggable Django app for adding breadcrumbs to your project. ',
classifiers=[
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
],
long_description=open('README.rst').read(),
zip_safe=False,
)
| from setuptools import setup, find_packages
setup(
name='django-crumbs',
version=__import__('crumbs').__version__,
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
include_package_data=True,
packages=find_packages(exclude=['sample_project']),
exclude_package_data={'': ['*.sql', '*.pyc']},
url='http://github.com/caktus/django-crumbs/',
license='BSD',
description='A pluggable Django app for adding breadcrumbs to your project. ',
classifiers=[
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
],
long_description=open('README.rst').read(),
zip_safe=False,
)
|
Use mkdir instead of makedirs because we don't need parent directories made | from os import mkdir
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import urlopenmock
class BaseTest(object):
files = 'tests/files'
def setup(self):
# if `file` isn't there, make it
if not exists(self.files):
mkdir(self.files)
# absolute path to the file is pretty useful
self.path = abspath(dirname(__file__))
# build the file list
with open(join(self.path, 'file_list'), 'r') as f:
for fn in f.readlines():
with open(abspath(join(self.files, fn.strip())), 'w') as f:
f.write('')
# instantiate tvr
self.config = Config(join(self.path, 'config.yml'))
self.tv = TvRenamr(self.files, self.config)
def teardown(self):
rmtree(self.files)
| from os import makedirs
from os.path import abspath, dirname, exists, join
from shutil import rmtree
from tvrenamr.config import Config
from tvrenamr.main import TvRenamr
from tvrenamr.tests import urlopenmock
class BaseTest(object):
files = 'tests/files'
def setup(self):
# if `file` isn't there, make it
if not exists(self.files):
makedirs(self.files)
# absolute path to the file is pretty useful
self.path = abspath(dirname(__file__))
# build the file list
with open(join(self.path, 'file_list'), 'r') as f:
for fn in f.readlines():
with open(abspath(join(self.files, fn.strip())), 'w') as f:
f.write('')
# instantiate tvr
self.config = Config(join(self.path, 'config.yml'))
self.tv = TvRenamr(self.files, self.config)
def teardown(self):
rmtree(self.files)
|
Add items to prescription state | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { ROUTES } from '../navigation/constants';
import { UIDatabase } from '../database';
import { PRESCRIPTION_ACTIONS } from '../actions/PrescriptionActions';
const initialState = () => ({
currentTab: 0,
transaction: null,
items: UIDatabase.objects('Item'),
itemSearchTerm: '',
});
export const PrescriptionReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case 'Navigation/NAVIGATE': {
const { routeName, params } = action;
if (routeName !== ROUTES.PRESCRIPTION) return state;
const { transaction } = params;
return { ...state, transaction };
}
case PRESCRIPTION_ACTIONS.REFRESH: {
return { ...state };
}
case PRESCRIPTION_ACTIONS.FILTER: {
const { payload } = action;
const { itemSearchTerm } = payload;
return { ...state, itemSearchTerm };
}
default:
return state;
}
};
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { ROUTES } from '../navigation/constants';
import { PRESCRIPTION_ACTIONS } from '../actions/PrescriptionActions';
const initialState = () => ({
currentTab: 0,
transaction: null,
itemSearchTerm: '',
});
export const PrescriptionReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case 'Navigation/NAVIGATE': {
const { routeName, params } = action;
if (routeName !== ROUTES.PRESCRIPTION) return state;
const { transaction } = params;
return { ...state, transaction };
}
case PRESCRIPTION_ACTIONS.REFRESH: {
return { ...state };
}
case PRESCRIPTION_ACTIONS.FILTER: {
const { payload } = action;
const { itemSearchTerm } = payload;
return { ...state, itemSearchTerm };
}
default:
return state;
}
};
|
BB-6143: Add code property for attribute group
- fix translation key | <?php
namespace Oro\Bundle\EntityConfigBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
class AttributeFamilyGroups extends Constraint
{
/**
* @var string
*/
public $emptyGroupsMessage = 'oro.entity_config.validator.attribute_family.empty_groups';
/**
* @var string
*/
public $manyDefaultGroupsMessage = 'oro.entity_config.validator.attribute_family.many_default_groups';
/**
* @var string
*/
public $defaultGroupIsNotExistMessage = 'oro.entity_config.validator.attribute_family.default_group_is_not_exist';
/**
* @var string
*/
public $sameLabelsMessage = 'oro.entity_config.validator.attribute_family.same_labels';
/**
* {@inheritdoc}
*/
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
/**
* {@inheritdoc}
*/
public function validatedBy()
{
return AttributeFamilyGroupsValidator::ALIAS;
}
}
| <?php
namespace Oro\Bundle\EntityConfigBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
class AttributeFamilyGroups extends Constraint
{
/**
* @var string
*/
public $emptyGroupsMessage = 'oro.entity_config.validator.attribute_family.empty_groups';
/**
* @var string
*/
public $manyDefaultGroupsMessage = 'oro.entity_config.validator.attribute_family.many_default_groups';
/**
* @var string
*/
public $defaultGroupIsNotExistMessage = 'oro.entity_config.validator.attribute_family.default_group_is_not_exist';
/**
* @var string
*/
public $sameLabelsMessage = 'oro.entity_extend.validator.attribute_family.same_labels';
/**
* {@inheritdoc}
*/
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
/**
* {@inheritdoc}
*/
public function validatedBy()
{
return AttributeFamilyGroupsValidator::ALIAS;
}
}
|
Connect to databases INVFEST-DB-dev & INVFEST-DB-PUBLIC-dev from the development branch | <?php
if ($_SESSION["autentificado"]=='SI') {
if ($_SESSION['MySQLuser']=="invfest") {
// Admin user
$user = "invfest";
$password = "pwdInvFEST";
$db = "INVFEST-DB-dev";
} elseif ($_SESSION['MySQLuser']=="invfestdb-lab") {
// Lab user
$user = "invfestdb-lab";
$password = "InvFESTLab";
$db = "INVFEST-DB-dev";
} else {
// I don't know who you are...
$user = "invfest";
$password = "pwdInvFEST";
$db = "INVFEST-DB-PUBLIC-dev";
}
} else {
// No login
$user = "invfest";
$password = "pwdInvFEST";
$db = "INVFEST-DB-PUBLIC-dev";
}
$con = mysql_connect('localhost', $user, $password);
//$con = mysql_connect('localhost', 'root', 'pwdroot');
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($db, $con);
?>
| <?php
if ($_SESSION["autentificado"]=='SI') {
if ($_SESSION['MySQLuser']=="invfest") {
// Admin user
$user = "invfest";
$password = "pwdInvFEST";
$db = "INVFEST-DB";
} elseif ($_SESSION['MySQLuser']=="invfestdb-lab") {
// Lab user
$user = "invfestdb-lab";
$password = "InvFESTLab";
$db = "INVFEST-DB";
} else {
// I don't know who you are...
$user = "invfest";
$password = "pwdInvFEST";
$db = "INVFEST-DB-PUBLIC";
}
} else {
// No login
$user = "invfest";
$password = "pwdInvFEST";
$db = "INVFEST-DB-PUBLIC";
}
$con = mysql_connect('localhost', $user, $password);
//$con = mysql_connect('localhost', 'root', 'pwdroot');
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($db, $con);
?>
|
Add comment about what it is | // # Map (map interval)
// Ease function can be a interpolation function as below
function map ( input, inputMin, inputMax, outputMin, outputMax, clamp, ease ) {
input = ( input - inputMin ) / ( inputMax - inputMin );
if ( ease ) {
input = ease(input);
}
var output = input * ( outputMax - outputMin ) + outputMin;
if ( !!clamp ) {
if ( outputMax < outputMin ) {
if ( output < outputMax ) {
output = outputMax;
}
else if ( output > outputMin ) {
output = outputMin;
}
} else {
if ( output > outputMax ) {
output = outputMax;
}
else if ( output < outputMin ) {
output = outputMin;
}
}
}
return output;
}
| // Ease function can be a interpolation function as below
function map ( input, inputMin, inputMax, outputMin, outputMax, clamp, ease ) {
input = ( input - inputMin ) / ( inputMax - inputMin );
if ( ease ) {
input = ease(input);
}
var output = input * ( outputMax - outputMin ) + outputMin;
if ( !!clamp ) {
if ( outputMax < outputMin ) {
if ( output < outputMax ) {
output = outputMax;
}
else if ( output > outputMin ) {
output = outputMin;
}
} else {
if ( output > outputMax ) {
output = outputMax;
}
else if ( output < outputMin ) {
output = outputMin;
}
}
}
return output;
}
|
Revert "Experiment with SequenceField that inherits from AutoField"
This reverts commit 726c1d31e353e6c1a079fd06c3008c0714f95b86. | from django.db.models import Field
class SequenceField(Field):
def __init__(self, *args, **kwargs):
kwargs['blank'] = True
super(SequenceField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(SequenceField, self).deconstruct()
# lacks 'kwargs['primary_key'] = True', unlike AutoField
return name, path, args, kwargs
def get_internal_type(self):
return "SequenceField"
def to_python(self, value):
return int(value)
def db_type(self, connection):
return 'serial'
def get_db_prep_value(self, value, connection, prepared=False):
if not prepared:
value = self.get_prep_value(value)
# avoid the PK validation of AutoField
return value
def get_prep_value(self, value):
value = super(SequenceField, self).get_prep_value(value)
if value is None or value == '':
return None
return int(value)
def contribute_to_class(self, cls, name):
# TODO Cleaner way to call Field's version
self.set_attributes_from_name(name)
self.model = cls
cls._meta.add_field(self)
| from django.db.models import AutoField
class SequenceField(AutoField):
"""Overrides the parts of AutoField that force it to be a PK"""
def __init__(self, *args, **kwargs):
super(SequenceField, self).__init__(*args, **kwargs)
def check(self, **kwargs):
"""Shut up '(fields.E100) AutoFields must set primary_key=True.'"""
errors = super(AutoField, self).check(**kwargs)
return errors
def deconstruct(self):
name, path, args, kwargs = super(AutoField, self).deconstruct()
# lacks 'kwargs['primary_key'] = True', unlike AutoField
return name, path, args, kwargs
def get_internal_type(self):
return "SequenceField"
def get_db_prep_value(self, value, connection, prepared=False):
if not prepared:
value = self.get_prep_value(value)
# avoid the PK validation of AutoField
return value
def contribute_to_class(self, cls, name, **kwargs):
"""Stop enforcing the 'one autofield per class' validation"""
super(AutoField, self).contribute_to_class(cls, name, **kwargs)
|
Enable Shutdown button for a suspended VM
Fixes: https://github.com/oVirt/ovirt-web-ui/issues/1227
Add missing 'suspended' in the array of VM statuses for shutdown button being enabled in VM details page.
Make the Shutdown action available for a suspended VM. | export function canStart (state) {
return ['down', 'paused', 'suspended'].includes(state)
}
export function canShutdown (state) {
return ['up', 'migrating', 'reboot_in_progress', 'paused', 'powering_up', 'powering_down', 'not_responding', 'suspended'].includes(state)
}
export function canRestart (state) {
return ['up', 'migrating'].includes(state)
}
export function canSuspend (state) {
return ['up'].includes(state)
}
export function canConsole (state) {
return ['up', 'powering_up', 'powering_down', 'paused', 'migrating', 'reboot_in_progress', 'saving_state'].includes(state)
}
export function canRemove (state) {
return ['down'].includes(state)
}
export function canChangeCluster (state) {
return ['down'].includes(state)
}
export function canChangeCd (state) {
return ['up'].includes(state)
}
export function canDeleteDisk (state) {
return ['down'].includes(state)
}
export function canExternalService (state, fqdn) {
return fqdn ? canRestart(state) : false
}
| export function canStart (state) {
return ['down', 'paused', 'suspended'].includes(state)
}
export function canShutdown (state) {
return ['up', 'migrating', 'reboot_in_progress', 'paused', 'powering_up', 'powering_down', 'not_responding'].includes(state)
}
export function canRestart (state) {
return ['up', 'migrating'].includes(state)
}
export function canSuspend (state) {
return ['up'].includes(state)
}
export function canConsole (state) {
return ['up', 'powering_up', 'powering_down', 'paused', 'migrating', 'reboot_in_progress', 'saving_state'].includes(state)
}
export function canRemove (state) {
return ['down'].includes(state)
}
export function canChangeCluster (state) {
return ['down'].includes(state)
}
export function canChangeCd (state) {
return ['up'].includes(state)
}
export function canDeleteDisk (state) {
return ['down'].includes(state)
}
export function canExternalService (state, fqdn) {
return fqdn ? canRestart(state) : false
}
|
Correct CSS class name typo | import React from 'react/addons';
import Backbone from 'backbone';
import Router from 'react-router';
export default React.createClass({
displayName: "Name",
propTypes: {
provider: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
render: function () {
let provider = this.props.provider;
return (
<div className="row">
<h1>{provider.get('name')}</h1>
<Router.Link className="btn btn-default" to="all-providers" >
<span className="glyphicon glyphicon-arrow-left"> </span>
{" Back to All Providers" }
</Router.Link>
</div>
);
}
});
| import React from 'react/addons';
import Backbone from 'backbone';
import Router from 'react-router';
export default React.createClass({
displayName: "Name",
propTypes: {
provider: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
render: function () {
let provider = this.props.provider;
return (
<div className="row">
<h1>{provider.get('name')}</h1>
<Router.Link className=" btn btn-default" to = "all-providers" >
<span className="glyphico glyphicon-arrow-left"> </span>
{" Back to All Providers" }
</Router.Link>
</div>
);
}
});
|
Add warning when no .env file found | /**
* Load environment variables from .env for local development.
* If no .env file is to be found at
*/
const path = require('path')
const chalk = require('chalk')
const env = require('dotenv').config()
if (env.error) {
console.warn(chalk.yellow(`No config file was found at ${env.error.path}`))
} else {
console.info(chalk.green('Environment variables loaded from .env:'))
console.info(chalk.grey(JSON.stringify(env, null, 2)))
}
module.exports = {
port: process.env.PORT || 4000,
host: process.env.HOST || 'localhost',
env: process.env.NODE_ENV || 'development',
database_url: process.env.DATABASE_URL,
sentry_dsn: process.env.SENTRY_DSN,
}
| /**
* Load environment variables from .env for local development.
* If no .env file is to be found at
*/
// const path = require('path')
// const chalk = require('chalk')
// const env = require('dotenv').config()
// if (env.error) {
// console.warn(chalk.yellow(`No config file was found at ${env.error.path}`))
// } else {
// console.info(chalk.green('Environment variables loaded from .env:'))
// console.info(chalk.grey(JSON.stringify(env, null, 2)))
// }
module.exports = {
port: process.env.PORT || 4000,
host: process.env.HOST || 'localhost',
env: process.env.NODE_ENV || 'development',
database_url: process.env.DATABASE_URL,
sentry_dsn: process.env.SENTRY_DSN,
}
|
Change name function generate on tick | // Cron.js - in api/services
"use strict";
const CronJob = require('cron').CronJob;
const _ = require('lodash');
const crons = [];
module.exports = {
start: () => {
sails.config.scientilla.crons.forEach(cron => {
crons.push(new CronJob(cron.time, generateOnTick(cron), null, false, 'Europe/Rome'))
});
crons.forEach(cron => cron.start());
},
stop: () => {
crons.forEach(cron => cron.stop());
}
};
function generateOnTick(cron) {
return async function () {
if (!cron.enabled) {
return;
}
sails.log.info('Cron ' + cron.name + ' started at ' + new Date().toISOString());
try{
await GruntTaskRunner.run('cron:' + cron.name);
} catch(e) {
sails.log.debug(e);
}
sails.log.info('Cron ' + cron.name + ' finished at ' + new Date().toISOString());
}
} | // Cron.js - in api/services
"use strict";
const CronJob = require('cron').CronJob;
const _ = require('lodash');
const crons = [];
module.exports = {
start: () => {
sails.config.scientilla.crons.forEach(cron => {
crons.push(new CronJob(cron.time, onTick(cron), null, false, 'Europe/Rome'))
});
crons.forEach(cron => cron.start());
},
stop: () => {
crons.forEach(cron => cron.stop());
}
};
function onTick(cron) {
return async function () {
if (!cron.enabled) {
return;
}
sails.log.info('Cron ' + cron.name + ' started at ' + new Date().toISOString());
await GruntTaskRunner.run('cron:' + cron.name);
sails.log.info('Cron ' + cron.name + ' finished at ' + new Date().toISOString());
}
} |
Add 'six' to the install requirements | from __future__ import absolute_import
import subprocess
from setuptools import setup
try:
pandoc = subprocess.Popen(['pandoc', 'README.md', '--to', 'rst'],
stdout=subprocess.PIPE)
readme = str(pandoc.communicate()[0])
except OSError:
with open('README.md') as f:
readme = f.read()
setup(
name="notedown",
version="1.3.1",
description="Convert markdown to IPython notebook.",
long_description=readme,
packages=['notedown'],
author="Aaron O'Leary",
author_email='dev@aaren.me',
license='BSD 2-Clause',
url='http://github.com/aaren/notedown',
install_requires=['ipython[nbconvert] >= 3.0', 'pandoc-attributes', 'six'],
entry_points={'console_scripts': ['notedown = notedown:cli', ]},
package_dir={'notedown': 'notedown'},
package_data={'notedown': ['templates/markdown.tpl']},
include_package_data=True,
)
| from __future__ import absolute_import
import subprocess
from setuptools import setup
try:
pandoc = subprocess.Popen(['pandoc', 'README.md', '--to', 'rst'],
stdout=subprocess.PIPE)
readme = str(pandoc.communicate()[0])
except OSError:
with open('README.md') as f:
readme = f.read()
setup(
name="notedown",
version="1.3.1",
description="Convert markdown to IPython notebook.",
long_description=readme,
packages=['notedown'],
author="Aaron O'Leary",
author_email='dev@aaren.me',
license='BSD 2-Clause',
url='http://github.com/aaren/notedown',
install_requires=['ipython[nbconvert] >= 3.0', 'pandoc-attributes'],
entry_points={'console_scripts': ['notedown = notedown:cli', ]},
package_dir={'notedown': 'notedown'},
package_data={'notedown': ['templates/markdown.tpl']},
include_package_data=True,
)
|
Send email notifications in asynchronous mode
Each mail notification is done on a thread in order to not block the main thread
of the web app. | # -*- coding: utf-8 -*-
from flask import render_template,g
from flask.ext.mail import Message
from app import mail, db
from .models import User
from config import MAIL_SENDER
from threading import Thread
from app import app
# Send mail into a dedicated thread in order to avoir the web app to wait
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
# Wrapper function for sending mails using flask-mail plugin
def send_email(subject, sender, recipients, text_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
# Function which sends notifications to users when a movie is added
def add_movie_notification(movie):
users = User.query.all()
you_user = False
for cur_user in users:
# Check if the cur_user is the logged user who added the movie
# in order to change the mail text
if cur_user.id==g.user.id:
you_user=True
send_email('[Cineapp] - Ajout d\'un film' , MAIL_SENDER,[ cur_user.email ] ,
render_template('add_movie_notification.txt', dest_user=cur_user, add_user=g.user,movie=movie,you_user=you_user))
| # -*- coding: utf-8 -*-
from flask import render_template,g
from flask.ext.mail import Message
from app import mail, db
from .models import User
from config import MAIL_SENDER
# Wrapper function for sending mails using flask-mail plugin
def send_email(subject, sender, recipients, text_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
mail.send(msg)
def add_movie_notification(movie):
users = User.query.all()
you_user = False
for cur_user in users:
# Check if the cur_user is the logged user who added the movie
# in order to change the mail text
if cur_user.id==g.user.id:
you_user=True
send_email('[Cineapp] - Ajout d\'un film' , MAIL_SENDER,[ cur_user.email ] ,
render_template('add_movie_notification.txt', dest_user=cur_user, add_user=g.user,movie=movie,you_user=you_user))
|
Fix error reporting on test. | package gorand
import (
"testing"
)
func TestID(t *testing.T) {
id, err := ID()
if err != nil {
t.Error(err.Error())
}
if len(id) != 128 {
t.Error("Length of UUID isn't 128")
}
}
func TestUUID(t *testing.T) {
uuid, err := UUID()
if err != nil {
t.Error(err.Error())
}
if len(uuid) != 36 {
t.Error("Length of UUID isn't 36")
}
}
func TestMarshalUUID(t *testing.T) {
uuid, err := UUID()
if err != nil {
t.Error(err.Error())
}
m, err := UnmarshalUUID(uuid)
if err != nil {
t.Error(err.Error())
}
u, err := MarshalUUID(m)
if err != nil {
t.Error(err.Error())
}
if u != uuid {
t.Errorf("%s != %s after Unmarshal and Marshal", u, uuid)
}
}
func BenchmarkID(b *testing.B) {
for n := 0; n < b.N; n++ {
ID()
}
}
func BenchmarkUUID(b *testing.B) {
for n := 0; n < b.N; n++ {
UUID()
}
}
| package gorand
import (
"testing"
)
func TestID(t *testing.T) {
id, err := ID()
if err != nil {
t.Error(err.Error())
}
if len(id) != 128 {
t.Error("Length of UUID isn't 128")
}
}
func TestUUID(t *testing.T) {
uuid, err := UUID()
if err != nil {
t.Error(err.Error())
}
if len(uuid) != 36 {
t.Error("Length of UUID isn't 36")
}
}
func TestMarshalUUID(t *testing.T) {
uuid, err := UUID()
if err != nil {
t.Error(err.Error())
}
m, err := UnmarshalUUID(uuid)
if err != nil {
t.Error(err.Error())
}
u, err := MarshalUUID(m)
if err != nil {
t.Error(err.Error())
}
if u != uuid {
t.Errorf("%s != %s after Unmarshal and Marshal")
}
}
func BenchmarkID(b *testing.B) {
for n := 0; n < b.N; n++ {
ID()
}
}
func BenchmarkUUID(b *testing.B) {
for n := 0; n < b.N; n++ {
UUID()
}
}
|
Add prop test to Foo | import React from "react";
import toJson from "enzyme-to-json";
import { shallow, mount, render } from "enzyme";
import Foo from "../Foo";
describe("A suite", function() {
it("should render without throwing an error", function() {
const info = "Bar";
expect(
shallow(<Foo loading info={info} />).contains(
<div className="foo">{info}</div>
)
).toBe(true);
});
it('should be selectable by class "foo"', function() {
expect(shallow(<Foo loading />).is(".foo")).toBe(true);
});
it("should mount in a full DOM", function() {
expect(mount(<Foo loading />).find(".foo").length).toBe(1);
});
it("should render to static HTML", function() {
const info = "Bar";
expect(render(<Foo loading info={info} />).text()).toEqual(info);
});
it("snapshot check", () => {
const wrapper = shallow(<Foo loading />);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("Should update Foo props", () => {
const info = "Foo";
const wrapper = mount(<Foo loading info="Bar" />);
expect(wrapper.setState({ info }).text()).toEqual(info);
});
});
| import React from "react";
import toJson from "enzyme-to-json";
import { shallow, mount, render } from "enzyme";
import Foo from "../Foo";
describe("A suite", function() {
it("should render without throwing an error", function() {
const info = "Bar";
expect(
shallow(<Foo loading info={info} />).contains(
<div className="foo">{info}</div>
)
).toBe(true);
});
it('should be selectable by class "foo"', function() {
expect(shallow(<Foo loading />).is(".foo")).toBe(true);
});
it("should mount in a full DOM", function() {
expect(mount(<Foo loading />).find(".foo").length).toBe(1);
});
it("should render to static HTML", function() {
const info = "Bar";
expect(render(<Foo loading info={info} />).text()).toEqual(info);
});
it("snapshot check", () => {
const wrapper = shallow(<Foo loading />);
expect(toJson(wrapper)).toMatchSnapshot();
});
});
|
Fix failing test - Photo ID Guide to Larvae at Hydrothermal Vents. | <?php
namespace php_active_record;
require_library('connectors/HydrothermalVentLarvaeAPI');
class test_connector_vent_larvae_api extends SimpletestUnitBase
{
function testVentLarvaeAPI()
{
$url = "http://www.whoi.edu/vent-larval-id/MiscSpecies.htm";
//$url = "http://pandanus.eol.org/public/test_resources/MiscSpecies.htm";
$taxa = HydrothermalVentLarvaeAPI::get_larvae_taxa($url, array());
$this->assertTrue(is_array($taxa), 'Taxa should be an array');
$taxon = $taxa["page_taxa"][0];
$this->assertIsA($taxon, 'SchemaTaxon', 'Response should be an array of SchemaTaxon');
$dataObject = $taxon->dataObjects[0];
$this->assertIsA($dataObject, 'SchemaDataObject', 'Taxon should have a data object');
}
}
?> | <?php
namespace php_active_record;
require_library('connectors/HydrothermalVentLarvaeAPI');
class test_connector_vent_larvae_api extends SimpletestUnitBase
{
function testVentLarvaeAPI()
{
//$url = "http://www.whoi.edu/vent-larval-id/MiscSpecies.htm";
$url = "http://pandanus.eol.org/public/test_resources/MiscSpecies.htm";
$taxa = HydrothermalVentLarvaeAPI::get_larvae_taxa($url);
$this->assertTrue(is_array($taxa), 'Taxa should be an array');
$taxon = $taxa[0];
$this->assertIsA($taxon, 'SchemaTaxon', 'Response should be an array of SchemaTaxon');
$dataObject = $taxon->dataObjects[0];
$this->assertIsA($dataObject, 'SchemaDataObject', 'Taxon should have a data object');
}
}
?> |
Split Entry into Income and Expense schemes
Splitting the Entry schema into two seperate schemes allows
us to use different collections to store them, which in turn makes
our work easier later on. | from app import db
from app.mod_auth.model import User
class Category(db.Document):
# The name of the category.
name = db.StringField(required = True)
class Income(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the entry.
description = db.StringField(required = True)
# The owner of the entry.
# Should the owner be deleted, we also want to delete all of his entries.
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
# The category of this entry.
category = db.ReferenceField(Category, required = True)
class Expense(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the expense.
description = db.StringField(required = True)
# The owner of the expense.
# Should the owner be deleted, we also want to delete all of his entries.
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
# The category of this entry.
category = db.ReferenceField(Category, required = True)
class CategoryBudget(db.Document):
# The amount of the budget.
amount = db.DecimalField(precision = 2, required = True)
# The category.
category = db.ReferenceField(Category, required = True)
def sumEntries():
return sum([entry.amount for entry in Entry.objects if entry.amount > 0])
| from app import db
from app.mod_auth.model import User
class Category(db.Document):
# The name of the category.
name = db.StringField(required = True)
class Entry(db.Document):
# The amount of the entry.
amount = db.DecimalField(precision = 2, required = True)
# A short description for the entry.
description = db.StringField(required = True)
# The owner of the entry.
# Should the owner be deleted, we also want to delete all of his entries.
owner = db.ReferenceField(User, reverse_delete_rule = db.CASCADE, required = True)
# The category of this entry.
category = db.ReferenceField(Category, required = True)
class CategoryBudget(db.Document):
# The amount of the budget.
amount = db.DecimalField(precision = 2, required = True)
# The category.
category = db.ReferenceField(Category, required = True)
def sumEntries():
return sum([entry.amount for entry in Entry.objects if entry.amount > 0])
|
Use plan name instead of description | from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
stripe.Plan.create(
amount=100 * settings.PAYMENTS_PLANS[plan]["price"],
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency="usd",
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for %s" % plan
| from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
stripe.Plan.create(
amount=100 * settings.PAYMENTS_PLANS[plan]["price"],
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["description"],
currency="usd",
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for %s" % plan
|
Use the full class name in the registry | <?php
namespace Integrated\Bundle\ContentBundle\Form\Registry;
use Integrated\Common\ContentType\Form\Custom\Type;
use Integrated\Common\ContentType\Form\Custom\Type\Registry;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
/**
* Simple factory for Registry
*
* @author Jeroen van Leeuwen <jeroen@e-active.nl>
*/
class RegistryFactory
{
/**
* @return Registry
*/
public static function create()
{
$registry = new Registry();
// Todo this must be configurable
$text = new Type();
$text
->setType(TextType::class)
->setName('Text')
;
$textarea = new Type();
$textarea
->setType(TextareaType::class)
->setName('Textarea')
;
$registry
->add($text)
->add($textarea)
;
return $registry;
}
}
| <?php
namespace Integrated\Bundle\ContentBundle\Form\Registry;
use Integrated\Common\ContentType\Form\Custom\Type;
use Integrated\Common\ContentType\Form\Custom\Type\Registry;
/**
* Simple factory for Registry
*
* @author Jeroen van Leeuwen <jeroen@e-active.nl>
*/
class RegistryFactory
{
/**
* @return Registry
*/
public static function create()
{
$registry = new Registry();
// Todo this must be configurable
$text = new Type();
$text
->setType('text')
->setName('Text')
;
$textarea = new Type();
$textarea
->setType('textarea')
->setName('Textarea')
;
$registry
->add($text)
->add($textarea)
;
return $registry;
}
}
|
Update myTBA on launch always | package com.thebluealliance.androidclient;
import android.app.Application;
import android.util.Log;
import com.google.android.gms.analytics.Tracker;
import com.thebluealliance.androidclient.accounts.AccountHelper;
import com.thebluealliance.androidclient.background.UpdateMyTBA;
/**
* File created by phil on 7/21/14.
*/
public class TBAAndroid extends Application {
@Override
public void onCreate() {
super.onCreate();
Log.i(Constants.LOG_TAG, "Welcome to The Blue Alliance for Android, v" + BuildConfig.VERSION_NAME);
if(AccountHelper.isAccountSelected(this)){
new UpdateMyTBA(this, true).execute();
}
}
public Tracker getTracker(Analytics.GAnalyticsTracker tracker) {
return Analytics.getTracker(tracker, this);
}
}
| package com.thebluealliance.androidclient;
import android.app.Application;
import android.util.Log;
import com.google.android.gms.analytics.Tracker;
import com.thebluealliance.androidclient.accounts.AccountHelper;
import com.thebluealliance.androidclient.background.UpdateMyTBA;
/**
* File created by phil on 7/21/14.
*/
public class TBAAndroid extends Application {
@Override
public void onCreate() {
super.onCreate();
Log.i(Constants.LOG_TAG, "Welcome to The Blue Alliance for Android, v" + BuildConfig.VERSION_NAME);
if(AccountHelper.isAccountSelected(this)){
new UpdateMyTBA(this, false).execute();
}
}
public Tracker getTracker(Analytics.GAnalyticsTracker tracker) {
return Analytics.getTracker(tracker, this);
}
}
|
Change new_bmi fixture scope to be function level. | import os
import pytest
from scripting.contexts import cd
from . import Bmi, INPUT_FILE
from .utils import all_grids, all_names, out_names, strictly_input_names
@pytest.fixture
def new_bmi(infile=None):
try:
with open('.ROOT_DIR', 'r') as fp:
root_dir = fp.read()
except IOError:
root_dir = '.'
bmi = Bmi()
with cd(root_dir):
bmi.initialize(infile or INPUT_FILE)
return bmi
def pytest_runtest_setup(item):
print 'moving folders', item
# os.chdir('/Users/huttone/git/csdms/bmi-tester/_child_run')
def pytest_generate_tests(metafunc):
if 'gid' in metafunc.fixturenames:
metafunc.parametrize('gid', all_grids(new_bmi()))
elif 'var_name' in metafunc.fixturenames:
metafunc.parametrize('var_name', all_names(new_bmi()))
elif 'in_var_name' in metafunc.fixturenames:
metafunc.parametrize('in_var_name', strictly_input_names(new_bmi()))
elif 'out_var_name' in metafunc.fixturenames:
metafunc.parametrize('out_var_name', out_names(new_bmi()))
| import os
import pytest
from scripting.contexts import cd
from . import Bmi, INPUT_FILE
from .utils import all_grids, all_names, out_names, strictly_input_names
@pytest.fixture(scope='module')
def new_bmi(infile=None):
try:
with open('.ROOT_DIR', 'r') as fp:
root_dir = fp.read()
except IOError:
root_dir = '.'
bmi = Bmi()
with cd(root_dir):
bmi.initialize(infile or INPUT_FILE)
return bmi
def pytest_runtest_setup(item):
print 'moving folders', item
# os.chdir('/Users/huttone/git/csdms/bmi-tester/_child_run')
def pytest_generate_tests(metafunc):
if 'gid' in metafunc.fixturenames:
metafunc.parametrize('gid', all_grids(new_bmi()))
elif 'var_name' in metafunc.fixturenames:
metafunc.parametrize('var_name', all_names(new_bmi()))
elif 'in_var_name' in metafunc.fixturenames:
metafunc.parametrize('in_var_name', strictly_input_names(new_bmi()))
elif 'out_var_name' in metafunc.fixturenames:
metafunc.parametrize('out_var_name', out_names(new_bmi()))
|
Remove "css" from input format | 'use strict';
var Cleaner = require('clean-css');
var defaultCleaner = new Cleaner();
var Promise = require('promise');
exports.name = 'clean-css';
exports.inputFormats = ['clean-css', 'cssmin'];
exports.outputFormat = 'css';
function getCleaner (options) {
if (!options ||
(typeof options === 'object' && Object.keys(options).length === 0)) {
return defaultCleaner;
} else {
return new Cleaner(options);
}
}
exports.render = function (str, options) {
return getCleaner(options).minify(str).styles;
};
exports.renderAsync = function (str, options) {
return new Promise(function (fulfill, reject) {
getCleaner(options).minify(str, function (err, minified) {
if (err) {
reject(err);
}
else {
fulfill(minified.styles);
}
});
});
};
| 'use strict';
var Cleaner = require('clean-css');
var defaultCleaner = new Cleaner();
var Promise = require('promise');
exports.name = 'clean-css';
exports.inputFormats = ['clean-css', 'css', 'cssmin'];
exports.outputFormat = 'css';
function getCleaner (options) {
if (!options ||
(typeof options === 'object' && Object.keys(options).length === 0)) {
return defaultCleaner;
} else {
return new Cleaner(options);
}
}
exports.render = function (str, options) {
return getCleaner(options).minify(str).styles;
};
exports.renderAsync = function (str, options) {
return new Promise(function (fulfill, reject) {
getCleaner(options).minify(str, function (err, minified) {
if (err) {
reject(err);
}
else {
fulfill(minified.styles);
}
});
});
};
|
Fix bug where user could not be found
This problem only occured when a request tried to find the user right
after it had been created. | from google.appengine.api import users
from google.appengine.ext import db
from model import User
latest_signup = None
@db.transactional
def create_user(google_user):
global latest_signup
user = User(
google_user=google_user
)
user.put()
latest_signup = user
return user
def get_current_user():
google_user = users.get_current_user()
if latest_signup != None and google_user == latest_signup.google_user:
return latest_signup
user = get_user_model_for(google_user)
return user
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get() | from google.appengine.api import users
from google.appengine.ext import db
from model import User
@db.transactional
def create_user(google_user):
user = User(
google_user=google_user
)
user.put()
return user
def get_current_user():
google_user = users.get_current_user()
user = get_user_model_for(google_user)
return user
def get_user_model_for(google_user=None):
return User.all().filter('google_user =', google_user).get()
def get_user_model_by_id_or_nick(id_or_nick):
if id_or_nick.isdigit():
return User.get_by_id(int(id_or_nick))
else:
return User.all().filter('nickname_lower = ', id_or_nick.lower()).get() |
Encrypt password before saving user | from index import db, brcypt
class UserModel(db.Model):
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String(80), unique=True, nullable=False)
fullname = db.Column(db.String(80), unique=True, nullable=False)
initials = db.Column(db.String(10), unique=True, nullable=False)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(80), unique=True, nullable=False)
application = db.Column(db.String(80), unique=True, nullable=False)
def __init__(self, name, fullname, initials, email, password, application):
self.name = name
self.fullname = fullname
self.initials = initials
self.email = email
self.application = application
self.set_password(password)
def __repr__(self):
return self.name
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def check_password(self, password):
return bcrypt.check_password_hash(self.password, password) | from index import db
class UserModel(db.Model):
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String(80), unique=True, nullable=False)
fullname = db.Column(db.String(80), unique=True, nullable=False)
initials = db.Column(db.String(10), unique=True, nullable=False)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(80), unique=True, nullable=False)
application = db.Column(db.String(80), unique=True, nullable=False)
def __init__(self, name, fullname, initials, email, password, application):
self.name = name
self.fullname = fullname
self.initials = initials
self.email = email
self.password = password
self.application = application
def __repr__(self):
return self.name |
Exclude forms partial as well. | // Check SCSS for code quality
module.exports = function(grunt) {
grunt.config('scsslint', {
allFiles: [
'scss/**/*.scss',
],
options: {
bundleExec: false,
colorizeOutput: true,
config: '.scss-lint.yml',
exclude: [
'scss/core/_normalize.scss',
'scss/iconfont/*',
'scss/main/_oldie.scss',
'scss/mixins/_type.scss',
'scss/mixins/_units.scss',
'scss/modules/_forms.scss',
'scss/modules/_images.scss'
],
reporterOutput: null
},
});
grunt.loadNpmTasks('grunt-scss-lint');
};
| // Check SCSS for code quality
module.exports = function(grunt) {
grunt.config('scsslint', {
allFiles: [
'scss/**/*.scss',
],
options: {
bundleExec: false,
colorizeOutput: true,
config: '.scss-lint.yml',
exclude: [
'scss/core/_normalize.scss',
'scss/iconfont/*',
'scss/main/_oldie.scss',
'scss/mixins/_type.scss',
'scss/mixins/_units.scss',
'scss/modules/_images.scss'
],
reporterOutput: null
},
});
grunt.loadNpmTasks('grunt-scss-lint');
};
|
Change StoreWatchMixin to watch in componentDidMount
See #88 | var _each = require("lodash-node/modern/collections/forEach");
var StoreWatchMixin = function() {
var storeNames = Array.prototype.slice.call(arguments);
return {
componentDidMount: function() {
var flux = this.props.flux || this.context.flux;
_each(storeNames, function(store) {
flux.store(store).on("change", this._setStateFromFlux);
}, this);
},
componentWillUnmount: function() {
var flux = this.props.flux || this.context.flux;
_each(storeNames, function(store) {
flux.store(store).removeListener("change", this._setStateFromFlux);
}, this);
},
_setStateFromFlux: function() {
if(this.isMounted()) {
this.setState(this.getStateFromFlux());
}
},
getInitialState: function() {
return this.getStateFromFlux();
}
};
};
StoreWatchMixin.componentWillMount = function() {
throw new Error("Fluxxor.StoreWatchMixin is a function that takes one or more " +
"store names as parameters and returns the mixin, e.g.: " +
"mixins[Fluxxor.StoreWatchMixin(\"Store1\", \"Store2\")]");
};
module.exports = StoreWatchMixin;
| var _each = require("lodash-node/modern/collections/forEach");
var StoreWatchMixin = function() {
var storeNames = Array.prototype.slice.call(arguments);
return {
componentWillMount: function() {
var flux = this.props.flux || this.context.flux;
_each(storeNames, function(store) {
flux.store(store).on("change", this._setStateFromFlux);
}, this);
},
componentWillUnmount: function() {
var flux = this.props.flux || this.context.flux;
_each(storeNames, function(store) {
flux.store(store).removeListener("change", this._setStateFromFlux);
}, this);
},
_setStateFromFlux: function() {
if(this.isMounted()) {
this.setState(this.getStateFromFlux());
}
},
getInitialState: function() {
return this.getStateFromFlux();
}
};
};
StoreWatchMixin.componentWillMount = function() {
throw new Error("Fluxxor.StoreWatchMixin is a function that takes one or more " +
"store names as parameters and returns the mixin, e.g.: " +
"mixins[Fluxxor.StoreWatchMixin(\"Store1\", \"Store2\")]");
};
module.exports = StoreWatchMixin;
|
Update eBay script to handle https | // ==UserScript==
// @name eBay - Hilight Items With Bids
// @namespace http://mathemaniac.org
// @include http://*.ebay.*/*
// @include https://*.ebay.*/*
// @grant none
// @version 2.3.4
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @description Hilights items that have bids with a red border and yellow background.
// ==/UserScript==
// Based on http://userscripts.org/users/126140 v.2.2.1
// Updated for newer eBay layout.
$(function() {
$(".lvprices .lvformat").each(function() {
// Skip listings with no bids.
if ($(this).text().match(/\b0 bids/) || !$(this).text().match(/\d+ bids?/)) return;
$(this).closest('li[listingid]').css({
"border": "3px solid red",
"background-color": "yellow"
});
});
});
| // ==UserScript==
// @name eBay - Hilight Items With Bids
// @namespace http://mathemaniac.org
// @include http://*.ebay.*/*
// @grant none
// @version 2.3.3
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @description Hilights items that have bids with a red border and yellow background.
// ==/UserScript==
// Based on http://userscripts.org/users/126140 v.2.2.1
// Updated for newer eBay layout.
$('document').ready(function() {
$(".lvprices .lvformat").each(function() {
// Skip listings with no bids.
if ($(this).text().match(/\b0 bids/) || !$(this).text().match(/\d+ bids?/)) return;
$(this).closest('li[listingid]').css({
"border": "3px solid red",
"background-color": "yellow"
});
});
});
|
Add echoPermission option in PopoverModel |
// ----------------------------------------------------------------
// Popover Class
class PopoverModel extends CommonModel {
constructor({
name = 'Popover',
selector = null,
help = 'popover',
trigger = 'hover'
} = {})
{
super({
name: name,
echoPermission: false
});
this.NAME = name;
this.SELECTOR = selector;
this.HELP = help;
this.TRIGGER = trigger;
}
}
class PopoverView extends CommonView {
constructor(_model = new PopoverModel()) {
super(_model);
this.setPopover();
}
setPopover() {
if (this.model.SELECTOR != null) {
$(this.model.SELECTOR).attr('data-toggle', 'popover');
$(this.model.SELECTOR).attr('data-content', this.model.HELP);
$(this.model.SELECTOR).attr('data-trigger', this.model.TRIGGER);
$(this.model.SELECTOR).popover();
}
}
}
// ----------------------------------------------------------------
// Controllers
class PopoverController extends CommonController {
constructor(_obj) {
super({
name: 'Popover Controller'
});
this.model = new PopoverModel(_obj);
this.view = new PopoverView(this.model);
}
}
|
// ----------------------------------------------------------------
// Popover Class
class PopoverModel extends CommonModel {
constructor({
name = 'Popover',
selector = null,
help = 'popover',
trigger = 'hover'
} = {})
{
super({
name: name
});
this.NAME = name;
this.SELECTOR = selector;
this.HELP = help;
this.TRIGGER = trigger;
}
}
class PopoverView extends CommonView {
constructor(_model = new PopoverModel()) {
super(_model);
this.setPopover();
}
setPopover() {
if (this.model.SELECTOR != null) {
$(this.model.SELECTOR).attr('data-toggle', 'popover');
$(this.model.SELECTOR).attr('data-content', this.model.HELP);
$(this.model.SELECTOR).attr('data-trigger', this.model.TRIGGER);
$(this.model.SELECTOR).popover();
}
}
}
// ----------------------------------------------------------------
// Controllers
class PopoverController extends CommonController {
constructor(_obj) {
super({
name: 'Popover Controller'
});
this.model = new PopoverModel(_obj);
this.view = new PopoverView(this.model);
}
}
|
Update the long_description with README.rst | import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.6",
author = "Samuel Hoffstaetter",
author_email="",
maintainer = "Matthias Lee",
maintainer_email = "pytesseract@madmaze.net",
description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
long_description = longDesc,
license = "GPLv3",
keywords = "python-tesseract OCR Python",
url = "https://github.com/madmaze/python-tesseract",
packages=['pytesseract'],
package_dir={'pytesseract': 'src'},
package_data = {'pytesseract': ['*.png','*.jpg']},
entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
| import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.md"):
longDesc = open("README.md").read().strip()
setup(
name = "pytesseract",
version = "0.1.6",
author = "Samuel Hoffstaetter",
author_email="",
maintainer = "Matthias Lee",
maintainer_email = "pytesseract@madmaze.net",
description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
long_description = longDesc,
license = "GPLv3",
keywords = "python-tesseract OCR Python",
url = "https://github.com/madmaze/python-tesseract",
packages=['pytesseract'],
package_dir={'pytesseract': 'src'},
package_data = {'pytesseract': ['*.png','*.jpg']},
entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
|
Correct drop table referencing wrong table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ConstrainComments extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
//
Schema::table('comments',function($table)
{
$table->foreign('userID')->references('userID')->on('users');
$table->foreign('workID')->references('workID')->on('works');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::table('comments', function ($table) {
$table->dropForeign('comments_userID_foreign');
$table->dropForeign('comments_workID_foreign');
});
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ConstrainComments extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
//
Schema::table('comments',function($table)
{
$table->foreign('userID')->references('userID')->on('users');
$table->foreign('workID')->references('workID')->on('works');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::table('users', function ($table) {
$table->dropForeign('comments_userID_foreign');
$table->dropForeign('comments_workID_foreign');
});
}
}
|
[BlockStorage] Attach Volume
Add the type. | <?php
namespace wappr\digitalocean\Requests\BlockStorageActions;
use wappr\digitalocean\Helpers\RegionsHelper;
use wappr\digitalocean\RequestContract;
/**
* Class AttachVolumeRequest.
*
* Attach a volume to a Droplet.
*/
class AttachVolumeRequest extends RequestContract
{
public $type = 'attach';
public $volume_id;
public $droplet_id;
public $region;
public function __construct($volume_id, $droplet_id)
{
$this->volume_id = $volume_id;
$this->droplet_id = $droplet_id;
}
public function setRegion($region)
{
if (!RegionsHelper::check($region)) {
throw new \InvalidArgumentException('Region must be a slug.', 200);
}
$this->region = $region;
}
}
| <?php
namespace wappr\digitalocean\Requests\BlockStorageActions;
use wappr\digitalocean\Helpers\RegionsHelper;
use wappr\digitalocean\RequestContract;
/**
* Class AttachVolumeRequest.
*
* Attach a volume to a Droplet.
*/
class AttachVolumeRequest extends RequestContract
{
public $volume_id;
public $droplet_id;
public $region;
public function __construct($volume_id, $droplet_id)
{
$this->volume_id = $volume_id;
$this->droplet_id = $droplet_id;
}
public function setRegion($region)
{
if (!RegionsHelper::check($region)) {
throw new \InvalidArgumentException('Region must be a slug.', 200);
}
$this->region = $region;
}
}
|
Fix WidgetWithScript to accept renderer kwarg | from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
class WidgetWithScript(Widget):
def render_html(self, name, value, attrs):
"""Render the HTML (non-JS) portion of the field markup"""
return super().render(name, value, attrs)
def render(self, name, value, attrs=None, renderer=None):
# no point trying to come up with sensible semantics for when 'id' is missing from attrs,
# so let's make sure it fails early in the process
try:
id_ = attrs['id']
except (KeyError, TypeError):
raise TypeError("WidgetWithScript cannot be rendered without an 'id' attribute")
widget_html = self.render_html(name, value, attrs)
js = self.render_js_init(id_, name, value)
out = '{0}<script>{1}</script>'.format(widget_html, js)
return mark_safe(out)
def render_js_init(self, id_, name, value):
return ''
| from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
class WidgetWithScript(Widget):
def render_html(self, name, value, attrs):
"""Render the HTML (non-JS) portion of the field markup"""
return super().render(name, value, attrs)
def render(self, name, value, attrs=None):
# no point trying to come up with sensible semantics for when 'id' is missing from attrs,
# so let's make sure it fails early in the process
try:
id_ = attrs['id']
except (KeyError, TypeError):
raise TypeError("WidgetWithScript cannot be rendered without an 'id' attribute")
widget_html = self.render_html(name, value, attrs)
js = self.render_js_init(id_, name, value)
out = '{0}<script>{1}</script>'.format(widget_html, js)
return mark_safe(out)
def render_js_init(self, id_, name, value):
return ''
|
Revert "Revert "refactor: add progress reporter back in for karma tests""
This reverts commit f4855a955decace888d1291eab1b09b076b51a2f. | module.exports = function (config) {
config.set({
basePath: './',
frameworks: ['jasmine'],
browsers: ['Chrome', 'Firefox', 'PhantomJS'],
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'dist/ng-restful-collection.js',
'tests/**/*.js'
],
captureTimeout: 60000,
colors: true,
logLevel: config.LOG_INFO,
port: 9876,
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-coverage'
],
runnerPort: 9100,
singleRun: true,
autoWatch: false,
coverageReporter: {
type: 'lcov',
dir: 'coverage/'
},
preprocessors: {
'dist/ng-restful-collection.js': ['coverage']
},
reporters: ['progress', 'coverage']
});
}; | module.exports = function (config) {
config.set({
basePath: './',
frameworks: ['jasmine'],
browsers: ['Chrome', 'Firefox', 'PhantomJS'],
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'dist/ng-restful-collection.js',
'tests/**/*.js'
],
captureTimeout: 60000,
colors: true,
logLevel: config.LOG_INFO,
port: 9876,
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-coverage'
],
runnerPort: 9100,
singleRun: true,
autoWatch: false,
coverageReporter: {
type: 'lcov',
dir: 'coverage/'
},
preprocessors: {
'dist/ng-restful-collection.js': ['coverage']
},
reporters: ['coverage']
});
}; |
Add benchmark test for COWList_Get | package gorocksdb
import (
"fmt"
"sync"
"testing"
"github.com/facebookgo/ensure"
)
func TestCOWList(t *testing.T) {
cl := NewCOWList()
cl.Append("hello")
cl.Append("world")
cl.Append("!")
ensure.DeepEqual(t, cl.Get(0), "hello")
ensure.DeepEqual(t, cl.Get(1), "world")
ensure.DeepEqual(t, cl.Get(2), "!")
}
func TestCOWListMT(t *testing.T) {
cl := NewCOWList()
expectedRes := make([]int, 3)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func(v int) {
defer wg.Done()
index := cl.Append(v)
expectedRes[index] = v
}(i)
}
wg.Wait()
for i, v := range expectedRes {
ensure.DeepEqual(t, cl.Get(i), v)
}
}
func BenchmarkCOWList_Get(b *testing.B) {
cl := NewCOWList()
for i := 0; i < 10; i++ {
cl.Append(fmt.Sprintf("helloworld%d", i))
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = cl.Get(i % 10).(string)
}
}
| package gorocksdb
import (
"sync"
"testing"
"github.com/facebookgo/ensure"
)
func TestCOWList(t *testing.T) {
cl := NewCOWList()
cl.Append("hello")
cl.Append("world")
cl.Append("!")
ensure.DeepEqual(t, cl.Get(0), "hello")
ensure.DeepEqual(t, cl.Get(1), "world")
ensure.DeepEqual(t, cl.Get(2), "!")
}
func TestCOWListMT(t *testing.T) {
cl := NewCOWList()
expectedRes := make([]int, 3)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func(v int) {
defer wg.Done()
index := cl.Append(v)
expectedRes[index] = v
}(i)
}
wg.Wait()
for i, v := range expectedRes {
ensure.DeepEqual(t, cl.Get(i), v)
}
}
|
Add test for api error response | var fs = require('fs');
var config = require('../config');
var schemaText = fs.readFileSync(config.schemapath);
var schema = JSON.parse(schemaText.toString());
schema.host = 'localhost';
schema.port = '3000'
schema.version = undefined;
var Api = require('../lib/api').Api;
var api = new Api({
schema: schema,
format: 'json',
logger: require('../lib/logger')
});
var expect = require('chai').expect;
describe('api', function () {
it('should get a release by id', function (done) {
var releases = new api.Releases();
releases.getDetails({ releaseId: 1192901 }, function (err, data) {
expect(data.release.title).to.equal('Wasting Light');
done();
});
});
it('should handle bad xml from the api', function (done) {
var releases = new api.Releases();
releases.getDetails({ releaseId: 'error' }, function (err, data) {
//Currently dies because xml2js never calls back..
//https://github.com/Leonidas-from-XIV/node-xml2js/issues/51
expect(err).to.not.equal(undefined);
done();
});
});
it('should handle missing resources from the api', function (done) {
var releases = new api.Releases();
releases.getDetails({ releaseId: 'missing' }, function (err, data) {
expect(err).to.not.equal(undefined);
expect(err.code).to.equal('2001');
done();
});
});
});
| var fs = require('fs');
var config = require('../config');
var schemaText = fs.readFileSync(config.schemapath);
var schema = JSON.parse(schemaText.toString());
schema.host = 'localhost';
schema.port = '3000'
schema.version = undefined;
var Api = require('../lib/api').Api;
var api = new Api({
schema: schema,
format: 'json',
logger: require('../lib/logger')
});
var expect = require('chai').expect;
describe('api', function () {
it('should get a release by id', function (done) {
var releases = new api.Releases();
releases.getDetails({ releaseId: 1192901 }, function (err, data) {
expect(data.release.title).to.equal('Wasting Light');
done();
});
});
it('should handle bad xml from the api', function (done) {
var releases = new api.Releases();
releases.getDetails({ releaseId: 'error' }, function (err, data) {
//Currently dies because xml2js never calls back..
//https://github.com/Leonidas-from-XIV/node-xml2js/issues/51
expect(err).to.not.equal(undefined);
done();
});
});
});
|
Fix return type in sitemap object type interface | <?php
namespace wcf\system\sitemap\object;
use wcf\data\DatabaseObject;
use wcf\data\DatabaseObjectList;
/**
* Interface for sitemap objects.
*
* @author Joshua Ruesweg
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Sitemap\Object
* @since 3.1
*/
interface ISitemapObjectObjectType {
/**
* Returns the DatabaseObject class name for the sitemap object.
*
* @return string
*/
public function getObjectClass();
/**
* Returns the DatabaseObjectList class name for the sitemap object.
*
* @return string
*/
public function getObjectListClass();
/**
* Returns the DatabaseObjectList for the sitemap object.
*
* @return DatabaseObjectList
*/
public function getObjectList();
/**
* Returns the database column, which represents the last modified date.
* If there isn't any column, this method should return `null`.
*
* @return string|null
*/
public function getLastModifiedColumn();
/**
* Returns the permission for a guest to view a certain object for this object type.
*
* @param DatabaseObject $object
* @return boolean
*/
public function canView(DatabaseObject $object);
}
| <?php
namespace wcf\system\sitemap\object;
use wcf\data\DatabaseObject;
/**
* Interface for sitemap objects.
*
* @author Joshua Ruesweg
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Sitemap\Object
* @since 3.1
*/
interface ISitemapObjectObjectType {
/**
* Returns the DatabaseObject class name for the sitemap object.
*
* @return string
*/
public function getObjectClass();
/**
* Returns the DatabaseObjectList class name for the sitemap object.
*
* @return string
*/
public function getObjectListClass();
/**
* Returns the DatabaseObjectList for the sitemap object.
*
* @return string
*/
public function getObjectList();
/**
* Returns the database column, which represents the last modified date.
* If there isn't any column, this method should return `null`.
*
* @return string|null
*/
public function getLastModifiedColumn();
/**
* Returns the permission for a guest to view a certain object for this object type.
*
* @param DatabaseObject $object
* @return boolean
*/
public function canView(DatabaseObject $object);
}
|
Add test for inc page num, good format | import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-001'}
return sample_page
def test_build_img_path(sample_page_bad_format):
chapter = sample_page_bad_format["chapter"]
page = sample_page_bad_format["page"]
expected_output = "/chapter1/3"
assert utils.build_img_path(chapter,page) == expected_output
def test_increment_page_number_bad_format(sample_page_bad_format):
with pytest.raises(ValueError):
current_page = utils.build_img_path(sample_page_bad_format["chapter"],
sample_page_bad_format["page"])
utils.increment_page_number(current_page)
def test_increment_page_number_good_format(sample_page_good_format):
chapter = sample_page_good_format["chapter"]
page = sample_page_good_format["page"]
current_page = utils.build_img_path(chapter, page)
next_page = utils.increment_page_number(current_page)
expected_output = '/manga_ch1/x_v001-002'
assert next_page == expected_output
| import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-001'}
return sample_page
def test_build_img_path(sample_page_bad_format):
chapter = sample_page_bad_format["chapter"]
page = sample_page_bad_format["page"]
expected_output = "/chapter1/3"
assert utils.build_img_path(chapter,page) == expected_output
def test_increment_page_number_bad_formate(sample_page_bad_format):
with pytest.raises(ValueError):
current_page = utils.build_img_path(sample_page_bad_format["chapter"],
sample_page_bad_format["page"])
utils.increment_page_number(current_page)
|
Fix bug from last commit. | """
Common methods for getting data from the backend.
These methods are intended to be used by both views.py, which should define
only pages, and xhr_handlers.py, which are intended to respond to AJAX
requests.
"""
from main.model_views import CastVariantView
from main.model_views import MeltedVariantView
from variants.variant_filter import get_variants_that_pass_filter
def lookup_variants(reference_genome, combined_filter_string, is_melted):
"""Lookup the Variants that match the filter specified in the params.
Returns:
List of CastVariantView or MeltedVariantView objects.
"""
# Apply the filters.
filter_result = get_variants_that_pass_filter(
combined_filter_string, reference_genome)
variant_list = filter_result.variant_set
variant_id_to_metadata_dict = filter_result.variant_id_to_metadata_dict
# Convert to appropriate view objects.
if is_melted:
melted_variant_list = []
for variant in variant_list:
melted_variant_list.extend(
MeltedVariantView.variant_as_melted_list(variant,
variant_id_to_metadata_dict))
return melted_variant_list
else:
return [CastVariantView.variant_as_cast_view(variant,
variant_id_to_metadata_dict) for variant in variant_list]
| """
Common methods for getting data from the backend.
These methods are intended to be used by both views.py, which should define
only pages, and xhr_handlers.py, which are intended to respond to AJAX
requests.
"""
from main.model_views import CastVariantView
from main.model_views import MeltedVariantView
from variants.variant_filter import get_variants_that_pass_filter
def lookup_variants(reference_genome, combined_filter_string, is_melted):
"""Lookup the Variants that match the filter specified in the params.
Returns:
List of CastVariantView or MeltedVariantView objects.
"""
# Apply the filters.
filter_result = get_variants_that_pass_filter(
combined_filter_string, reference_genome)
variant_list = filter_result.variant_set
variant_id_to_metadata_dict = filter_result.variant_id_to_metadata_dict
# Convert to appropriate view objects.
if is_melted:
melted_variant_list = []
for variant in variant_list:
melted_variant_list.extend(
MeltedVariantView.variant_as_melted_list(variant,
variant_id_to_metadata_dict))
return melted_variant_list
else:
return [CastVariantView(variant,
variant_id_to_metadata_dict) for variant in variant_list]
|
Move data into owner gdb | #!/usr/bin/env python
# * coding: utf8 *
'''
BemsPallet.py
A module that contains a pallet to update the querable layers behind our UTM basemaps
'''
from forklift.models import Pallet
from os.path import join
class BemsPallet(Pallet):
def __init__(self):
super(BemsPallet, self).__init__()
self.arcgis_services = [('BEMS/Boundaries', 'MapServer')]
self.destination_workspace = 'C:\\Scheduled\\Staging\\Health.gdb'
self.copy_data = [self.destination_workspace]
def build(self, configuration=None):
self.add_crates(['EMSServiceAreas'], {'source_workspace': join(self.garage, 'SGID10.sde'),
'destination_workspace': self.destination_workspace})
| #!/usr/bin/env python
# * coding: utf8 *
'''
BemsPallet.py
A module that contains a pallet to update the querable layers behind our UTM basemaps
'''
from forklift.models import Pallet
from os.path import join
class BemsPallet(Pallet):
def __init__(self):
super(BemsPallet, self).__init__()
self.arcgis_services = [('BEMS/Boundaries', 'MapServer')]
self.destination_workspace = 'C:\\Scheduled\\Staging\\SGID.gdb'
self.copy_data = [self.destination_workspace]
def build(self, configuration=None):
self.add_crates(['EMSServiceAreas'], {'source_workspace': join(self.garage, 'SGID10.sde'),
'destination_workspace': self.destination_workspace})
|
Fix indentation of the Java grammar | define(function() {
return function(Prism) {
Prism.languages.java = Prism.languages.extend('clike', {
'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/g,
'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+[e]?[\d]*[df]\b|\W\d*\.?\d+\b/gi,
'operator': {
pattern: /([^\.]|^)([-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\/|%|\^|(<){2}|($gt;){2,3}|:|~)/g,
lookbehind: true
}
});
};
});
| define(function() {
// Export
return function(Prism) {
Prism.languages.java = Prism.languages.extend('clike', {
'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/g,
'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+[e]?[\d]*[df]\b|\W\d*\.?\d+\b/gi,
'operator': {
pattern: /([^\.]|^)([-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\/|%|\^|(<){2}|($gt;){2,3}|:|~)/g,
lookbehind: true
}
});
};
});
|
Remove unused import. Facebook compliance support python3 | from json import dumps
try:
from urlparse import parse_qsl
except ImportError:
from urllib.parse import parse_qsl
def facebook_compliance_fix(session):
def _compliance_fix(r):
# if Facebook claims to be sending us json, let's trust them.
if 'application/json' in r.headers['content-type']:
return r
# Facebook returns a content-type of text/plain when sending their
# x-www-form-urlencoded responses, along with a 200. If not, let's
# assume we're getting JSON and bail on the fix.
if 'text/plain' in r.headers['content-type'] and r.status_code == 200:
token = dict(parse_qsl(r.text, keep_blank_values=True))
else:
return r
expires = token.get('expires')
if expires is not None:
token['expires_in'] = expires
token['token_type'] = 'Bearer'
r._content = dumps(token)
return r
session.register_compliance_hook('access_token_response', _compliance_fix)
return session
| from json import dumps
from oauthlib.common import urldecode
from urlparse import parse_qsl
def facebook_compliance_fix(session):
def _compliance_fix(r):
# if Facebook claims to be sending us json, let's trust them.
if 'application/json' in r.headers['content-type']:
return r
# Facebook returns a content-type of text/plain when sending their
# x-www-form-urlencoded responses, along with a 200. If not, let's
# assume we're getting JSON and bail on the fix.
if 'text/plain' in r.headers['content-type'] and r.status_code == 200:
token = dict(parse_qsl(r.text, keep_blank_values=True))
else:
return r
expires = token.get('expires')
if expires is not None:
token['expires_in'] = expires
token['token_type'] = 'Bearer'
r._content = dumps(token)
return r
session.register_compliance_hook('access_token_response', _compliance_fix)
return session
|
Fix XMLHttpRequest - 3.0.0 PR edition
As on tin. Same thing as #107. | //
// Browser requests, mirrors the syntax of the node requests
//
var when = require('when');
var form = require('./form');
exports.https = function(options, formData) {
options = options || {};
options.headers = options.headers || {};
var data = form.getData(formData);
options.headers['Content-Type'] = data.contentType;
return when.promise(function(resolve, reject) {
try {
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
var x = new window.XMLHttpRequest();
var url = 'https://' + options.hostname + options.path;
// append the form data to the end of the url
if (options.method === 'GET') {
url += '?' + data.buffer.toString();
}
x.open(options.method, url, true);
Object.keys(options.headers).forEach(function(headerKey) {
x.setRequestHeader(headerKey, options.headers[headerKey]);
});
x.onreadystatechange = function() {
if (x.readyState > 3) {
// Normalize the result to match how requestNode.js works
return resolve({
_body: x.responseText,
_status: x.status
});
}
};
x.send(options.method === 'GET' ? null : data.buffer.toString());
} catch (e) {
return reject(e);
}
});
};
| //
// Browser requests, mirrors the syntax of the node requests
//
var when = require('when');
var form = require('./form');
exports.https = function(options, formData) {
options = options || {};
options.headers = options.headers || {};
var data = form.getData(formData);
options.headers['Content-Type'] = data.contentType;
return when.promise(function(resolve, reject) {
try {
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
var x = new XMLHttpRequest();
var url = 'https://' + options.hostname + options.path;
// append the form data to the end of the url
if (options.method === 'GET') {
url += '?' + data.buffer.toString();
}
x.open(options.method, url, true);
Object.keys(options.headers).forEach(function(headerKey) {
x.setRequestHeader(headerKey, options.headers[headerKey]);
});
x.onreadystatechange = function() {
if (x.readyState > 3) {
// Normalize the result to match how requestNode.js works
return resolve({
_body: x.responseText,
_status: x.status
});
}
};
x.send(options.method === 'GET' ? null : data.buffer.toString());
} catch (e) {
return reject(e);
}
});
};
|
Add a link back to the client from the config page | @extends('master')
@section('title')
Micropub Config «
@stop
@section('content')
<p>The values for your micropub endpoint.</p>
<dl>
<dt>Me (your url)</dt><dd>{{ $data['me'] }}</dd>
<dt>Token</dt><dd>{{ $data['token'] }}</dd>
<dt>Syndication Targets</dt><dd>@if(is_array($data['syndication']))<ul>@foreach ($data['syndication'] as $syn)<li>{{ $syn['name'] }} ({{ $syn['target'] }})</li>@endforeach</ul>@else{{ $data['syndication'] }}@endif</dd>
<dt>Media Endpoint</dt><dd>{{ $data['media-endpoint'] }}</dd>
</dl>
<p><a href="{{ route('micropub-query-action') }}">Re-query</a> the endpoint.</p>
<p>Return to <a href="{{ route('micropub-client') }}">client</a>.
@stop
| @extends('master')
@section('title')
Micropub Config «
@stop
@section('content')
<p>The values for your micropub endpoint.</p>
<dl>
<dt>Me (your url)</dt><dd>{{ $data['me'] }}</dd>
<dt>Token</dt><dd>{{ $data['token'] }}</dd>
<dt>Syndication Targets</dt><dd>@if(is_array($data['syndication']))<ul>@foreach ($data['syndication'] as $syn)<li>{{ $syn['name'] }} ({{ $syn['target'] }})</li>@endforeach</ul>@else{{ $data['syndication'] }}@endif</dd>
<dt>Media Endpoint</dt><dd>{{ $data['media-endpoint'] }}</dd>
</dl>
<p><a href="{{ route('micropub-query-action') }}">Re-query</a> the endpoint.</p>
@stop
|
Add clubId property and change labels | import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
export const Coachs = new Mongo.Collection('coachs');
Coachs.deny({
insert() {
return true;
},
update() {
return true;
},
remove() {
return true;
}
});
export const coachSchema = new SimpleSchema({
gameId: {
type: String,
label: 'Coach\'s game id'
},
teamId: {
type: String,
label: 'Coach\'s team id'
},
clubId: {
type: String,
label: 'Coach\'s club id',
optional: true
},
firstName: {
type: String,
label: 'Coach\'s first name',
optional: true
},
lastName: {
type: String,
label: 'Coach\'s last name',
optional: true
},
primaryCoach: {
type: Boolean,
label: 'Primary coach or not'
},
techFouls: {
type: Number,
label: 'Coach\'s tech fouls',
min: 0,
max: 2
}
});
Coachs.schemas = coachSchema;
| import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
export const Coachs = new Mongo.Collection('coachs');
Coachs.deny({
insert() {
return true;
},
update() {
return true;
},
remove() {
return true;
}
});
export const coachSchema = new SimpleSchema({
gameId: {
type: String,
label: 'Game id'
},
teamId: {
type: String,
label: 'Team id'
},
firstName: {
type: String,
label: 'Coachs first name',
optional: true
},
lastName: {
type: String,
label: 'Coachs last name',
optional: true
},
primaryCoach: {
type: Boolean,
label: 'Primary coach or not'
},
techFouls: {
type: Number,
label: 'Coach tech fouls',
min: 0,
max: 2
}
});
Coachs.schemas = coachSchema;
|
Use 'range' rather than 'xrange' for Python 3 compatibility. | #!/usr/bin/env python
# coding=utf-8
"""
Balanced ternary binary encoding
============
Tools for encoding balanced ternary data into binary formats and back again.
The encoded scheme used here uses 8-bit segments to represent 5-trit segments.
Each 5-trit segment is mapped to an 8-bit binary value which corresponds to its
value as an unsigned integer.
So, for example, consider the trit sequence:
0-00+
This sequence interpreted as a signed number is decimal -70, and as an unsigned
number decimal 51. We encode it using the byte value 51, or hex 0x33, which
gives:
0011 0011
If a trit sequence is not evenly divisible into 5-trit segments, the final
segment is padded to 5 trits by adding '-' trits to the left.
"""
from . import trit, integer
def encode(source):
result = b''
for i in range(0, len(source), 5):
value = integer.UInt(source[i:i+5], 5)
result += chr(value)
return result
def decode(binary):
trits = trit.Trits('')
for i in range(len(binary)):
value = ord(binary[i])
if value > 242:
raise ValueError(
"Invalid byte at position {}: {:#02x}".format(i, value))
trits += integer.UInt(value, 5)
return trits
| #!/usr/bin/env python
# coding=utf-8
"""
Balanced ternary binary encoding
============
Tools for encoding balanced ternary data into binary formats and back again.
The encoded scheme used here uses 8-bit segments to represent 5-trit segments.
Each 5-trit segment is mapped to an 8-bit binary value which corresponds to its
value as an unsigned integer.
So, for example, consider the trit sequence:
0-00+
This sequence interpreted as a signed number is decimal -70, and as an unsigned
number decimal 51. We encode it using the byte value 51, or hex 0x33, which
gives:
0011 0011
If a trit sequence is not evenly divisible into 5-trit segments, the final
segment is padded to 5 trits by adding '-' trits to the left.
"""
from . import trit, integer
def encode(source):
result = b''
for i in xrange(0, len(source), 5):
value = integer.UInt(source[i:i+5], 5)
result += chr(value)
return result
def decode(binary):
trits = trit.Trits('')
for i in xrange(len(binary)):
value = ord(binary[i])
if value > 242:
raise ValueError(
"Invalid byte at position {}: {:#02x}".format(i, value))
trits += integer.UInt(value, 5)
return trits
|
Change the config dictionary key validation | #!/usr/bin/python3
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scannerConf.close()
GATEWAY = '192.168.1.1'
if 'GATEWAY' in env:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if 'IFACE' in env:
IFACE = env['IFACE']
print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE))
while True:
ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY])
if ret == 0:
print("Network appears to be up")
else:
print("Network appears to be down, restarting...")
ret = subprocess.call(['/sbin/ifdown', '--force', IFACE])
ret = subprocess.call(['/sbin/ifup', IFACE])
sleep(60)
| #!/usr/bin/python3
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scannerConf.close()
GATEWAY = '192.168.1.1'
if env['GATEWAY']:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if env['IFACE']:
IFACE = env['IFACE']
print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE))
while True:
ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY])
if ret == 0:
print("Network appears to be up")
else:
print("Network appears to be down, restarting...")
ret = subprocess.call(['/sbin/ifdown', '--force', IFACE])
ret = subprocess.call(['/sbin/ifup', IFACE])
sleep(60)
|
Remove `implicitBundleDest` property from example app (now uses default). | var path = require("path");
var Interlock = require("..");
var ilk = new Interlock({
srcRoot: __dirname,
destRoot: path.join(__dirname, "dist"),
entry: {
"./app/entry-a.js": "entry-a.bundle.js",
"./app/entry-b.js": { dest: "entry-b.bundle.js" }
},
split: {
"./app/shared/lib-a.js": "[setHash].js"
},
includeComments: true,
sourceMaps: true,
plugins: []
});
ilk.watch(true).observe(function (buildEvent) {
var patchModules = buildEvent.patchModules;
var compilation = buildEvent.compilation;
if (patchModules) {
const paths = patchModules.map(function (module) { return module.path; });
console.log("the following modules have been updated:", paths);
}
if (compilation) {
console.log("a new compilation has completed");
}
});
// ilk.build();
| var path = require("path");
var Interlock = require("..");
var ilk = new Interlock({
srcRoot: __dirname,
destRoot: path.join(__dirname, "dist"),
entry: {
"./app/entry-a.js": "entry-a.bundle.js",
"./app/entry-b.js": { dest: "entry-b.bundle.js" }
},
split: {
"./app/shared/lib-a.js": "[setHash].js"
},
includeComments: true,
sourceMaps: true,
implicitBundleDest: "[setHash].js",
plugins: []
});
ilk.watch(true).observe(function (buildEvent) {
var patchModules = buildEvent.patchModules;
var compilation = buildEvent.compilation;
if (patchModules) {
const paths = patchModules.map(function (module) { return module.path; });
console.log("the following modules have been updated:", paths);
}
if (compilation) {
console.log("a new compilation has completed");
}
});
// ilk.build();
|
Change API key to unit test version | <?php
return array(
/*
|--------------------------------------------------------------------------
| Enable Tracking
|--------------------------------------------------------------------------
|
| Enable Google Analytics tracking.
|
*/
'enabled' => true,
/*
|--------------------------------------------------------------------------
| Google Analytics Tracking Identifier
|--------------------------------------------------------------------------
|
| A Google Analytics tracking identifier to link Googlitics to Google
| Analytics.
|
*/
'id' => env('GOOGLE_API_KEY', 'AIzaSyCTwWv4rTQdNtZAaAd8D1SK5m94eTp8GiQ'),
/*
|--------------------------------------------------------------------------
| Tracking Domain
|--------------------------------------------------------------------------
|
| The domain which is being tracked. Leave as 'auto' if you want Googlitics
| to automatically set the current domain. Otherwise enter your domain,
| e.g. google.com
|
*/
'domain' => 'auto',
/*
|--------------------------------------------------------------------------
| Anonymise Tracking
|--------------------------------------------------------------------------
|
| Anonymise users IP addresses when tracking them via Googlitics.
|
*/
'anonymise' => true,
/*
|--------------------------------------------------------------------------
| Enable Automatic Tracking
|--------------------------------------------------------------------------
|
| Enable automatic tracking to ensure users are tracked automatically by
| Googlitics.
|
*/
'automatic' => true,
);
| <?php
return array(
/*
|--------------------------------------------------------------------------
| Enable Tracking
|--------------------------------------------------------------------------
|
| Enable Google Analytics tracking.
|
*/
'enabled' => true,
/*
|--------------------------------------------------------------------------
| Google Analytics Tracking Identifier
|--------------------------------------------------------------------------
|
| A Google Analytics tracking identifier to link Googlitics to Google
| Analytics.
|
*/
'id' => env('GOOGLE_API_KEY', 'AIzaSyDlBSG-e2TlAg4OY29OcKXb78kiN0iEeWA'),
/*
|--------------------------------------------------------------------------
| Tracking Domain
|--------------------------------------------------------------------------
|
| The domain which is being tracked. Leave as 'auto' if you want Googlitics
| to automatically set the current domain. Otherwise enter your domain,
| e.g. google.com
|
*/
'domain' => 'auto',
/*
|--------------------------------------------------------------------------
| Anonymise Tracking
|--------------------------------------------------------------------------
|
| Anonymise users IP addresses when tracking them via Googlitics.
|
*/
'anonymise' => true,
/*
|--------------------------------------------------------------------------
| Enable Automatic Tracking
|--------------------------------------------------------------------------
|
| Enable automatic tracking to ensure users are tracked automatically by
| Googlitics.
|
*/
'automatic' => true,
);
|
Fix a bug in the cache manager
It is possible that the previous state is None | import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
if self.tracer.previous != None:
state = self.tracer.previous.state
else:
state = None
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds
| import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
state = self.tracer.previous.state
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds
|
Make faucet support anon access | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import { syncHistoryWithStore } from 'react-router-redux'
import { UserIsAuthenticated, UserIsNotAuthenticated } from './util/wrappers.js'
// Material UI dependency thing
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
// Layouts
import Faucet from './faucet/Faucet';
import Home from './layouts/Home';
import Dashboard from './layouts/Dashboard';
import SignUp from './layouts/SignUp';
import Profile from './layouts/Profile';
// Redux Store
import store from './store';
const history = syncHistoryWithStore(browserHistory, store)
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Home} />
<Route path="dashboard" component={UserIsAuthenticated(Dashboard)} />
<Route path="faucet" component={UserIsNotAuthenticated(Faucet)} />
<Route path="signup" component={UserIsNotAuthenticated(SignUp)} />
<Route path="profile" component={UserIsAuthenticated(Profile)} />
</Router>
</Provider>
),
document.getElementById('root')
);
| import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import { syncHistoryWithStore } from 'react-router-redux'
import { UserIsAuthenticated, UserIsNotAuthenticated } from './util/wrappers.js'
// Material UI dependency thing
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
// Layouts
import Faucet from './faucet/Faucet';
import Home from './layouts/Home';
import Dashboard from './layouts/Dashboard';
import SignUp from './layouts/SignUp';
import Profile from './layouts/Profile';
// Redux Store
import store from './store';
const history = syncHistoryWithStore(browserHistory, store)
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Home} />
<Route path="dashboard" component={UserIsAuthenticated(Dashboard)} />
<Route path="faucet" component={UserIsAuthenticated(Faucet)} />
<Route path="signup" component={UserIsNotAuthenticated(SignUp)} />
<Route path="profile" component={UserIsAuthenticated(Profile)} />
</Router>
</Provider>
),
document.getElementById('root')
);
|
Remove functions that rely on the console object
Mainly because console.log isn't a standard JS feature
and is implemented differently across browsers, causing
problems when trying to alias it. | 'use strict';
var $ = require('jquery');
var forOwn = require('lodash/object/forOwn');
var isArray = require('lodash/lang/isArray');
var isPlainObject = require('lodash/lang/isPlainObject');
var extend = require('lodash/object/extend');
var transform = require('lodash/object/transform');
module.exports = {
Modules: {},
Helpers: {},
Events: $({}),
init: function() {
var self = this;
forOwn(this.Modules, function(module) {
if (typeof module.init === 'function') {
module.base = self;
module.init();
}
});
// trigger initial render event
this.Events.trigger('render');
},
use: function(modules) {
if (isArray(modules)) {
transform(modules, extend, this.Modules);
} else if(isPlainObject(modules)) {
extend(this.Modules, modules);
} else {
throw('Pass either single module or an array of modules.\ne.g. `.use(require(\'./modules/some-module\')`');
}
return this;
}
};
| 'use strict';
var $ = require('jquery');
var forOwn = require('lodash/object/forOwn');
var isArray = require('lodash/lang/isArray');
var isPlainObject = require('lodash/lang/isPlainObject');
var extend = require('lodash/object/extend');
var transform = require('lodash/object/transform');
module.exports = {
Modules: {},
Helpers: {},
Events: $({}),
init: function() {
var self = this;
forOwn(this.Modules, function(module) {
if (typeof module.init === 'function') {
module.base = self;
module.init();
}
});
// trigger initial render event
this.Events.trigger('render');
},
// safe logging
log: function() {
if (window && window.console) {
window.console.log.apply(console, arguments);
}
},
dir: function() {
if (window && window.console) {
window.console.dir.apply(console, arguments);
}
},
use: function(modules) {
if (isArray(modules)) {
transform(modules, extend, this.Modules);
} else if(isPlainObject(modules)) {
extend(this.Modules, modules);
} else {
throw('Pass either single module or an array of modules.\ne.g. `.use(require(\'./modules/some-module\')`');
}
return this;
}
};
|
Update tests to new SimpleProps | package dev.kkorolyov.sqlob;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import dev.kkorolyov.simpleprops.Properties;
@SuppressWarnings("javadoc")
public class TestAssets {
private static final String HOST = "HOST",
DATABASE = "DATABASE",
USER = "USER",
PASSWORD = "PASSWORD";
private static final Properties props = new Properties(new File("TestSQLOb.ini"), buildDefaults());
static {
try {
props.saveFile();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static String host() {
return props.get(HOST);
}
public static String database() {
return props.get(DATABASE);
}
public static String user() {
return props.get(USER);
}
public static String password() {
return props.get(PASSWORD);
}
private static Properties buildDefaults() {
Properties defaults = new Properties();
defaults.put(HOST, "");
defaults.put(DATABASE, "");
defaults.put(USER, "");
defaults.put(PASSWORD, "");
return defaults;
}
}
| package dev.kkorolyov.sqlob;
import java.io.IOException;
import java.io.UncheckedIOException;
import dev.kkorolyov.simpleprops.Properties;
@SuppressWarnings("javadoc")
public class TestAssets {
private static final String TEST_PROPERTIES_NAME = "TestSQLOb.ini";
private static final String HOST = "HOST",
DATABASE = "DATABASE",
USER = "USER",
PASSWORD = "PASSWORD";
private static final String[][] defaults = {{HOST, ""},
{DATABASE, ""},
{USER, "postgres"},
{PASSWORD, ""}};
private static final Properties props = Properties.getInstance(TEST_PROPERTIES_NAME, defaults);
static {
try {
props.saveToFile();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static String host() {
return props.getValue(HOST);
}
public static String database() {
return props.getValue(DATABASE);
}
public static String user() {
return props.getValue(USER);
}
public static String password() {
return props.getValue(PASSWORD);
}
}
|
Fix public asset publish location | <?php namespace GeneaLabs\Bones\Keeper;
use Illuminate\Support\ServiceProvider;
class BonesKeeperServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
if (! $this->app->routesAreCached()) {
require __DIR__ . '/../../../routes.php';
}
$this->publishes([__DIR__ . '/../../../config/config.php' => config_path('/genealabs/bones-keeper.php')], 'genealabs-bones-keeper');
$this->publishes([__DIR__ . '/../../../../public' => public_path('genealabs/bones-keeper')], 'genealabs-bones-keeper');
$this->loadViewsFrom(__DIR__.'/../../../views', 'genealabs-bones-keeper');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['genealabs-bones-keeper'];
}
}
| <?php namespace GeneaLabs\Bones\Keeper;
use Illuminate\Support\ServiceProvider;
class BonesKeeperServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
if (! $this->app->routesAreCached()) {
require __DIR__ . '/../../../routes.php';
}
$this->publishes([__DIR__ . '/../../../config/config.php' => config_path('/genealabs/bones-keeper.php')], 'genealabs-bones-keeper');
$this->publishes([
__DIR__ . '/../../../../public' => public_path('genealabs/bones-keeper')], 'genealabs-bones-keeper');
$this->loadViewsFrom(__DIR__.'/../../../views', 'genealabs-bones-keeper');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['genealabs-bones-keeper'];
}
}
|
Add unittest skip for CI | # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
@unittest.skipIf(skip, 'SKIP_INTEGRATION_TESTS==1')
def setUp(self):
"""
Get a non-interactive client secret
"""
self.domain = os.getenv('DOMAIN')
self.client_id = os.getenv('CLIENT_ID')
self.secret_id = os.getenv('CLIENT_SECRET')
def test_get_a_token(self):
"""
Test getting a 24 hour token from the oauth token endpoint
"""
token = get_token(self.domain, self.client_id, self.secret_id)
assert token['access_token']
| # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
def setUp(self):
"""
Get a non-interactive client secret
"""
self.domain = os.getenv('DOMAIN')
self.client_id = os.getenv('CLIENT_ID')
self.secret_id = os.getenv('CLIENT_SECRET')
def test_get_a_token(self):
"""
Test getting a 24 hour token from the oauth token endpoint
"""
token = get_token(self.domain, self.client_id, self.secret_id)
assert token['access_token']
|
Use set method on EnvFile object | <?php
namespace Sven\FlexEnv;
use Sven\FlexEnv\Contracts\Parser;
class EnvParser implements Parser
{
public function parse(string $env): EnvFile
{
$lines = $this->removeEmptyLines(
$this->splitIntoLines($env)
);
$parser = new LineParser();
return array_reduce($lines, function (EnvFile $file, $line) use ($parser) {
[$key, $value] = $parser->parse($line);
$file->set($key, $value);
return $file;
}, new EnvFile);
}
protected function splitIntoLines(string $env): array
{
return explode(PHP_EOL, $env);
}
protected function removeEmptyLines(array $lines): array
{
return array_filter($lines);
}
}
| <?php
namespace Sven\FlexEnv;
use Sven\FlexEnv\Contracts\Parser;
class EnvParser implements Parser
{
public function parse(string $env): EnvFile
{
$lines = $this->removeEmptyLines(
$this->splitIntoLines($env)
);
$parser = new LineParser();
return array_reduce($lines, function (EnvFile $carry, $line) use ($parser) {
[$key, $value] = $parser->parse($line);
$carry[$key] = $value;
return $carry;
}, new EnvFile);
}
protected function splitIntoLines(string $env): array
{
return explode(PHP_EOL, $env);
}
protected function removeEmptyLines(array $lines): array
{
return array_filter($lines);
}
}
|
Rename photo endpoint to submission | """.. Ignore pydocstyle D400.
=============
Core API URLs
=============
The ``routList`` is ment to be included in ``urlpatterns`` with the
following code:
.. code-block:: python
from rest_framework import routers
from rolca.core.api import urls as core_api_urls
route_lists = [
core_api_urls.routeList,
...
]
router = routers.DefaultRouter()
for route_list in route_lists:
for prefix, viewset in route_list:
router.register(prefix, viewset)
For advanced configuration code can be accordingly changed to meet the
needs.
"""
from rolca.core.api.views import ContestViewSet, SubmissionViewSet
routeList = (
(r'submission', SubmissionViewSet),
(r'contest', ContestViewSet),
)
| """.. Ignore pydocstyle D400.
=============
Core API URLs
=============
The ``routList`` is ment to be included in ``urlpatterns`` with the
following code:
.. code-block:: python
from rest_framework import routers
from rolca.core.api import urls as core_api_urls
route_lists = [
core_api_urls.routeList,
...
]
router = routers.DefaultRouter()
for route_list in route_lists:
for prefix, viewset in route_list:
router.register(prefix, viewset)
For advanced configuration code can be accordingly changed to meet the
needs.
"""
from rolca.core.api.views import ContestViewSet, SubmissionViewSet
routeList = (
(r'photo', SubmissionViewSet),
(r'contest', ContestViewSet),
)
|
Tag Display in single Ticket | <?php
use yii\helpers\Html;
use yii\bootstrap\Carousel;
/* @var $this yii\web\View */
/* @var $ticket common\models\Ticket */
/* @var $showTagMax int/boolean maximum number of tags to display*/
//Ticket Decoration Bar displays the Ticket decorations
if ($taglist = $ticket->tagNames) {
echo Html::beginTag('div', ['class' => 'ticket-single-tags']);
$tagArray = explode(',', $taglist);
$tagCount = count($tagArray);
$i = 1;
foreach ($tagArray as $tag) {
$carouselItems[] = [
'content' => '',
'caption' => "$tag - <small>($i/$tagCount)</small>",
];
$i++;
}
echo Carousel::widget([
'items' => $carouselItems,
'controls' => false,
'showIndicators' => false,
]);
echo Html::endTag('div');
}
?> | <?php
use yii\helpers\Html;
use yii\bootstrap\Carousel;
/* @var $this yii\web\View */
/* @var $ticket common\models\Ticket */
/* @var $showTagMax int/boolean maximum number of tags to display*/
//Ticket Decoration Bar displays the Ticket decorations
if ($taglist = $ticket->tagNames) {
echo Html::beginTag('div', ['class' => 'ticket-single-tags']);
$tagArray = explode(',', $taglist);
$tagCount = count($tagArray);
$i = 1;
foreach ($tagArray as $tag) {
$carouselItems[] = [
'content' => '',
'caption' => "<small>$i/$tagCount</small> $tag",
];
$i++;
}
echo Carousel::widget([
'items' => $carouselItems,
'controls' => false,
'showIndicators' => false,
]);
echo Html::endTag('div');
}
?> |
Fix outdated link in sample plugin
Link in sample_plugin.py is outdated
and is changed
Change-Id: I2f3a7b59c6380e4584a8ce2a5313fe766a40a52a
Closes-Bug: #1491975 | # Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Sample plugin for Heat.
For more Heat related benchmarks take a look here:
http://github.com/openstack/rally/tree/master/rally/plugins/openstack/scenarios/heat
About plugins: https://rally.readthedocs.org/en/latest/plugins.html
Rally concepts https://wiki.openstack.org/wiki/Rally/Concepts
"""
from rally.benchmark.scenarios import base
class HeatPlugin(base.Scenario):
@base.scenario(context={"cleanup": ["heat"]})
def list_benchmark(self, container_format,
image_location, disk_format, **kwargs):
"""Get heatclient and do whatever."""
stacks = list(self.clients("heat").stacks.list())
| # Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Sample plugin for Heat.
For more Heat related benchmarks take a look here:
http://github.com/stackforge/rally/blob/master/rally/benchmark/scenarios/heat/
About plugins: https://rally.readthedocs.org/en/latest/plugins.html
Rally concepts https://wiki.openstack.org/wiki/Rally/Concepts
"""
from rally.benchmark.scenarios import base
class HeatPlugin(base.Scenario):
@base.scenario(context={"cleanup": ["heat"]})
def list_benchmark(self, container_format,
image_location, disk_format, **kwargs):
"""Get heatclient and do whatever."""
stacks = list(self.clients("heat").stacks.list())
|
Add semi-colon and use dot notation. | //Filter experiment or computation templates
Application.Filters.filter('byMediaType', function () {
return function (items, values) {
var matches = [];
if (items) {
items.forEach(function(item) {
if ('mediatype' in item) {
values.forEach(function(val){
if (item.mediatype === val){
matches.push(item);
}
});
}
});
}
return matches;
};
});
| //Filter experiment or computation templates
Application.Filters.filter('byMediaType', function () {
return function (items, values) {
var matches = [];
if (items) {
items.forEach(function(item) {
if ('mediatype' in item) {
values.forEach(function(val){
if (item['mediatype'] == val){
matches.push(item);
}
})
}
});
}
return matches;
};
});
|
Fix GoogleDrive OAuth callback URL in OAuth module. | # -*- encoding:utf8 -*-
import os
from oauth2client.client import OAuth2WebServerFlow
class OAuth:
def __init__(self):
pass
def get_flow(self):
scope = 'https://www.googleapis.com/auth/drive'
try:
client_id = os.environ['GOOGLE_CLIENT_ID']
client_secret = os.environ['GOOGLE_CLIENT_SECRET']
base_url = os.environ['BOTNYAN_BASE_URL']
separator = "/"
if base_url.endswith("/"):
separator = ""
redirect_url = "{0}{1}api/drive/callback".format(base_url, separator)
flow = OAuth2WebServerFlow(client_id=client_id,
client_secret=client_secret,
scope=scope,
redirect_uri=redirect_url)
return flow
except:
return None
| # -*- encoding:utf8 -*-
import os
from oauth2client.client import OAuth2WebServerFlow
class OAuth:
def __init__(self):
pass
def get_flow(self):
scope = 'https://www.googleapis.com/auth/drive'
try:
client_id = os.environ['GOOGLE_CLIENT_ID']
client_secret = os.environ['GOOGLE_CLIENT_SECRET']
base_url = os.environ['BOTNYAN_BASE_URL']
separator = "/"
if base_url.endswith("/"):
separator = ""
redirect_url = "{0}{1}drive/callback".format(base_url, separator)
flow = OAuth2WebServerFlow(client_id=client_id,
client_secret=client_secret,
scope=scope,
redirect_uri=redirect_url)
return flow
except:
return None
|
Add button title to the footer "Title" | import { h } from 'preact'
import InfoIcon from '../icons/InfoIcon'
import DescriptionIcon from '../icons/DescriptionIcon'
function Footer({
title,
date,
showTitle,
showInfo,
onTitleClick,
onToggleClick
}) {
const footerVisibility = showTitle ? 'show' : ''
let toggleButtonClasses = ['btn']
if (showInfo) toggleButtonClasses.push('active')
return (
<footer class="footer-container">
<div class="footer-icon">
<a class="btn" onClick={onTitleClick}>
<InfoIcon />
<span class="btn-text">Title</span>
</a>
</div>
<div class={`footer ${footerVisibility}`}>
<div class="footer-inner">
<span class="footer-title">{title}</span>
</div>
</div>
<div class="footer-icon">
<a class={toggleButtonClasses.join(' ')} onClick={onToggleClick}>
<DescriptionIcon />
<span class="btn-text">Details</span>
</a>
</div>
</footer>
)
}
export default Footer
| import { h } from 'preact'
import InfoIcon from '../icons/InfoIcon'
import DescriptionIcon from '../icons/DescriptionIcon'
function Footer({
title,
date,
showTitle,
showInfo,
onTitleClick,
onToggleClick
}) {
const footerVisibility = showTitle ? 'show' : ''
let toggleButtonClasses = ['btn']
if (showInfo) toggleButtonClasses.push('active')
return (
<footer class="footer-container">
<div class="footer-icon">
<a class="btn" onClick={onTitleClick}>
<InfoIcon />
</a>
</div>
<div class={`footer ${footerVisibility}`}>
<div class="footer-inner">
<span class="footer-title">{title}</span>
</div>
</div>
<div class="footer-icon">
<a class={toggleButtonClasses.join(' ')} onClick={onToggleClick}>
<DescriptionIcon />
<span class="btn-text">Details</span>
</a>
</div>
</footer>
)
}
export default Footer
|
Add quickstarts to root module.
Fixes checkstyle errors in samples. | /*
Copyright 2016, Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.storage;
// [START storage_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class QuickstartSample {
public static void main(String... args) throws Exception {
// Instantiates a client
Storage storage = StorageOptions.defaultInstance().service();
// The name for the new bucket
String bucketName = "my-new-bucket";
// Creates the new bucket
Bucket bucket = storage.create(BucketInfo.of(bucketName));
System.out.printf("Bucket %s created.%n", bucket.name());
}
}
// [END storage_quickstart]
| /*
Copyright 2016, Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.storage;
// [START storage_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
public class QuickstartSample {
public static void main(String... args) throws Exception {
// Instantiates a client
Storage storage = StorageOptions.defaultInstance().service();
// The name for the new bucket
String bucketName = "my-new-bucket";
// Creates the new bucket
Bucket bucket = storage.create(BucketInfo.of(bucketName));
System.out.printf("Bucket %s created.%n", bucket.name());
}
}
// [END storage_quickstart]
|
Fix passing dashed module paths to generator | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var convert = {
moduleToFolder: moduleToFolder,
pathToModule: pathToModule
};
function pathToModule(dir, entered) {
var moduleName = _.camelCase(path.basename(dir));
var moduleFilename = path.basename(dir) + '.module.js';
var moduleFilePath = path.resolve(dir, moduleFilename);
var prefix;
try {
fs.accessSync(moduleFilePath, fs.F_OK);
prefix = pathToModule(path.resolve(dir, '..'), true);
return (prefix) ? prefix + '.' + moduleName : moduleName;
} catch (e) {
if (entered) {
return '';
} else {
prefix = pathToModule(path.resolve(dir, '..'), true);
return (prefix) ? prefix + '.' + moduleName : moduleName;
}
}
}
function moduleToFolder(moduleName) {
var moduleParts = moduleName.split('.');
for (var i = 0; i < moduleParts.length; i++) {
moduleParts[i] = _.kebabCase(moduleParts[i]);
}
moduleParts = _.join(moduleParts, '/') + '/';
return moduleParts.replace(/v-24/g, 'v24');
}
module.exports = convert;
| 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var convert = {
moduleToFolder: moduleToFolder,
pathToModule: pathToModule
};
function pathToModule(dir, entered) {
var moduleName = _.camelCase(path.basename(dir));
var moduleFilename = moduleName + '.module.js';
var moduleFilePath = path.resolve(dir, moduleFilename);
var prefix;
try {
fs.accessSync(moduleFilePath, fs.F_OK);
prefix = pathToModule(path.resolve(dir, '..'), true);
return (prefix) ? prefix + '.' + moduleName : moduleName;
} catch (e) {
if (entered) {
return '';
} else {
prefix = pathToModule(path.resolve(dir, '..'), true);
return (prefix) ? prefix + '.' + moduleName : moduleName;
}
}
}
function moduleToFolder(moduleName) {
var moduleParts = moduleName.split('.');
for (var i = 0; i < moduleParts.length; i++) {
moduleParts[i] = _.kebabCase(moduleParts[i]);
}
moduleParts = _.join(moduleParts, '/') + '/';
return moduleParts.replace(/v-24/g, 'v24');
}
module.exports = convert;
|
Add match_distance flag to load_data_frame() | import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the second-to-last column
:param match_distance: if True, the distance between the closest match is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
if match_distance:
column_names.append('distance')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
| import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
|
Add PR merge hook handling. | <?php namespace App\Http\Controllers;
use App\Jobs\UpdateLiveCopy;
use App\Jobs\UpdateVersionHashes;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Inspiring;
use Illuminate\Http\Request;
class HooksController extends Controller
{
use DispatchesJobs;
public function specChange(Request $request)
{
switch ($request->header('x-github-event'))
{
case 'pull_request':
// update jobs are only necessary on PR merges
$json = json_decode($request->input('payload'), true);
if ($json['action'] == 'closed' && $json['merged'])
{
$this->dispatch(new UpdateLiveCopy());
$this->dispatch(new UpdateVersionHashes());
}
break;
case 'push':
// just initiate spec and version updates
$this->dispatch(new UpdateLiveCopy());
$this->dispatch(new UpdateVersionHashes());
break;
case 'ping':
default:
return response()->json(['result' => Inspiring::quote()]);
}
}
public function addVersion()
{
// Buildkite build finish hook, receive a packed fully built version
}
} | <?php namespace App\Http\Controllers;
use App\Jobs\UpdateLiveCopy;
use App\Jobs\UpdateVersionHashes;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Inspiring;
use Illuminate\Http\Request;
class HooksController extends Controller
{
use DispatchesJobs;
public function specChange(Request $request)
{
// GitHub update hook, load new version hashes
$json = json_decode($request->input('payload'), true);
switch ($request->header('x-github-event'))
{
case 'pull_request': break;
case 'push':
// just initiate spec and version updates
$this->dispatch(new UpdateLiveCopy());
$this->dispatch(new UpdateVersionHashes());
break;
case 'ping':
default:
return response()->json(['result' => Inspiring::quote()]);
}
}
public function addVersion()
{
// Buildkite build finish hook, receive a packed fully built version
}
} |
Comment just to prevent the errors | import Ember from 'ember';
import layout from '../templates/components/yebo-checkout';
/**
A single page checkout that reactively responds to changes in the
`yebo.checkouts` service.
**To Override:** You'll need to run the components generator:
```bash
ember g yebo-ember-storefront-components
```
This will install all of the Yebo Ember Storefront component files into your
host application at `app/components/yebo-*.js`, ready to be extended or
overriden.
@class YeboCheckout
@namespace Component
@extends Ember.Component
*/
export default Ember.Component.extend({
layout: layout,
action: 'transitionCheckoutState',
/**
*
*/
init() {
// Call the super
this._super();
// Set initialize it
// this.get('checkouts').trigger('checkoutCalled');
},
actions: {
transitionCheckoutState: function(stateName) {
this.sendAction('action', stateName);
}
}
});
| import Ember from 'ember';
import layout from '../templates/components/yebo-checkout';
/**
A single page checkout that reactively responds to changes in the
`yebo.checkouts` service.
**To Override:** You'll need to run the components generator:
```bash
ember g yebo-ember-storefront-components
```
This will install all of the Yebo Ember Storefront component files into your
host application at `app/components/yebo-*.js`, ready to be extended or
overriden.
@class YeboCheckout
@namespace Component
@extends Ember.Component
*/
export default Ember.Component.extend({
layout: layout,
action: 'transitionCheckoutState',
/**
*
*/
init() {
// Call the super
this._super();
// Set initialize it
this.get('checkouts').trigger('checkoutCalled');
},
actions: {
transitionCheckoutState: function(stateName) {
this.sendAction('action', stateName);
}
}
});
|
Fix network service provider functional test
SDK refactor broken network service provider
functional test, tested this command works,
but there is a error in the funtional test,
so fix it.
Change-Id: I783c58cedd39a05b665e47709b2b5321871e558b
Closes-Bug: 1653138 | # Copyright (c) 2016, Intel Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstackclient.tests.functional import base
class TestNetworkServiceProvider(base.TestCase):
"""Functional tests for network service provider"""
SERVICE_TYPE = 'L3_ROUTER_NAT'
def test_network_service_provider_list(self):
raw_output = self.openstack('network service provider list')
self.assertIn(self.SERVICE_TYPE, raw_output)
| # Copyright (c) 2016, Intel Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import testtools
from openstackclient.tests.functional import base
class TestNetworkServiceProvider(base.TestCase):
"""Functional tests for network service provider"""
SERVICE_TYPE = ['L3_ROUTER_NAT']
@testtools.skip('broken SDK testing')
def test_network_service_provider_list(self):
raw_output = self.openstack('network service provider list')
self.assertIn(self.SERVICE_TYPE, raw_output)
|
Add trailing commas (to secretly nudge travis-ci) | /*
* grunt-contrib-watch
* http://gruntjs.com/
*
* Copyright (c) 2013 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/**/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
watch: {
all: {
files: ['<%= jshint.all %>'],
tasks: ['jshint', 'nodeunit'],
},
},
nodeunit: {
tests: ['test/tasks/*_test.js'],
},
});
// Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
grunt.registerTask('test', function(file) {
grunt.config('nodeunit.tests', String(grunt.config('nodeunit.tests')).replace('*', file || '*'));
grunt.task.run('nodeunit');
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-internal');
grunt.registerTask('default', ['jshint', 'nodeunit', 'build-contrib']);
};
| /*
* grunt-contrib-watch
* http://gruntjs.com/
*
* Copyright (c) 2013 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/**/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
watch: {
all: {
files: ['<%= jshint.all %>'],
tasks: ['jshint', 'nodeunit'],
},
},
nodeunit: {
tests: ['test/tasks/*_test.js']
}
});
// Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
grunt.registerTask('test', function(file) {
grunt.config('nodeunit.tests', String(grunt.config('nodeunit.tests')).replace('*', file || '*'));
grunt.task.run('nodeunit');
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-internal');
grunt.registerTask('default', ['jshint', 'nodeunit', 'build-contrib']);
};
|
Make attributes -> attr calls easier to follow | import injectAttr from "./runtime/attr";
import injectForOwn from "./runtime/for-own";
import toFunctionCall from "./ast/to-function-call";
import iDOMMethod from "./idom-method";
// Transforms an attribute array into sequential attr calls.
export default function attrsToAttrCalls(t, file, attrs) {
const forOwn = injectForOwn(t, file);
const forOwnAttr = injectAttr(t, file);
let name = null;
return attrs.reduce((calls, attr) => {
if (t.isJSXSpreadAttribute(attr)) {
calls.push(toFunctionCall(t, forOwn, [attr.argument, forOwnAttr]));
} else {
if (name) {
calls.push(toFunctionCall(t, iDOMMethod(file, "attr"), [name, attr]));
name = null;
} else {
name = attr;
}
}
return calls;
}, []);
}
| import injectAttr from "./runtime/attr";
import injectForOwn from "./runtime/for-own";
import toFunctionCall from "./ast/to-function-call";
import iDOMMethod from "./idom-method";
// Transforms an attribute array into sequential attr calls.
export default function attrsToAttrCalls(t, file, attrs) {
const forOwn = injectForOwn(t, file);
const forOwnAttr = injectAttr(t, file);
let current = [];
return attrs.reduce((calls, attr) => {
if (t.isJSXSpreadAttribute(attr)) {
calls.push(toFunctionCall(t, forOwn, [attr.argument, forOwnAttr]));
} else {
current.push(attr);
if (current.length === 2) {
calls.push(toFunctionCall(t, iDOMMethod(file, "attr"), current));
current = [];
}
}
return calls;
}, []);
}
|
Fix accidental change of fromJSON() to create(). | // If we're in Node.js then require VTTRegion so we can extend it, otherwise assume
// VTTRegion is on the global.
if (typeof module !== "undefined" && module.exports) {
this.VTTRegion = require("./vttregion").VTTRegion;
}
// Extend VTTRegion with methods to convert to JSON, from JSON, and construct a
// VTTRegion from an options object. The primary purpose of this is for use in the
// vtt.js test suite. It's also useful if you need to work with VTTRegions in
// JSON format.
(function(root) {
root.VTTRegion.create = function(options) {
var region = new root.VTTRegion();
for (var key in options) {
if (region.hasOwnProperty(key)) {
region[key] = options[key];
}
}
return region;
};
root.VTTRegion.fromJSON = function(json) {
return this.create(JSON.parse(json));
};
}(this));
| // If we're in Node.js then require VTTRegion so we can extend it, otherwise assume
// VTTRegion is on the global.
if (typeof module !== "undefined" && module.exports) {
this.VTTRegion = require("./vttregion").VTTRegion;
}
// Extend VTTRegion with methods to convert to JSON, from JSON, and construct a
// VTTRegion from an options object. The primary purpose of this is for use in the
// vtt.js test suite. It's also useful if you need to work with VTTRegions in
// JSON format.
(function(root) {
root.VTTRegion.create = function(options) {
var region = new root.VTTRegion();
for (var key in options) {
if (region.hasOwnProperty(key)) {
region[key] = options[key];
}
}
return region;
};
root.VTTRegion.create = function(json) {
return this.create(JSON.parse(json));
};
}(this));
|
Fix Accept-Encoding match (split would result in ' gzip', which doesn't match.
Add minimum_size attribute. | import gzip
import StringIO
from flask import request
class Gzip(object):
def __init__(self, app, compress_level=6, minimum_size=500):
self.app = app
self.compress_level = compress_level
self.minimum_size = minimum_size
self.app.after_request(self.after_request)
def after_request(self, response):
accept_encoding = request.headers.get('Accept-Encoding', '')
if 'gzip' not in accept_encoding.lower():
return response
if (200 > response.status_code >= 300) or len(response.data) < self.minimum_size or 'Content-Encoding' in response.headers:
return response
gzip_buffer = StringIO.StringIO()
gzip_file = gzip.GzipFile(mode='wb', compresslevel=self.compress_level, fileobj=gzip_buffer)
gzip_file.write(response.data)
gzip_file.close()
response.data = gzip_buffer.getvalue()
response.headers['Content-Encoding'] = 'gzip'
response.headers['Content-Length'] = len(response.data)
return response
| import gzip
import StringIO
from flask import request
class Gzip(object):
def __init__(self, app, compress_level=6):
self.app = app
self.compress_level = compress_level
self.app.after_request(self.after_request)
def after_request(self, response):
accept_encoding = request.headers.get('Accept-Encoding', '')
if not accept_encoding:
return response
encodings = accept_encoding.split(',')
if 'gzip' not in encodings:
return response
if (200 > response.status_code >= 300) or len(response.data) < 500 or 'Content-Encoding' in response.headers:
return response
gzip_buffer = StringIO.StringIO()
gzip_file = gzip.GzipFile(mode='wb', compresslevel=self.compress_level, fileobj=gzip_buffer)
gzip_file.write(response.data)
gzip_file.close()
response.data = gzip_buffer.getvalue()
response.headers['Content-Encoding'] = 'gzip'
response.headers['Content-Length'] = len(response.data)
return response
|
Fix unneeded float cast and add return type | <?php
namespace OpenDominion\Models;
class Race extends AbstractModel
{
public function dominions()
{
return $this->hasMany(Dominion::class);
}
public function perks()
{
return $this->hasMany(RacePerk::class);
}
public function units()
{
return $this->hasMany(Unit::class)->orderBy('slot')->limit(4);
}
/**
* Gets a Race's perk multiplier.
*
* @param string $key
* @return float
*/
public function getPerkMultiplier($key): float
{
$perks = $this->perks->filter(function (RacePerk $racePerk) use ($key) {
return ($racePerk->type->key === $key);
});
if ($perks->isEmpty()) {
return (float)0;
}
return ((float)$perks->first()->value / 100);
}
}
| <?php
namespace OpenDominion\Models;
class Race extends AbstractModel
{
public function dominions()
{
return $this->hasMany(Dominion::class);
}
public function perks()
{
return $this->hasMany(RacePerk::class);
}
public function units()
{
return $this->hasMany(Unit::class)->orderBy('slot')->limit(4);
}
/**
* Gets a Race's perk multiplier.
*
* @param string $key
* @return float
*/
public function getPerkMultiplier($key)
{
$perks = $this->perks->filter(function (RacePerk $racePerk) use ($key) {
return ($racePerk->type->key === $key);
});
if ($perks->isEmpty()) {
return (float)0;
}
return (float)((float)$perks->first()->value / 100);
}
}
|
Add Emittery back into the event mangager | const { ReporterAggregator } = require("truffle-reporters");
const Emittery = require("emittery");
class EventManager {
constructor(eventManagerOptions) {
const { logger, muteReporters, globalConfig } = eventManagerOptions;
// Keep a reference to these so it can be cloned
// if necessary in truffle-config
this.initializationOptions = eventManagerOptions;
const emitter = new Emittery();
this.emitter = emitter;
const initializationOptions = {
emitter,
globalConfig,
logger,
muteReporters
};
this.initializeSubscribers(initializationOptions);
}
emit(event, data) {
if (this.reporters) this.reporters.emit(event, data);
}
initializeReporters(initializationOptions) {
this.reporters = new ReporterAggregator(initializationOptions);
}
initializeSubscribers(initializationOptions) {
const { muteReporters } = initializationOptions;
if (!muteReporters) this.initializeReporters(initializationOptions);
}
}
module.exports = EventManager;
| const { ReporterAggregator } = require("truffle-reporters");
class EventManager {
constructor(eventManagerOptions) {
const { logger, muteReporters, globalConfig } = eventManagerOptions;
// Keep a reference to these so it can be cloned
// if necessary in truffle-config
this.initializationOptions = eventManagerOptions;
const initializationOptions = {
globalConfig,
logger,
muteReporters
};
this.initializeSubscribers(initializationOptions);
}
emit(event, data) {
if (this.reporters) this.reporters.emit(event, data);
}
initializeReporters(initializationOptions) {
this.reporters = new ReporterAggregator(initializationOptions);
}
initializeSubscribers(initializationOptions) {
const { muteReporters } = initializationOptions;
if (!muteReporters) this.initializeReporters(initializationOptions);
}
}
module.exports = EventManager;
|
Fix wrong install requirement name. | #!/usr/bin/env python
# coding=utf-8
__author__ = 'kulakov.ilya@gmail.com'
from setuptools import setup
setup(name="Power",
version="1.0",
description="Cross-platform system power status information.",
author="Ilya Kulakov",
author_email="kulakov.ilya@gmail.com",
url="https://github.com/Kentzo/Power",
platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"],
packages=['power'],
classifiers=[
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Topic :: System :: Power (UPS)',
'Topic :: System :: Hardware',
'Topic :: System :: Monitoring'
],
install_requires=['pyobjc == 2.3']
)
| #!/usr/bin/env python
# coding=utf-8
__author__ = 'kulakov.ilya@gmail.com'
from setuptools import setup
setup(name="Power",
version="1.0",
description="Cross-platform system power status information.",
author="Ilya Kulakov",
author_email="kulakov.ilya@gmail.com",
url="https://github.com/Kentzo/Power",
platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"],
packages=['power'],
classifiers=[
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Topic :: System :: Power (UPS)',
'Topic :: System :: Hardware',
'Topic :: System :: Monitoring'
],
install_requires=['pyobjc-core == 2.3.2a0']
)
|
Add Python 2 trove classifier | from setuptools import setup
try:
readme = open("README.rst")
long_description = str(readme.read())
finally:
readme.close()
setup(name='itolapi',
version='1.1.2',
description='API for interacting with itol.embl.de',
long_description=long_description,
url='http://github.com/albertyw/itolapi',
author='Albert Wang',
author_email='albertyw@mit.edu',
license='MIT',
packages=['itolapi'],
install_requires=[
'urllib2_file==0.2.1',
],
scripts=['itolapi/Itol.py', 'itolapi/ItolExport.py'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2 :: Only',
'Topic :: Scientific/Engineering :: Bio-Informatics',
],
)
| from setuptools import setup
try:
readme = open("README.rst")
long_description = str(readme.read())
finally:
readme.close()
setup(name='itolapi',
version='1.1.2',
description='API for interacting with itol.embl.de',
long_description=long_description,
url='http://github.com/albertyw/itolapi',
author='Albert Wang',
author_email='albertyw@mit.edu',
license='MIT',
packages=['itolapi'],
install_requires=[
'urllib2_file==0.2.1',
],
scripts=['itolapi/Itol.py', 'itolapi/ItolExport.py'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Topic :: Scientific/Engineering :: Bio-Informatics',
],
)
|
Remove repositoryUrl as a parameter in comment | <?php
namespace Accompli\Chrono\Adapter;
/**
* AdapterInterface.
*
* @author Niels Nijens <nijens.niels@gmail.com>
*/
interface AdapterInterface
{
/**
* Returns true when the adapter supports the repository URL.
*
* @return bool
*/
public function supportsRepository();
/**
* Returns the list of branches from the repository.
*
* @return array
*/
public function getBranches();
/**
* Returns the list of tags from the repository.
*
* @return array
*/
public function getTags();
/**
* Checks out a branch or tag from the repository.
*
* @param string $version
*
* @return bool
*/
public function checkout($version);
}
| <?php
namespace Accompli\Chrono\Adapter;
/**
* AdapterInterface.
*
* @author Niels Nijens <nijens.niels@gmail.com>
*/
interface AdapterInterface
{
/**
* Returns true when the adapter supports the repository URL.
*
* @param string $repositoryUrl
*
* @return bool
*/
public function supportsRepository();
/**
* Returns the list of branches from the repository.
*
* @return array
*/
public function getBranches();
/**
* Returns the list of tags from the repository.
*
* @return array
*/
public function getTags();
/**
* Checks out a branch or tag from the repository.
*
* @param string $version
*
* @return bool
*/
public function checkout($version);
}
|
Return appropriate error from getWidth() | package gohr
import (
"fmt"
"log"
"os"
"golang.org/x/crypto/ssh/terminal"
)
// getWidth gets number of width of terminal from crypto subdirectory ssh/terminal
func getWidth() (int, error) {
w, _, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
return -1, err
}
return w, nil
}
// Draw fills a row with '#' by default (if no arguments are provided) or takes arguments and prints each pattern on a new line.
func Draw(args ...string) {
w, err := getWidth()
if err != nil {
log.Fatalf("Error getting terminal width: %s\n", err)
}
if len(args) == 0 {
for i := 0; i < w; i++ {
fmt.Printf("#")
}
fmt.Printf("\n")
} else {
for _, arg := range args {
l := len(arg)
for i := 0; i < w/l; i++ {
fmt.Printf(arg)
}
// Fills up the remaining columns in the row with part of the pattern
fmt.Printf("%s\n", arg[:w%l])
}
}
}
| package gohr
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
//get number of columns of terminal from crypto subdirectory ssh/terminal
func getCols() int {
c, _, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
panic(err)
}
return c
}
// DrawHr fills a row with '#' by default (if no arguments are provided) or take command line arguments and print each pattern on a new line
func DrawHr(args ...string) {
cols := getCols()
if len(args) == 0 {
for i := 0; i < cols; i++ {
fmt.Printf("#")
}
fmt.Println()
} else {
for _, arg := range args {
l := len(arg)
for i := 0; i < cols/l; i++ {
fmt.Printf(arg)
}
// Fill ups the remaining columns in the row with part of the pattern
fmt.Printf("%v\n", arg[:cols%l])
}
}
}
|
Remove redundant class loader register call | <?php
/*
* This file is part of Evenement.
*
* Copyright (c) 2011 Igor Wiedler
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('Evenement\Tests', __DIR__);
| <?php
/*
* This file is part of Evenement.
*
* Copyright (c) 2011 Igor Wiedler
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('Evenement\Tests', __DIR__);
$loader->register();
|
Bump flask from 0.10.1 to 1.0
Bumps [flask](https://github.com/pallets/flask) from 0.10.1 to 1.0.
- [Release notes](https://github.com/pallets/flask/releases)
- [Changelog](https://github.com/pallets/flask/blob/main/CHANGES.rst)
- [Commits](https://github.com/pallets/flask/compare/0.10.1...1.0)
---
updated-dependencies:
- dependency-name: flask
dependency-type: direct:production
...
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com> | # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="myapp",
version='0.0.1-dev',
description='My Awesome Application',
author='**INSERT_AUTHOR_NAME**',
author_email='**INSERT_AUTHOR_EMAIL**',
packages=[
'myapp',
'myapp.blueprints'
],
url='https://www.github.com/codehugger/myapp',
include_package_data=True,
zip_safe=False,
install_requires=[
'Flask==1.0',
'Flask-Migrate==1.2.0',
'Flask-SQLAlchemy==1.0',
'Flask-Script==0.6.7',
'Flask-Testing==0.4.1',
'Jinja2==2.7.2',
'Mako==0.9.1',
'MarkupSafe==0.19',
'SQLAlchemy==0.9.4',
'Werkzeug==0.9.4',
'alembic==0.6.4',
'itsdangerous==0.24',
'wsgiref==0.1.2',
]
)
| # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="myapp",
version='0.0.1-dev',
description='My Awesome Application',
author='**INSERT_AUTHOR_NAME**',
author_email='**INSERT_AUTHOR_EMAIL**',
packages=[
'myapp',
'myapp.blueprints'
],
url='https://www.github.com/codehugger/myapp',
include_package_data=True,
zip_safe=False,
install_requires=[
'Flask==0.10.1',
'Flask-Migrate==1.2.0',
'Flask-SQLAlchemy==1.0',
'Flask-Script==0.6.7',
'Flask-Testing==0.4.1',
'Jinja2==2.7.2',
'Mako==0.9.1',
'MarkupSafe==0.19',
'SQLAlchemy==0.9.4',
'Werkzeug==0.9.4',
'alembic==0.6.4',
'itsdangerous==0.24',
'wsgiref==0.1.2',
]
)
|
Refactor and complement yeoman.test.createGenerator tests | /*global it, describe, before, beforeEach */
var util = require('util');
var assert = require('assert');
var yeoman = require('..');
var helpers = yeoman.test;
describe('yeoman.test', function () {
'use strict';
beforeEach(function () {
var self = this;
this.StubGenerator = function (args, options) {
self.args = args;
self.options = options;
};
util.inherits(this.StubGenerator, yeoman.Base);
});
describe('#createGenerator', function () {
it('create a new generator', function () {
var generator = helpers.createGenerator('unicorn:app', [
[this.StubGenerator, 'unicorn:app']
]);
assert.ok(generator instanceof this.StubGenerator);
});
it('pass args params to the generator', function () {
helpers.createGenerator('unicorn:app', [
[this.StubGenerator, 'unicorn:app']
], ['temp']);
assert.deepEqual(this.args, ['temp']);
});
it('pass options param to the generator', function () {
helpers.createGenerator('unicorn:app', [
[this.StubGenerator, 'unicorn:app']
], ['temp'], {ui: 'tdd'});
assert.equal(this.options.ui, 'tdd');
});
});
});
| /*global it, describe, before, beforeEach */
var util = require('util');
var assert = require('assert');
var generators = require('..');
var helpers = require('../').test;
describe('yeoman.generators.test', function () {
'use strict';
var Unicorn;
beforeEach(function () {
var self = this;
Unicorn = function (args, options) {
self.args = args;
self.options = options;
generators.Base.apply(this, arguments);
};
util.inherits(Unicorn, generators.Base);
});
describe('helpers.createGenerator', function () {
it('with args params', function () {
helpers.createGenerator('unicorn:app', [
[Unicorn, 'unicorn:app']
], ['temp']);
// assert.ok();
assert.deepEqual(this.args, ['temp']);
});
it('with options param', function () {
helpers.createGenerator('unicorn:app', [
[Unicorn, 'unicorn:app']
], ['temp'], {ui: 'tdd'});
assert.equal(this.options.ui, 'tdd');
});
});
});
|
Remove IE10 specific Spice file | //= require jquery
//= require spice-html5-bower
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
$('#ctrlaltdel').click(sendCtrlAltDel);
var spice = new SpiceMainConn({
uri: (encrypt ? 'wss://' : 'ws://') + host + ':' + port + '/' + $('#remote-console').attr('data-url'),
screen_id: "remote-console",
password: $('#remote-console').attr('data-secret'),
onerror: function(e) {
spice.stop();
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error("SPICE", e);
},
onsuccess: function() {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
},
});
});
| //= require jquery
//= require spice-html5-bower/spiceHTML5/spicearraybuffer
//= require spice-html5-bower
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
$('#ctrlaltdel').click(sendCtrlAltDel);
var spice = new SpiceMainConn({
uri: (encrypt ? 'wss://' : 'ws://') + host + ':' + port + '/' + $('#remote-console').attr('data-url'),
screen_id: "remote-console",
password: $('#remote-console').attr('data-secret'),
onerror: function(e) {
spice.stop();
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error("SPICE", e);
},
onsuccess: function() {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
},
});
});
|
Allow dashes in proposal kind slugs
We can see from the setting PROPOSAL_FORMS that at least one proposal kind,
Sponsor Tutorial, has a slug with a dash in it: sponsor-tutorial. Yet the
URL pattern for submitting a proposal doesn't accept dashes in the slug.
Fix it. | from django.conf.urls import patterns, url
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"),
url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"),
url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"),
url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"),
url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"),
url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"),
url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"),
url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"),
url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"),
)
| from django.conf.urls.defaults import *
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"),
url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"),
url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"),
url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"),
url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"),
url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"),
url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"),
url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"),
url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"),
)
|
Fix handling of image tag sources | var performImage = function() {
var t=[];
function prepareString(withUrl) {
return '<a href="' + withUrl + '"><img title="'+ withUrl +'" src="' + withUrl + '"></a>';
}
// Image tags are the easiest to do. Loop thru the set, and pull up the images out
Array.prototype.slice.call(document.getElementsByTagName('img')).forEach(function(imgTag) {
t.push(prepareString(imgTag.src));
});
// now inspect elements that are applied to background elements
var reImg = /^url\(\"/;
Array.prototype.slice.call(document.querySelectorAll('body *')).filter(function(element) {
// check for cases where no image is defined
return window.getComputedStyle(element).backgroundImage !== 'none';
}).filter(function(element) {
// find elements that are inline images
return reImg.test(window.getComputedStyle(element).backgroundImage);
}).map(function(element) {
// trim CSS wrapping for URLs
return window.getComputedStyle(element).backgroundImage.split('url("')[1].slice(0, -2);
}).forEach(function(url) {
// push to result array
t.push(prepareString(url));
});
return t.length ? t.join('') : '<h1>No Images Present</h1>';
};
| var performImage = function() {
var t=[];
function prepareString(withUrl) {
return '<a href="' + withUrl + '"><img title="'+ withUrl +'" src="' + withUrl + '"></a>';
}
// Image tags are the easiest to do. Loop thru the set, and pull up the images out
Array.prototype.slice.call(document.getElementsByTagName('img')).forEach(function(imgTag) {
t.push(prepareString(imgTag));
});
// now inspect elements that are applied to background elements
var reImg = /^url\(\"/;
Array.prototype.slice.call(document.querySelectorAll('body *')).filter(function(element) {
// check for cases where no image is defined
return window.getComputedStyle(element).backgroundImage !== 'none';
}).filter(function(element) {
// find elements that are inline images
return reImg.test(window.getComputedStyle(element).backgroundImage);
}).map(function(element) {
// trim CSS wrapping for URLs
return window.getComputedStyle(element).backgroundImage.split('url("')[1].slice(0, -2);
}).forEach(function(url) {
// push to result array
t.push(prepareString(url));
});
return t.length ? t.join('') : '<h1>No Images Present</h1>';
};
|
Add another class to Quote block for consistency
Heading block has an analogous version of this, so added here too for consistency. | /*
Block Quote
*/
SirTrevor.Blocks.Quote = (function(){
var template = _.template([
'<blockquote class="st-required st-text-block st-text-block--quote" contenteditable="true"></blockquote>',
'<label class="st-input-label"> <%= i18n.t("blocks:quote:credit_field") %></label>',
'<input maxlength="140" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"',
' class="st-input-string st-required js-cite-input" type="text" />'
].join("\n"));
return SirTrevor.Block.extend({
type: 'Quote',
title: function(){ return i18n.t('blocks:quote:title'); },
icon_name: 'quote',
editorHTML: function() {
return template(this);
},
loadData: function(data){
this.getTextBlock().html(SirTrevor.toHTML(data.text, this.type));
this.$('.js-cite-input').val(data.cite);
},
toMarkdown: function(markdown) {
return markdown.replace(/^(.+)$/mg,"> $1");
}
});
})();
| /*
Block Quote
*/
SirTrevor.Blocks.Quote = (function(){
var template = _.template([
'<blockquote class="st-required st-text-block" contenteditable="true"></blockquote>',
'<label class="st-input-label"> <%= i18n.t("blocks:quote:credit_field") %></label>',
'<input maxlength="140" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"',
' class="st-input-string st-required js-cite-input" type="text" />'
].join("\n"));
return SirTrevor.Block.extend({
type: 'Quote',
title: function(){ return i18n.t('blocks:quote:title'); },
icon_name: 'quote',
editorHTML: function() {
return template(this);
},
loadData: function(data){
this.getTextBlock().html(SirTrevor.toHTML(data.text, this.type));
this.$('.js-cite-input').val(data.cite);
},
toMarkdown: function(markdown) {
return markdown.replace(/^(.+)$/mg,"> $1");
}
});
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.