text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add option for multiple inner expectations | <?php
namespace Matthias\Codesniffer\Sequence\Expectation;
use Matthias\Codesniffer\Sequence\Exception\ExpectationNotMatched;
use Matthias\Codesniffer\Sequence\SequenceInterface;
class Quantity implements ExpectationInterface
{
const ANY = null;
/**
* @var $innerExpectation ExpectationInterface[]
... | <?php
namespace Matthias\Codesniffer\Sequence\Expectation;
use Matthias\Codesniffer\Sequence\Exception\ExpectationNotMatched;
use Matthias\Codesniffer\Sequence\SequenceInterface;
class Quantity implements ExpectationInterface
{
const ANY = null;
private $innerExpectation;
private $minimum;
private $... |
fix(suspension/actionButton): Reorder action button in toolbar
related to CAM-1403 | ngDefine('cockpit.plugin.base.views', ['require'], function(module, require) {
var Controller = [ '$scope', '$dialog',
function($scope, $dialog) {
$scope.openDialog = function () {
var dialog = $dialog.dialog({
resolve: {
processData: function() { return $scope.processData; }... | ngDefine('cockpit.plugin.base.views', ['require'], function(module, require) {
var Controller = [ '$scope', '$dialog',
function($scope, $dialog) {
$scope.openDialog = function () {
var dialog = $dialog.dialog({
resolve: {
processData: function() { return $scope.processData; }... |
Fix bug where client didn't use proper host name | import React, { Component } from 'react';
import SocketIOClient from 'socket.io-client';
import logo from '../assets/logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.socket = SocketIOClient(location.origin);
this.keyPressEvent = this.keyPressEvent.bind(... | import React, { Component } from 'react';
import SocketIOClient from 'socket.io-client';
import logo from '../assets/logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.socket = SocketIOClient('http://localhost:3000');
this.keyPressEvent = this.keyPressEve... |
Add migrations folder to build. | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-oidc-provider',
version='0.... | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-oidc-provider',
version='0.... |
Switch from fetch to beacon | document
.querySelectorAll('pre')
.forEach(node => {
node.title = 'Copy to clipboard';
node.classList.add('copy');
node.onclick = function (event) {
navigator.clipboard.writeText(event.target.innerText);
};
});
(function () {
const themes = [ 'light', 'dark', 'markdown' ];
l... | document
.querySelectorAll('pre')
.forEach(node => {
node.title = 'Copy to clipboard';
node.classList.add('copy');
node.onclick = function (event) {
navigator.clipboard.writeText(event.target.innerText);
};
});
(function () {
const themes = [ 'light', 'dark', 'markdown' ];
l... |
Update cookie-based login process event
エラーログによると、クッキーベースのログインをしたとき、
ログイン履歴を保存するためのフック関数において
https://github.com/fetus-hina/stat.ink/blob/ec679de7b6402be34edbff51a4b54b8cd6046a87/config/web/user.php#L38
の identity プロパティが見つからない時があるらしい。
この identity は \yii\web\User によって提供される getIdentity() の呼び出しになるはずなので
見つからないはずがないのだが、記録さ... | <?php
declare(strict_types=1);
use app\components\web\User;
use app\models\LoginMethod;
use app\models\User as UserModel;
use app\models\UserLoginHistory;
use yii\web\ServerErrorHttpException;
use yii\web\UserEvent;
return (function (): array {
$authKeyFile = dirname(__DIR__) . '/authkey-secret.php';
$authKey... | <?php
declare(strict_types=1);
use app\components\web\User;
use app\models\LoginMethod;
use app\models\User as UserModel;
use app\models\UserLoginHistory;
use yii\web\UserEvent;
return (function (): array {
$authKeyFile = dirname(__DIR__) . '/authkey-secret.php';
$authKeySecret = @file_exists($authKeyFile)
... |
Use correct command in docblock type hint | <?php declare(strict_types=1);
namespace ApiClients\Client\Github\CommandBus\Handler\Repository;
use ApiClients\Client\AppVeyor\AsyncClient;
use ApiClients\Client\AppVeyor\Resource\ProjectInterface;
use ApiClients\Client\Github\CommandBus\Command\Repository\AppVeyorCommand;
use React\Promise\Promise;
use React\Promis... | <?php declare(strict_types=1);
namespace ApiClients\Client\Github\CommandBus\Handler\Repository;
use ApiClients\Client\AppVeyor\AsyncClient;
use ApiClients\Client\AppVeyor\Resource\ProjectInterface;
use ApiClients\Client\Github\CommandBus\Command\Repository\AppVeyorCommand;
use ApiClients\Client\Github\CommandBus\Com... |
Add support for Select placeholder option customization without `option.value: ''`
Fixes #72 | import React from 'react'
//
import { buildHandler } from './util'
import FormInput from '../formInput'
export default function FormInputSelect ({
options,
field,
showErrors,
errorBefore,
onChange,
onBlur,
isForm,
noTouch,
errorProps,
placeholder,
...rest
}) {
return (
<FormInput
fiel... | import React from 'react'
//
import { buildHandler } from './util'
import FormInput from '../formInput'
export default function FormInputSelect ({
options,
field,
showErrors,
errorBefore,
onChange,
onBlur,
isForm,
noTouch,
errorProps,
...rest
}) {
return (
<FormInput
field={field}
... |
Remove emitter from cache if disposed | package org.adridadou.ethereum.propeller.event;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* Created by davidroon on 19.08.16.
* This c... | package org.adridadou.ethereum.propeller.event;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* Created by davidroon on 19.08.16.
* This c... |
Use correct environment markers syntax in the extras_require section.
See https://github.com/pypa/setuptools/issues/1087 | from setuptools import find_packages, setup
from channels import __version__
setup(
name='channels',
version=__version__,
url='http://github.com/django/channels',
author='Django Software Foundation',
author_email='foundation@djangoproject.com',
description="Brings event-driven capabilities to D... | from setuptools import find_packages, setup
from channels import __version__
setup(
name='channels',
version=__version__,
url='http://github.com/django/channels',
author='Django Software Foundation',
author_email='foundation@djangoproject.com',
description="Brings event-driven capabilities to D... |
CL011: Fix checkboxes inform and involved | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
... | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
... |
Remove unused left over parameter | #!/usr/bin/env python3
import json
import sys
import time
from urllib.request import urlopen
STATS_URL = "http://localhost:18001/stats"
MAXIMUM_TIME_SECONDS = 2 * 60
SLEEPING_INTERVAL_SECONDS = 1
STATUS_CODE_OK = 200
def is_initialised():
try:
response = urlopen(STATS_URL)
if (response.getcode()... | #!/usr/bin/env python3
import json
import sys
import time
from urllib.request import urlopen
STATS_URL = "http://localhost:18001/stats"
MAXIMUM_TIME_SECONDS = 2 * 60
SLEEPING_INTERVAL_SECONDS = 1
STATUS_CODE_OK = 200
def is_initialised():
try:
response = urlopen(STATS_URL)
if (response.getcode()... |
Refactor migrations after generating to ensure custom user model compatibility. | #!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)
# Load Django-related settings; necessary for tests t... | #!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)
# Load Django-related settings; necessary for tests t... |
Return str instead of dict. | import json
from flask import abort
from flask import Flask
from flask_caching import Cache
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Pars... | from flask import abort
from flask import Flask
from flask_caching import Cache
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Parser</title>' +... |
Allow a function to be called whenever a candidate blob is found during
image
processing | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config, each_blob=None):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:param each_blob: function, taking a SimpleCV.Blob as an argument, that is called for every candidate blob
:... | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:return: Mask with candidates surrounded in a green rectangle
"""
hsv_image = img.toHSV()
segmented = Image(cv2.inRa... |
Add missing dependency on h5py. | from setuptools import setup
setup(name='keras_tf_multigpu',
version='0.1',
description='Multi-GPU data-parallel training in Keras/TensorFlow',
url='https://github.com/rossumai/keras-multi-gpu',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
... | from setuptools import setup
setup(name='keras_tf_multigpu',
version='0.1',
description='Multi-GPU data-parallel training in Keras/TensorFlow',
url='https://github.com/rossumai/keras-multi-gpu',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
... |
BUG: Write concern bug fix in constantly deleting DB. It's on by default and w=1 does nothing. | """Delete all documents every second forever"""
__author__ = 'tunnell'
import sys
import time
import json
import pymongo
if __name__ == "__main__":
c = pymongo.MongoClient()
db = c.data
collection = db.test
# Key to sort by so we can use an index for quick query
sort_key = [("_id", pymongo.AS... | """Delete all documents every second forever"""
__author__ = 'tunnell'
import sys
import time
import json
import pymongo
if __name__ == "__main__":
c = pymongo.MongoClient()
db = c.data
collection = db.test
# Key to sort by so we can use an index for quick query
sort_key = [("_id", pymongo.AS... |
Simplify implementation of removeObject method. | <?php
namespace SimpleAcl\Object;
use SimpleAcl\Object;
/**
* Implement common function for Role and Resources.
*
*/
abstract class ObjectAggregate
{
/**
* @var Object[]
*/
protected $objects = array();
/**
* @param Object $object
*/
protected function addObject(Object $object)... | <?php
namespace SimpleAcl\Object;
use SimpleAcl\Object;
/**
* Implement common function for Role and Resources.
*
*/
abstract class ObjectAggregate
{
/**
* @var Object[]
*/
protected $objects = array();
/**
* @param Object $object
*/
protected function addObject(Object $object)... |
Fix count check of clusters in $grid | <?php
#
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#
# If we are in compare_hosts, views and decompose_graph context we shouldn't attempt
# any connections to the gmetad
if ( in_arr... | <?php
#
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#
# If we are in compare_hosts, views and decompose_graph context we shouldn't attempt
# any connections to the gmetad
if ( in_arr... |
news: Fix click behavior of like button | function likebutton(el, url) {
var dropdown;
var button;
init();
function init() {
button = el.querySelector('.button');
el.removeAttribute('onmousedown');
el.onmousedown = function(evt) {
toggle();
evt.stopPropagation();
};
dropdown = do... | function likebutton(el, url) {
var dropdown;
var button;
init();
function init() {
button = el.querySelector('.button');
el.removeAttribute('onmousedown');
el.onmousedown = function(evt) {
toggle();
evt.stopPropagation();
};
dropdown = do... |
Add different function to manage recursivity | <?php
require 'vendor/autoload.php';
function checkFirstAvailable($name, $field)
{
if (Member::where($field, $name)->count() == 0)
return $name;
$c = 0;
while (1 < 2) {
$c = $c + 1;
if (Member::where($field, $name . $c)->count() == 0)
return $name . $c;
}
}
Bootstr... | <?php
require 'vendor/autoload.php';
Bootstrap::boot();
$a = Csv::csv2array('example.csv');
foreach ($a as $k => $member) {
if (Member::where('email', $member[2])->count() == 0 AND Member::where('identification', $member[3])->count() == 0) {
$invite = sha1($member[0] . " " . $member[1] . ", " . date('c'... |
Fix issue with state being saved with last value | import React, { Component } from 'react';
import PikadayWrapper from '../../lib-components/PikadayWrapper/PikadayWrapper';
export default class PantryItem extends Component {
constructor(props) {
super(props);
this.state = {
expiration: this.props.item.expiration,
name: thi... | import React, { Component } from 'react';
import PikadayWrapper from '../../lib-components/PikadayWrapper/PikadayWrapper';
export default class PantryItem extends Component {
constructor(props) {
super(props);
this.state = {
expiration: this.props.item.expiration,
name: thi... |
[FEATURE] Use static instantiation with max depth check | <?php
namespace FOS\ElasticaBundle\Serializer;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;
class Callback
{
protected $serializer;
protected $groups;
protected $version;
public function setSerializer($serializer)
{
$this->serializer = $serializer;
... | <?php
namespace FOS\ElasticaBundle\Serializer;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;
class Callback
{
protected $serializer;
protected $groups;
protected $version;
public function setSerializer($serializer)
{
$this->serializer = $serializer;
... |
Rename parameter in interface to be more generic. | <?php
/**
* Interface that collections must implement.
*
* PHP Version 5.3
*
* @copyright (c) 2006-2014 brian ridley
* @author brian ridley <ptlis@ptlis.net>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that wa... | <?php
/**
* Interface that collections must implement.
*
* PHP Version 5.3
*
* @copyright (c) 2006-2014 brian ridley
* @author brian ridley <ptlis@ptlis.net>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that wa... |
Add use-strict to fix old versions of node. | 'use strict';
var fs = require('fs');
var path = require('path');
function getComponentFiles(filename) {
var ext = path.extname(filename);
if (ext === '.js') {
return null;
}
var nameNoExt = path.basename(filename, ext);
var isEntry = 'index' === nameNoExt;
var fileMatch = '('+nameN... | var fs = require('fs');
var path = require('path');
function getComponentFiles(filename) {
var ext = path.extname(filename);
if (ext === '.js') {
return null;
}
var nameNoExt = path.basename(filename, ext);
var isEntry = 'index' === nameNoExt;
var fileMatch = '('+nameNoExt.replace(/\... |
Change function to take ConcreteIntegers | package org.aac.average.java.impl;
import org.aac.average.java.impl.function.Function;
import org.aac.average.java.impl.function.FunctionParameter;
import org.aac.average.java.impl.datatypes.ConcreteInteger;
public class Average {
public static void main(String[] args) {
Function<ConcreteInteger> averageT... | package org.aac.average.java.impl;
import org.aac.average.java.impl.function.Function;
import org.aac.average.java.impl.function.FunctionParameter;
import org.aac.average.java.impl.datatypes.ConcreteInteger;
public class Average {
public static void main(String[] args) {
Function<Integer> average;
... |
Add missing fields in the create game resource. | @extends('layouts.app')
@section('content')
<form class="ui form" action="{{ route('games.store') }}" method="POST">
{{ csrf_field() }}
<div class="field">
<label>
Name: <input name="name" type="text">
</label>
</div>
<div class="field">
... | @extends('layouts.app')
@section('content')
<form class="ui form" action="{{ route('games.store') }}" method="POST">
{{ csrf_field() }}
<div class="field">
<label>
Name: <input name="name" type="text">
</label>
</div>
<div class="field">
... |
Add null as error argument for callback
Refs: #13
PR-URL: https://github.com/metarhia/metasync/pull/152
Reviewed-By: Timur Shemsedinov <6dc7cb6a9fcface2186172df883b5c9ab417ae33@gmail.com> | 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
... | 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
... |
Fix roles for Courses API | (function () {
'use strict';
// Courses controller
angular
.module('courses')
.controller('CoursesController', CoursesController);
CoursesController.$inject = ['$scope', '$state', '$window', 'Authentication', 'courseResolve', 'DepartmentsService'];
function CoursesController ($scope, $state, $windo... | (function () {
'use strict';
// Courses controller
angular
.module('courses')
.controller('CoursesController', CoursesController);
CoursesController.$inject = ['$scope', '$state', '$window', 'Authentication', 'courseResolve', 'DepartmentsService'];
function CoursesController ($scope, $state, $windo... |
Remove public keyword from interface declarations | package org.commcare.android.tasks.templates;
/**
* @author ctsims
*/
public interface CommCareTaskConnector<R> {
/**
* IMPORTANT: Any implementing class of CommCareTaskConnector should be
* implemented such that it will only automatically manage the dialog of a
* connected task IF the task i... | package org.commcare.android.tasks.templates;
/**
* @author ctsims
*/
public interface CommCareTaskConnector<R> {
/**
* IMPORTANT: Any implementing class of CommCareTaskConnector should be
* implemented such that it will only automatically manage the dialog of a
* connected task IF the task i... |
Replace undefined with null as default for index for BufferGeometry | import * as THREE from 'three';
import PropTypes from 'prop-types';
import GeometryDescriptorBase from './GeometryDescriptorBase';
import propTypeInstanceOf from '../../utils/propTypeInstanceOf';
class BufferGeometryDescriptor extends GeometryDescriptorBase {
constructor(react3RendererInstance) {
super(react3Re... | import * as THREE from 'three';
import PropTypes from 'prop-types';
import GeometryDescriptorBase from './GeometryDescriptorBase';
import propTypeInstanceOf from '../../utils/propTypeInstanceOf';
class BufferGeometryDescriptor extends GeometryDescriptorBase {
constructor(react3RendererInstance) {
super(react3Re... |
Move string above the imports so it becomes a docstring | """ Super simple IMS mock.
Just listens on localhost:8080 for the appropriate url, returns a test role and
a dummy JSON response.
"""
from __future__ import print_function, absolute_import, unicode_literals, division
from datetime import datetime, timedelta
from textwrap import dedent
from bottle import Bottle
impo... | from __future__ import print_function, absolute_import, unicode_literals, division
from datetime import datetime, timedelta
from textwrap import dedent
from bottle import Bottle
import pytz
""" Super simple IMS mock.
Just listens on localhost:8080 for the appropriate url, returns a test role and
a dummy JSON respon... |
Remove unused code from line graph view | define([
'extensions/views/graph/graph'
],
function (Graph) {
var LineGraph = Graph.extend({
components: function () {
var labelOptions, yAxisOptions;
if (this.isOneHundredPercent()) {
labelOptions = {
showValues: true,
showValuesPercentage: true,
isLineGraph:... | define([
'extensions/views/graph/graph',
'extensions/views/graph/linelabel'
],
function (Graph, LineLabel) {
var LineGraph = Graph.extend({
components: function () {
var labelComponent, labelOptions, yAxisOptions;
if (this.isOneHundredPercent()) {
labelComponent = LineLabel;
label... |
Add comment to explain the length of the scripts taken into account in DuplicateScripts | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, ... | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, ... |
Fix case converter for receiving multiple arguments | <?php
namespace Omelet\Util;
use Camel\Format;
final class CaseSensor
{
private static $formatters = [];
public static function LowerSnake()
{
return new self(Format\SnakeCase::class);
}
public static function UpperSnake()
{
return new self(Format\ScreamingSnakeCase::class);... | <?php
namespace Omelet\Util;
use Camel\Format;
final class CaseSensor
{
private static $formatters = [];
public static function LowerSnake()
{
return new self(self::getFormatter(Format\SnakeCase::class));
}
public static function UpperSnake()
{
return new self(self::getForma... |
Add get_config as GPIO action | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read', 'get_config')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
... | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_ur... |
Fix demo for <SplitView> to match prop changes of <ColumnView> | import React from 'react';
import SplitView from '@ichef/gypcrete/src/SplitView';
import SplitViewColumn from '@ichef/gypcrete/src/SplitViewColumn';
import DebugBox from 'utils/DebugBox';
import ColoredBox from 'utils/ColoredBox';
import DemoColumnView from './DemoColumnView';
function InsideColumnView() {
retu... | import React from 'react';
import SplitView from '@ichef/gypcrete/src/SplitView';
import SplitViewColumn from '@ichef/gypcrete/src/SplitViewColumn';
import DebugBox from 'utils/DebugBox';
import ColoredBox from 'utils/ColoredBox';
import DemoColumnView from './DemoColumnView';
function InsideColumnView() {
retu... |
Add RFS to `sendgrid` test | import sendgrid
import os
from flask import request, Flask
app = Flask(__name__)
@app.route("/sendgrid")
def send():
sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
data = {
"content": [
{
"type": "text/html",
"value": "<html>{}</html>"... | # This tests that the developer doesn't pass tainted user data into the mail.send.post() method in the SendGrid library.
import sendgrid
import os
sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
data = {
"content": [
{
"type": "text/html",
"value": "<html><p>He... |
Add handling of online/offline event | import React from 'react';
import {Link} from 'react-router';
export default class Header extends React.Component {
constructor() {
super();
this.state = {online: navigator.onLine};
}
componentDidMoun() {
window.addEventListener('online', this.updateOnlineState.bind(this));
window.addEventListe... | import React from 'react';
import {Link} from 'react-router';
export default class Header extends React.Component {
render() {
var offline = false;
if (!navigator.onLine) offline = (<span className="offline">offline</span>);
return (
<div className="header">
<div className="container">
... |
Throw Exception if is empty | <?php
namespace marmelab\NgAdminGeneratorBundle\Generator;
use Doctrine\ORM\EntityManagerInterface;
use marmelab\NgAdminGeneratorBundle\Transformer\TransformerInterface;
class ConfigurationGenerator
{
private $em;
private $twig;
/** @var TransformerInterface[] */
private $transformers = [];
pub... | <?php
namespace marmelab\NgAdminGeneratorBundle\Generator;
use Doctrine\ORM\EntityManagerInterface;
use marmelab\NgAdminGeneratorBundle\Transformer\TransformerInterface;
class ConfigurationGenerator
{
private $em;
private $twig;
/** @var TransformerInterface[] */
private $transformers = [];
pub... |
Update Core dependency to v27 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.7.0",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.7.0",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... |
Fix missing serialized name annotation | package co.phoenixlab.discord.api.entities;
import com.google.gson.annotations.SerializedName;
public class ReadyMessage {
@SerializedName("v")
private int version;
private User user;
@SerializedName("session_id")
private String sessionId;
@SerializedName("read_state")
private ReadState[... | package co.phoenixlab.discord.api.entities;
import com.google.gson.annotations.SerializedName;
public class ReadyMessage {
@SerializedName("v")
private int version;
private User user;
private String sessionId;
@SerializedName("read_state")
private ReadState[] readState;
@SerializedName("... |
Fix js error when using node < 4.x | var is = require('is');
var Immutable = require('immutable');
var Promise = require('../../utils/promise');
var editHTMLElement = require('./editHTMLElement');
/**
Return language for a code blocks from a list of class names
@param {Array<String>}
@return {String}
*/
function getLanguageForClass(classNam... | var is = require('is');
var Promise = require('../../utils/promise');
var editHTMLElement = require('./editHTMLElement');
/**
Return language for a code blocks from a list of class names
@param {Array<String>}
@return {String}
*/
function getLanguageForClass(classNames) {
return classNames
.ma... |
Test Head Behavior: Apply new HLM | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from humanoid_league_msgs.msg import BallInImage, BallRelative, BallInImageArray
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
def run():
pub_ball = rospy.Publisher("ball_in_image", BallsInImage, queue_size=1)
pub_hmg = rospy.... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import rospy
from humanoid_league_msgs.msg import BallInImage, BallRelative, BallsInImage
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
def run():
pub_ball = rospy.Publisher("ball_in_image", BallsInImage, queue_size=1)
pub_hmg = rospy.Publ... |
Use build() result for test | !function (assert, path) {
'use strict';
require('vows').describe('Integration test').addBatch({
'When minifying a CSS file': {
topic: function () {
var callback = this.callback,
topic;
require('publishjs')({
cache: fa... | !function (assert, path) {
'use strict';
require('vows').describe('Integration test').addBatch({
'When minifying a CSS file': {
topic: function () {
var callback = this.callback,
topic;
require('publishjs')({
cache: fa... |
Install requires pycryptodome, not pycrypto
PyCrypto version on PyPi is 2.6, but sjcl requires 2.7.
PyCrypto is not maintained. PyCryptodome is a drop in replacement.
A fresh install of sjcl with PyCrypto in Python 3.6.1 on macOS results
in error on:
File "/Users/jthetzel/.local/src/py_test/venv/lib/python3.6/
si... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('pandoc -o README.rst README.md')
os.system('python setup.py sdist upload')
sys.exit()
README = open(... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('pandoc -o README.rst README.md')
os.system('python setup.py sdist upload')
sys.exit()
README = open(... |
Return invalid if payment method is not supported yet | from mhvdb2.models import Payment, Entity
import re
from datetime import datetime
from peewee import DoesNotExist
def validate(amount, email, method, type, notes, reference):
errors = []
if not amount or not amount.isdigit() or int(amount) <= 0:
errors.append("Sorry, you need to provide a valid amoun... | from mhvdb2.models import Payment, Entity
import re
from datetime import datetime
from peewee import DoesNotExist
def validate(amount, email, method, type, notes, reference):
errors = []
if not amount or not amount.isdigit() or int(amount) <= 0:
errors.append("Sorry, you need to provide a valid amoun... |
Use Launchpad page as URL | from setuptools import setup, find_packages
from setuptools.command.install import install as Install
import re
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("axiom/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
class InstallAndRegenerate(Install):... | from setuptools import setup, find_packages
from setuptools.command.install import install as Install
import re
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("axiom/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
class InstallAndRegenerate(Install):... |
Add web middleware to route | <?php
namespace Gregoriohc\Preview;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
class PreviewServiceProvider extends LaravelServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $def... | <?php
namespace Gregoriohc\Preview;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
class PreviewServiceProvider extends LaravelServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $def... |
Use importlib to take place of im module
The imp module is deprecated[1] since version 3.4, use importlib to
instead
1: https://docs.python.org/3/library/imp.html#imp.reload
Change-Id: Ic126bc8e0936e5d7a2c7a910b54b7348026fedcb | # 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... | # 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... |
Move Nut extension command from TableHelper to Table | <?php
namespace Bolt\Nut;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Nut command to list all installed extensions
*/
class Extensions extends BaseCommand
{
/**
* @see \Symfony\Component\Console... | <?php
namespace Bolt\Nut;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Nut command to list all installed extensions
*/
class Extensions extends BaseCommand
{
/**
* @see \Symfony\Component\Console\Command\Command::configure()
*/
pr... |
Correct cloud type checker in TUI for localhost
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com> | from conjureup import events, utils
from conjureup.app_config import app
from . import common
class CredentialsController(common.BaseCredentialsController):
def render(self):
if app.provider.cloud_type == 'lxd':
# no credentials required for localhost
self.finish()
elif no... | from conjureup import events, utils
from conjureup.app_config import app
from . import common
class CredentialsController(common.BaseCredentialsController):
def render(self):
if app.provider.cloud_type == 'localhost':
# no credentials required for localhost
self.finish()
e... |
Change validators to allow additional arguments to be given to the functions they are wrapping | import json
from functools import wraps
from twisted.web import http
from jsonschema import Draft4Validator
from vumi_http_retry.workers.api.utils import response
def validate(*validators):
def validator(fn):
@wraps(fn)
def wrapper(api, req, *a, **kw):
errors = []
for v... | import json
from functools import wraps
from twisted.web import http
from jsonschema import Draft4Validator
from vumi_http_retry.workers.api.utils import response
def validate(*validators):
def validator(fn):
@wraps(fn)
def wrapper(api, req, *a, **kw):
errors = []
for v... |
Allow specifying fields for model_details | from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
... | from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for ... |
Improve thread safety with additional checks and a synchronized map. | package io.collap.bryg.environment;
import io.collap.bryg.Template;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class StandardEnvironment implements Environment {
private Map<String, Template> templateMap = Collections.synchronizedMap (new HashMap<String, Template> ());
... | package io.collap.bryg.environment;
import io.collap.bryg.Template;
import java.util.HashMap;
import java.util.Map;
public class StandardEnvironment implements Environment {
private Map<String, Template> templateMap = new HashMap<> ();
private ClassLoader templateClassLoader;
public StandardEnvironment... |
Correct the hostname option (smtpServer) | <?php
namespace duncan3dc\SwiftMailer;
class Mailer extends Email
{
public function __construct(array $options = null)
{
if (!is_array($options)) {
$options = [];
}
if (empty($options["smtpServer"])) {
$hostname = "localhost";
} else {
$hos... | <?php
namespace duncan3dc\SwiftMailer;
class Mailer extends Email
{
public function __construct(array $options = null)
{
if (!is_array($options)) {
$options = [];
}
if (empty($options["hostname"])) {
$hostname = "localhost";
} else {
$hostn... |
Fix setting up legacy Contenttype object
$this->app['storage']->getContenttype($contentType) can return object or array. | <?php
namespace Bolt\Storage;
use Bolt\Storage\Mapping\ContentType;
use Silex\Application;
/**
* Legacy bridge for Content object backward compatibility.
*
* @author Ross Riley <riley.ross@gmail.com>
*/
class ContentLegacyService
{
use Entity\ContentRelationTrait;
use Entity\ContentRouteTrait;
use En... | <?php
namespace Bolt\Storage;
use Bolt\Storage\Mapping\ContentType;
use Silex\Application;
/**
* Legacy bridge for Content object backward compatibility.
*
* @author Ross Riley <riley.ross@gmail.com>
*/
class ContentLegacyService
{
use Entity\ContentRelationTrait;
use Entity\ContentRouteTrait;
use En... |
test(karma): Set tests to run on Crome Canary on CI | // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
var configuration = {
basePath: '',
frameworks: ['jasmine', 'angular-cli'],
plugins: [
require('karma-jasmine'),
require('karma... | // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
var configuration = {
basePath: '',
frameworks: ['jasmine', 'angular-cli'],
plugins: [
require('karma-jasmine'),
require('karma... |
Use submit button type in search posts well. | import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
han... | import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
han... |
Add method for file renaming | const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get write... | const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get write... |
Make ResaleApartmentSerializer return Decoration.name on decoration field.
It allows to show readable value at resale detailed page. | from rest_framework import serializers
from .models import ResaleApartment, ResaleApartmentImage
class ResaleApartmentImageSerializer(serializers.ModelSerializer):
class Meta:
model = ResaleApartmentImage
fields = '__all__'
class ResaleApartmentSerializer(serializers.ModelSerializer):
# ima... | from rest_framework import serializers
from .models import ResaleApartment, ResaleApartmentImage
class ResaleApartmentImageSerializer(serializers.ModelSerializer):
class Meta:
model = ResaleApartmentImage
fields = '__all__'
class ResaleApartmentSerializer(serializers.ModelSerializer):
# ima... |
Set JSON mode as a requirement explicitly | hqDefine('hqwebapp/js/base_ace', [
'jquery',
'ace-builds/src-min-noconflict/ace',
'ace-builds/src-min-noconflict/mode-json',
], function (
$,
ace,
jsonMode
) {
var initAceEditor = function (element, mode, options, value) {
var defaultOptions = {
showPrintMargin: false,
... | hqDefine('hqwebapp/js/base_ace', [
'jquery',
'ace-builds/src-min-noconflict/ace',
], function (
$,
ace
) {
if (!ace.config.get('basePath')) {
var basePath = requirejs.s.contexts._.config.paths["ace-builds/src-min-noconflict/ace"];
ace.config.set("basePath",basePath.substring(0,baseP... |
Add shortcuts for levels and config | <?php declare(strict_types=1);
namespace Rector\Console;
use Jean85\PrettyVersions;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
final class Application extends SymfonyApplication
{
/**
... | <?php declare(strict_types=1);
namespace Rector\Console;
use Jean85\PrettyVersions;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
final class Application extends SymfonyApplication
{
/**
... |
Make cycle detection atomic. No 2 threads should use getInstance at the same time. The lock is shared for all scopes. This is a problem. | package toothpick;
import java.util.Stack;
import java.util.concurrent.locks.ReentrantLock;
import toothpick.config.Binding;
import static java.lang.String.format;
public abstract class Configuration {
public static volatile Configuration instance;
abstract void checkIllegalBinding(Binding binding);
abstrac... | package toothpick;
import java.util.Stack;
import toothpick.config.Binding;
import static java.lang.String.format;
public abstract class Configuration {
public static volatile Configuration instance;
abstract void checkIllegalBinding(Binding binding);
abstract void checkCyclesStart(Class clazz);
abstract... |
Add support for resolving the types | <?php
namespace PHPCfg\Visitor;
use PHPCfg\Visitor;
use PHPCfg\Op;
use PHPCfg\Block;
use PHPCfg\Operand;
class CallFinder implements Visitor {
protected $calls = [];
protected $funcStack = [];
protected $func;
public function getCallsForFunction($func) {
$func = strtolower($func);
... | <?php
namespace PHPCfg\Visitor;
use PHPCfg\Visitor;
use PHPCfg\Op;
use PHPCfg\Block;
use PHPCfg\Operand;
class CallFinder implements Visitor {
protected $calls = [];
protected $funcStack = [];
protected $func;
public function getCallsForFunction($func) {
return isset($this->calls[$func]... |
Add comment for empty catch | <?php
namespace Kevinrob\GuzzleCache\Storage;
use Doctrine\Common\Cache\Cache;
use Kevinrob\GuzzleCache\CacheEntry;
class DoctrineCacheWrapper implements CacheStorageInterface
{
/**
* @var Cache
*/
protected $cache;
/**
* @param Cache $cache
*/
public function __construct(Cache... | <?php
namespace Kevinrob\GuzzleCache\Storage;
use Doctrine\Common\Cache\Cache;
use Kevinrob\GuzzleCache\CacheEntry;
class DoctrineCacheWrapper implements CacheStorageInterface
{
/**
* @var Cache
*/
protected $cache;
/**
* @param Cache $cache
*/
public function __construct(Cache... |
Fix typo and minor formatting. | # -*- coding: utf-8 -*-
import os
import pprint
import warnings
from gpn.node import Node
suffix = '.node'
suffix_default = '.node-default'
class Graph(object):
def __init__(self, path=None, nodes=None):
global suffix
global suffix_default
assert not path or not nodes, ('Cannot specify b... | # -*- coding: utf-8 -*-
import os
import pprint
import warnings
from gpn.node import Node
suffix = '.node'
suffix_default = '.node-default'
class Graph(object):
def __init__(self, path=None, nodes=None):
global suffix
global suffix_default
assert not path or not nodes, ('Cannot specify b... |
Fix potential performance issue reported by FindBugs | package net.onrc.onos.ofcontroller.linkdiscovery.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.floodlightcontroller.routing.Link;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
import net.onrc.onos.of... | package net.onrc.onos.ofcontroller.linkdiscovery.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.floodlightcontroller.routing.Link;
import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
import net.onrc.onos.ofcontroller.linkdiscovery.Lin... |
Fix to work with DataObjects | <?php
class TestimonialsExtension extends SiteTreeExtension
{
private static $has_many = [
'Testimonials' => 'Testimonial'
];
public function updateCMSFields(FieldList $fields)
{
/** @var GridFieldConfig $gridConfig */
$gridConfig = GridFieldConfig::create();
$gridCo... | <?php
class TestimonialsExtension extends SiteTreeExtension
{
private static $has_many = [
'Testimonials' => 'Testimonial'
];
public function updateCMSFields(FieldList $fields)
{
/** @var GridFieldConfig $gridConfig */
$gridConfig = GridFieldConfig::create();
$gridCo... |
Add provenance type as item to reset. | Application.Services.factory('toggleDragButton', [toggleDragButton]);
function toggleDragButton() {
var service = {
addToReview: {
'samples': false,
'notes': false,
'files': false,
'provenance': false
},
addToProv: {
samples: false... | Application.Services.factory('toggleDragButton', [toggleDragButton]);
function toggleDragButton() {
var service = {
addToReview: {
'samples': false,
'notes': false,
'files': false,
'provenance': false
},
toggle: function (type, button) {
... |
Check if app is mounted | import React, { Component } from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import ImgurImage from './ImgurImage';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0};
... | import React, { Component } from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import ImgurImage from './ImgurImage';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0};
... |
Remove accidentally committed test code | package me.williamhester.reddit.ui.activities;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import me.williamhester.reddit.R;
import me.williamhester.reddit.models.Submission;
import me.williamhester.reddit.ui.fragments.CommentsFragment;
/** Activity that holds basic content. */
public class Con... | package me.williamhester.reddit.ui.activities;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import me.williamhester.reddit.R;
import me.williamhester.reddit.models.Submission;
import me.williamhester.reddit.ui.fragments.CommentsFragment;
/** Activity tha... |
doc: Use route for links to documents | @extends('layouts.app')
@section('title', 'Index')
@section('content')
<div class="row">
@if ($data['num_doc'] > 0)
<div class="row">
<div class="col-md-12">
<div class="col-md-offset-9 col-md-3">
Uploaded documents: {{$data['num_doc'... | @extends('layouts.app')
@section('title', 'Index')
@section('content')
<div class="row">
@if ($data['num_doc'] > 0)
<div class="row">
<div class="col-md-12">
<div class="col-md-offset-9 col-md-3">
Uploaded documents: {{$data['num_doc'... |
Add more information to failure message | package com.coronaide.test.ui;
import java.io.IOException;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.coronaide.core.mode... | package com.coronaide.test.ui;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.coronaide.core.model.Project;
import com.coronaide.core.service.IProjectService;
impo... |
Remove unused dependency and variable | var module = angular.module('ldsNavigation', ['ngRoute']);
module.directive('ldsNavigation', [function () {
return {
restrict: "E",
scope: true,
controller: ['$attrs', '$route', '$scope', function ($attrs, $route, $scope) {
var navItems = [],
routeDef,
... | var module = angular.module('ldsNavigation', ['ngRoute']);
module.directive('ldsNavigation', [function () {
return {
restrict: "E",
scope: true,
controller: ['$attrs', '$route', '$scope', 'lidsysFootballSchedule', function ($attrs, $route, $scope, footballSchedule) {
var navIte... |
Change the DT call, now the coding is working | import RPi.GPIO as GPIO
import time
class WeightSensor:
""" Class that get the weight from a HX711
this module is based on the HX711 datasheet
"""
def __init__(self, SCK, DT):
self.SCK = SCK
self.DT = DT
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.SCK, GPIO.OUT) # SCK comm... | import RPi.GPIO as GPIO
import time
class WeightSensor:
""" Class that get the weight from a HX711
this module is based on the HX711 datasheet
Not test yet
"""
def __init__(self, SCK, DT):
self.SCK = SCK
self.DT = DT
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.SCK, GPI... |
Convert a module's call to BEST.helpers.timeline -> BEST.helpers.piecewise | BEST.module('arkady.pevzner:timeline-example', {
behaviors: {
'#ui-el' : {
size: [100, 100],
style: function(myStyle) {
return myStyle;
},
position: function(myTimeline, time) {
return BEST.helpers.piecewise(myTimeline)(time);
... | BEST.module('arkady.pevzner:timeline-example', {
behaviors: {
'#ui-el' : {
size: [100, 100],
style: function(myStyle) {
return myStyle;
},
position: function(myTimeline, time) {
return BEST.helpers.timeline(myTimeline)(time);
... |
Update last login time on newcomer auth | <?php
namespace App\Http\Controllers\All;
use App\Http\Controllers\Controller;
use App\Models\User;
use EtuUTT;
use Request;
use Config;
use View;
use Crypt;
use Redirect;
use Auth;
use Response;
class AuthController extends Controller
{
/**
* Show the authentication for newcomer page
*
* @return ... | <?php
namespace App\Http\Controllers\All;
use App\Http\Controllers\Controller;
use App\Models\User;
use EtuUTT;
use Request;
use Config;
use View;
use Crypt;
use Redirect;
use Auth;
use Response;
class AuthController extends Controller
{
/**
* Show the authentication for newcomer page
*
* @return ... |
Update adapter to catch exception from loader | from collections import defaultdict
from django.template.base import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(B... | from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEn... |
Rename FK in migration 70 - For some reason, Gunks' db has it named differently than ours. | """Fix Folder, EASFolderSyncStatus unique constraints
Revision ID: 2525c5245cc2
Revises: 479b3b84a73e
Create Date: 2014-07-28 18:57:24.476123
"""
# revision identifiers, used by Alembic.
revision = '2525c5245cc2'
down_revision = '479b3b84a73e'
from alembic import op
import sqlalchemy as sa
from inbox.ignition impo... | """Fix Folder, EASFolderSyncStatus unique constraints
Revision ID: 2525c5245cc2
Revises: 479b3b84a73e
Create Date: 2014-07-28 18:57:24.476123
"""
# revision identifiers, used by Alembic.
revision = '2525c5245cc2'
down_revision = '479b3b84a73e'
from alembic import op
import sqlalchemy as sa
from inbox.ignition impo... |
Copy README.md to dist folder | var path = require("path");
var webpack = require("webpack");
var libraryName = 'lc-form-validation';
var CopyWebpackPlugin = require('copy-webpack-plugin');
var basePath = __dirname;
var env = process.env.NODE_ENV;
var production = 'production';
var config = {
context: path.join(basePath, "src"),
resolve: {
... | var path = require("path");
var webpack = require("webpack");
var libraryName = 'lc-form-validation';
var CopyWebpackPlugin = require('copy-webpack-plugin');
var basePath = __dirname;
var env = process.env.NODE_ENV;
var production = 'production';
var config = {
context: path.join(basePath, "src"),
resolve: {
... |
Add basic unit tests for BMAttackSurrender | <?php
class BMAttackSurrenderTest extends PHPUnit_Framework_TestCase {
/**
* @var BMAttackSurrender
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
... | <?php
class BMAttackSurrenderTest extends PHPUnit_Framework_TestCase {
/**
* @var BMAttackSurrender
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
... |
Add images to snapshot details | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snaps... | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqpar... |
Fix another simplejson deprecation warning | import json
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from djangocms_table.utils import static_url
from django.http import... | from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from models import Table
from djangocms_table.forms import TableForm
from django.utils import simplejson
from djangocms_table.utils import static_url... |
Fix tests for PHP 5.3 | <?php
/**
* PHP Version 5.3
*
* @copyright (c) 2006-2015 brian ridley
* @author brian ridley <ptlis@ptlis.net>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespa... | <?php
/**
* PHP Version 5.3
*
* @copyright (c) 2006-2015 brian ridley
* @author brian ridley <ptlis@ptlis.net>
* @license http://opensource.org/licenses/MIT MIT
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespa... |
fix: Solve the default random avatar path problem | const path = require('path');
const options = require('../utils/commandOptions');
module.exports = {
commonn: {
convertPxToRem: {
enable: false,
options: {
rootValue: 108, // 设计稿为3倍图
propList: ['*', '!border'],
unitPrecision: 4,
... | const path = require('path');
const options = require('../utils/commandOptions');
module.exports = {
commonn: {
convertPxToRem: {
enable: false,
options: {
rootValue: 108, // 设计稿为3倍图
propList: ['*', '!border'],
unitPrecision: 4,
... |
Make the script check all the site package directories | import os
import site
# Check to see if the previous version was installed and clean up
# installed-files.txt
prune = ['var/', 'var/run/', 'var/log/']
package_directories = site.PREFIXES
if site.USER_SITE:
package_directories.append(site.USER_SITE)
for package_dir in package_directories:
print 'Checking %s ... | import os
from distutils import sysconfig
# Check to see if the previous version was installed and clean up
# installed-files.txt
prune = ['var/', 'var/run/', 'var/log/']
python_lib_dir = sysconfig.get_python_lib()
fixed = False
for dir_path, dir_names, file_names in os.walk(python_lib_dir):
for dir_name in dir_na... |
Add changes forgotten in the last commit :-( | package de.ddb.pdc.storage;
import de.ddb.pdc.core.AnsweredQuestion;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.springframework.data.annotation.Id;
/**
* Entity representing the PDC record structure in storage.
*/
public class S... | package de.ddb.pdc.storage;
import de.ddb.pdc.core.AnsweredQuestion;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.springframework.data.annotation.Id;
/**
* Entity representing the PDC record structure in storage.
*/
public class S... |
Remove media screen to fix styles when printing. | <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/boots... | <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/boots... |
Set execution timeout to be lower
Otherwise the test would be much slower | from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)... | from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)... |
Reduce poll time to 10ms. | package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A queue of incoming {@link ResponseMessage} objects. The queue is updated by the
* {@link Handler.GremlinResponseDecoder} ... | package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A queue of incoming {@link ResponseMessage} objects. The queue is updated by the
* {@link Handler.GremlinResponseDecoder} ... |
Fix a test to work on php 7.1 | <?php
namespace Rybakit\Bundle\NavigationBundle\Tests\Twig;
use PHPUnit\Framework\TestCase;
use Rybakit\Bundle\NavigationBundle\Tests\Fixtures\Item;
use Rybakit\Bundle\NavigationBundle\Twig\NavigationExtension;
class NavigationExtensionTest extends TestCase
{
/**
* @dataProvider provideGetAncestorData
... | <?php
namespace Rybakit\Bundle\NavigationBundle\Tests\Twig;
use PHPUnit\Framework\TestCase;
use Rybakit\Bundle\NavigationBundle\Tests\Fixtures\Item;
use Rybakit\Bundle\NavigationBundle\Twig\NavigationExtension;
class NavigationExtensionTest extends TestCase
{
/**
* @dataProvider provideGetAncestorData
... |
Update find owner to work with promises. | """
Command that will allow for a user to inject triples into a database.
"""
from rhobot.components.commands.base_command import BaseCommand
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
from rhobot.components.storage import StoragePayload
import logging
logger = logging.getLogger(__name__)
clas... | """
Command that will allow for a user to inject triples into a database.
"""
from rhobot.components.commands.base_command import BaseCommand
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__name__)
class FindOwner(BaseCommand):
def initialize_command... |
Use bytes instead of str where appropriate for Python 3 | class Console(object):
def __init__(self, shell, stdout):
self._shell = shell
self._stdout = stdout
def run(self, description, command, **kwargs):
return self.run_all(description, [command], **kwargs)
def run_all(self, description, commands, quiet=False, cwd=None):
... | class Console(object):
def __init__(self, shell, stdout):
self._shell = shell
self._stdout = stdout
def run(self, description, command, **kwargs):
return self.run_all(description, [command], **kwargs)
def run_all(self, description, commands, quiet=False, cwd=None):
... |
Reduce visibility of firebase analytics constructor | package com.alexstyl.specialdates.analytics;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.novoda.notils.logger.simple.Log;
import java.util.Locale;
public class Firebase implements Analytics {
private static final Bundle NO_DATA = ... | package com.alexstyl.specialdates.analytics;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.novoda.notils.logger.simple.Log;
import java.util.Locale;
public class Firebase implements Analytics {
private static final Bundle NO_DATA = ... |
Convert all os.system() to subprocess.check_output(). | '''
@date 2015-02-21
@author Hong-She Liang <starofrainnight@gmail.com>
'''
import os
import re
import subprocess
from .mouse_constant import *
class Mouse(object):
## return current mouse absolute position
@classmethod
def position(cls):
output = subprocess.check_output(["xdotool", "getmouselocat... | '''
@date 2015-02-21
@author Hong-She Liang <starofrainnight@gmail.com>
'''
import os
import re
import subprocess
from .mouse_constant import *
class Mouse(object):
## return current mouse absolute position
@classmethod
def position(cls):
p = subprocess.Popen(["xdotool", "getmouselocation"], stdou... |
Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404. | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSe... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSe... |
Test the new enforce method | <?php
namespace PhpAbac\Test;
use PhpAbac\Abac;
class AbacTest extends AbacTestCase {
/** @var Abac **/
protected $abac;
public function setUp() {
$this->abac = new Abac(new \PDO(
'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' .
'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'... | <?php
namespace PhpAbac\Test;
use PhpAbac\Abac;
class AbacTest extends AbacTestCase {
/** @var Abac **/
protected $abac;
public function setUp() {
$this->abac = new Abac(new \PDO(
'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' .
'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'... |
Fix required_fields looking at wrong jsonify file. | import flask
from flask import request
import functools
from . import jsonify
def required_fields(fields, forbid_whitespace=False):
'''
Declare that the endpoint requires certain POST body fields. Without them,
we respond with 400 and a message.
forbid_whitespace:
If True, then providing the... | import flask
from flask import request
import functools
from etiquette import jsonify
def required_fields(fields, forbid_whitespace=False):
'''
Declare that the endpoint requires certain POST body fields. Without them,
we respond with 400 and a message.
forbid_whitespace:
If True, then provi... |
Use Grunt API to write file
This way it guarantees that all the intermediate directories are created. | var doxdox = require('doxdox'),
utils = require('doxdox/lib/utils'),
fs = require('fs'),
path = require('path'),
extend = require('extend');
module.exports = function (grunt) {
grunt.registerMultiTask('doxdox', 'Generate documentation with doxdox.', function () {
var done = this.async(),
... | var doxdox = require('doxdox'),
utils = require('doxdox/lib/utils'),
fs = require('fs'),
path = require('path'),
extend = require('extend');
module.exports = function (grunt) {
grunt.registerMultiTask('doxdox', 'Generate documentation with doxdox.', function () {
var done = this.async(),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.