text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Switch rear DT to move in opposite direction of front DT | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mechanism;
import actuator.IMotor;
import core.GRTLoggedProcess;
/**
* Standard 4 motor drivetrain.
* @author ajc
*/
public class GRTDriveTrain extends GRTLoggedProcess {
private final IMotor leftFront;... | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mechanism;
import actuator.IMotor;
import core.GRTLoggedProcess;
/**
* Standard 4 motor drivetrain.
* @author ajc
*/
public class GRTDriveTrain extends GRTLoggedProcess {
private final IMotor leftFront;... |
Fix test of assets twig extension | <?php
namespace Tests\Becklyn\AssetsBundle\Twig;
use Becklyn\AssetsBundle\Dependency\DependencyMap;
use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\File\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;
cl... | <?php
namespace Tests\Becklyn\AssetsBundle\Twig;
use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\File\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;
class AssetsTwigExtensionTest extends TestCase
{
... |
Validate even when we don't detect a mapper | <?php
namespace NS\ImportBundle\Validators;
use NS\ImportBundle\Converter\ColumnChooser;
use NS\ImportBundle\Entity\Column;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ImportMapColumnValidator extends ConstraintValidator
{
/** @var ColumnChooser */
p... | <?php
namespace NS\ImportBundle\Validators;
use NS\ImportBundle\Converter\ColumnChooser;
use NS\ImportBundle\Entity\Column;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ImportMapColumnValidator extends ConstraintValidator
{
/** @var ColumnChooser */
p... |
Fix for msg "Api validation failed" on first time save | <?php
namespace Dotdigitalgroup\Email\Model\Apiconnector;
class Test
{
/**
* @var \Dotdigitalgroup\Email\Helper\Data
*/
public $helper;
/**
* @var \Magento\Framework\App\Config\ReinitableConfigInterface
*/
public $config;
/**
* Test constructor.
*
* @param \Dotd... | <?php
namespace Dotdigitalgroup\Email\Model\Apiconnector;
class Test
{
/**
* @var \Dotdigitalgroup\Email\Helper\Data
*/
public $helper;
/**
* Test constructor.
*
* @param \Dotdigitalgroup\Email\Helper\Data $data
*/
public function __construct(
\Dotdigitalgroup\Em... |
Add some basic error handling in case the executables don't exist | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super... | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super... |
Test that log messages go to stderr. | import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = self.parseargs(["foo"])
... | import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = self.parseargs(["foo"])
... |
Implement suggested changes in PR review | """
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'privat... | """
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'privat... |
Update to AJAX functions in click controller. | 'use strict';
(function () {
var addButton = document.querySelector('.btn-add');
var deleteButton = document.querySelector('.btn-delete');
var clickNbr = document.querySelector('#click-nbr');
var apiUrl = 'http://localhost:3000/api/clicks';
function ready (fn) {
if (typeof fn !== 'function') {
... | 'use strict';
(function () {
var addButton = document.querySelector('.btn-add');
var deleteButton = document.querySelector('.btn-delete');
var clickNbr = document.querySelector('#click-nbr');
var apiUrl = 'http://localhost:3000/api/clicks';
function ready (fn) {
if (typeof fn !== 'function') {
... |
Use array index instead of .index | import React, { Component, PropTypes } from 'react'
import Tile from './Tile'
const styles = {
row: {
position: 'relative',
flexDirection: 'row'
}
}
export default class Board extends Component {
static propTypes = {
tiles: PropTypes.array.isRequired,
playTile: PropTypes.f... | import React, { Component, PropTypes } from 'react'
import Tile from './Tile'
import { sortBy } from 'lodash'
const styles = {
row: {
position: 'relative',
flexDirection: 'row'
}
}
export default class Board extends Component {
static propTypes = {
tiles: PropTypes.array.isRequire... |
Implement hashCode() when you implement equals()! | package nodomain.freeyourgadget.gadgetbridge.model;
/**
* Created by steffen on 07.06.16.
*/
public class MusicStateSpec {
public static final int STATE_PLAYING = 0;
public static final int STATE_PAUSED = 1;
public static final int STATE_STOPPED = 2;
public static final int STATE_UNKNOWN = 3;
p... | package nodomain.freeyourgadget.gadgetbridge.model;
/**
* Created by steffen on 07.06.16.
*/
public class MusicStateSpec {
public static final int STATE_PLAYING = 0;
public static final int STATE_PAUSED = 1;
public static final int STATE_STOPPED = 2;
public static final int STATE_UNKNOWN = 3;
p... |
Rename /user route to /min-side | var passport = require('passport');
var auth0 = require('../lib/services/auth0');
module.exports = {
type: 'authentication',
module: auth0,
initialize: (app) => {
passport.use(auth0.strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(fun... | var passport = require('passport');
var auth0 = require('../lib/services/auth0');
module.exports = {
type: 'authentication',
module: auth0,
initialize: (app) => {
passport.use(auth0.strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(fun... |
Remove line numbers from recipe code
The larger font made the numbers not match the code.
Added better link text to download the recipe. | """
Generate the rst files for the cookbook from the recipes.
"""
import sys
import os
body = r"""
**Download** source code: :download:`{recipe}<{code}>`
.. literalinclude:: {code}
:language: python
"""
def recipe_to_rst(recipe):
"""
Convert a .py recipe to a .rst entry for sphinx
"""
sys.stderr... | """
Generate the rst files for the cookbook from the recipes.
"""
import sys
import os
body = r"""
.. raw:: html
[<a href="{code}">source code</a>]
.. literalinclude:: {code}
:language: python
:linenos:
"""
def recipe_to_rst(recipe):
"""
Convert a .py recipe to a .rst entry for sphinx
"""
... |
Fix Stream instance of Guzzle | <?php
namespace Gerencianet\Exception;
use Exception;
class GerencianetException extends Exception
{
private $error;
private $errorDescription;
public function __construct($exception)
{
$error = $exception;
if ($exception instanceof \GuzzleHttp\Stream\Stream) {
$error =... | <?php
namespace Gerencianet\Exception;
use Exception;
class GerencianetException extends Exception
{
private $error;
private $errorDescription;
public function __construct($exception)
{
$error = $exception;
if ($exception instanceof \GuzzleHttp\Psr7\Stream) {
$error = $... |
Rename content field to field_value. | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... |
Remove unneeded variable from test. | from textwrap import dedent
from twisted.python.filepath import FilePath
from twisted.trial.unittest import SynchronousTestCase
from flocker import __version__ as version
from flocker.common.version import get_installable_version
from flocker.testtools import run_process
class VersionExtensionsTest(SynchronousTestC... | from textwrap import dedent
from twisted.python.filepath import FilePath
from twisted.trial.unittest import SynchronousTestCase
from flocker import __version__ as version
from flocker.common.version import get_installable_version
from flocker.testtools import run_process
class VersionExtensionsTest(SynchronousTestC... |
Use BrokerAwareExtension instead of deprecated BrokerAwareClassReflectionExtension | <?php
declare(strict_types=1);
namespace SaschaEgerer\PhpstanTypo3\Reflection;
use PHPStan\Broker\Broker;
use PHPStan\Reflection\BrokerAwareExtension;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\MethodsClassReflectionExtension;
class RepositoryMethodsClassR... | <?php
declare(strict_types=1);
namespace SaschaEgerer\PhpstanTypo3\Reflection;
use PHPStan\Broker\Broker;
use PHPStan\Reflection\BrokerAwareClassReflectionExtension;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
class RepositoryMethodsClassReflectionExtension implements \PHPStan\Re... |
Add TODO on how to make a better libspotify lookup | import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class Libspoti... | import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class Libspoti... |
Replace "pass" with "self.fail()" in tests
In this way, tests that haven't been written will run noisily instead of
silently, encouraging completion of writing tests. | # -*- coding: utf-8 -*-
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""... | # -*- coding: utf-8 -*-
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""... |
Switch to update_or_create - Django 1.7+
Can't use this on older versions of Django | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=... | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=... |
Remove default name and text of the control class | <?php
/**
* @author Manuel Thalmann <m@nuth.ch>
* @license Apache-2.0
*/
namespace System\Web\Forms;
use System\Object;
use System\Web\Forms\Rendering\IRenderable;
{
abstract class Control extends Object implements IRenderable
{
/**
* Initializ... | <?php
/**
* @author Manuel Thalmann <m@nuth.ch>
* @license Apache-2.0
*/
namespace System\Web\Forms;
use System\Object;
use System\Web\Forms\Rendering\IRenderable;
{
abstract class Control extends Object implements IRenderable
{
/**
* Initializ... |
Add .0 to version number. | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) 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-imgix',
versi... | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) 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-imgix',
versi... |
FIX only post message if a partner is existent | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Steve Ferry
#
# The licence is in the file __manifest__.py
#
###############... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Steve Ferry
#
# The licence is in the file __manifest__.py
#
###############... |
Set mocha test timeout for entire test, extended timeout to 30 seconds. | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('Ionic Framework Generator', function () {
this.timeout(30000);
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
... | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('Ionic Framework Generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
... |
Allow subclasses to customise the worker class | from django.core.management import BaseCommand, CommandError
from channels import DEFAULT_CHANNEL_LAYER
from channels.layers import get_channel_layer
from channels.log import setup_logger
from channels.routing import get_default_application
from channels.worker import Worker
class Command(BaseCommand):
leave_lo... | from django.core.management import BaseCommand, CommandError
from channels import DEFAULT_CHANNEL_LAYER
from channels.layers import get_channel_layer
from channels.log import setup_logger
from channels.routing import get_default_application
from channels.worker import Worker
class Command(BaseCommand):
leave_lo... |
createNotificationsMiddleware: Put an arg default back | import { fetch } from 'domain/Api';
import ApiCall from 'containers/ApiCalls';
/*
* Supports currying so that args can be recycled more conveniently.
* A contrived example:
* ```
* const createCreatorForX =
* createApiActionCreator('X_REQUEST', 'X_SUCCESS', 'X_FAILURE', 'http://...');
* const getXActionCreato... | import { fetch } from 'domain/Api';
import ApiCall from 'containers/ApiCalls';
/*
* Supports currying so that args can be recycled more conveniently.
* A contrived example:
* ```
* const createCreatorForX =
* createApiActionCreator('X_REQUEST', 'X_SUCCESS', 'X_FAILURE', 'http://...');
* const getXActionCreato... |
Use the new Deck class | #Cards Against Humanity game engine
from cards import Deck, NoMoreCards
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
... | #Cards Against Humanity game engine
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
#list of active pl... |
Sort versions in version list by 'version' descending | <?php
$page = new \Site\Page();
$page->requireRole('package manager');
// @TODO for PHP7 warnings, fix object inheritance Package\Version::get, Storage\File::get
error_reporting(E_ERROR | E_PARSE);
if (isset($_REQUEST['code'])) {
$package = new \Package\Package();
if (! $pa... | <?php
$page = new \Site\Page();
$page->requireRole('package manager');
// @TODO for PHP7 warnings, fix object inheritance Package\Version::get, Storage\File::get
error_reporting(E_ERROR | E_PARSE);
if (isset($_REQUEST['code'])) {
$package = new \Package\Package();
if (! $pa... |
Use isNaN() to check for NaN. Comparison op '!==='
doesn't work.
Also add a method 'selected' to factor out
retrieval of selected value | (function () {
var mr = sparks.activities.mr;
var str = sparks.string;
mr.ActivityDomHelper = {
ratedResistanceFormId: '#rated_resistance',
ratedResistanceValueId: '#rated_resistance_value_input',
ratedResistanceUnitId: '#rated_resitance_unit_select',
getA... | (function () {
var mr = sparks.activities.mr;
var str = sparks.string;
mr.ActivityDomHelper = {
ratedResistanceFormId: '#rated_resistance',
ratedResistanceValueId: '#rated_resistance_value_input',
ratedResistanceUnitId: '#rated_resitance_unit_select',
getA... |
Add e.preventDefault to comments form. | app.Comments = React.createClass({
//get all loaded comments
getInitialState: function () {
return {
displaying: false,
comments: app.CommentStore.getAll(this.props.idea_id)
};
},
//when we mount the view setup event listener for store changes
componentDidMount: function () {
app.Comm... | app.Comments = React.createClass({
//get all loaded comments
getInitialState: function () {
return {
displaying: false,
comments: app.CommentStore.getAll(this.props.idea_id)
};
},
//when we mount the view setup event listener for store changes
componentDidMount: function () {
app.Comm... |
Make version format PEP 440 compatible | import re
import sys
from collections import namedtuple
from .connection import connect, Connection, TIMEOUT as DEFAULT_TIMEOUT
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info', 'DEFAULT_TIMEOUT')
... | import re
import sys
from collections import namedtuple
from .connection import connect, Connection, TIMEOUT as DEFAULT_TIMEOUT
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info', 'DEFAULT_TIMEOUT')
... |
Use Google Closure style of marking function parameters as optional. | 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array=} args ... | 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array} [args] ... |
Remove old todo already done | Ext.namespace('ui','ui.component');
// ViewVCDiff
// config - {prefix, fid, fpath, fname, rev1, rev2}
ui.component.ViewVCDiff = Ext.extend(Ext.Panel,
{
layout : 'fit',
title : _('Diff From VCS'),
iconCls : 'iconDiffView',
collapsedIconCls : 'iconDiffView',
plugins : [Ext.ux.PanelCollaps... | Ext.namespace('ui','ui.component');
// TODO: Extract the URI specific at php's project into the config file to allow use of others projects
// ViewVCDiff
// config - {prefix, fid, fpath, fname, rev1, rev2}
ui.component.ViewVCDiff = Ext.extend(Ext.Panel,
{
layout : 'fit',
title : _('Diff From VCS'),
... |
Fix display issue with versions in worker stats | import React from 'react';
import moment from 'moment';
import Actions from '../actions';
import WorkerStatsStore from '../stores/worker-stats-store';
export default class WorkerPage extends React.Component {
constructor() {
super();
this.state = WorkerStatsStore.getState();
this.fetchTimeout = null;
... | import React from 'react';
import moment from 'moment';
import Actions from '../actions';
import WorkerStatsStore from '../stores/worker-stats-store';
export default class WorkerPage extends React.Component {
constructor() {
super();
this.state = WorkerStatsStore.getState();
this.fetchTimeout = null;
... |
Update to use new schema | <?php
namespace Rogue\Http\Transformers;
use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;
class PhoenixGalleryTransformer extends TransformerAbstract
{
/**
* Transform resource data.
*
* @param \Rogue\Models\Photo $photo
* @return array
*/
public function transform(Post... | <?php
namespace Rogue\Http\Transformers;
use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;
class PhoenixGalleryTransformer extends TransformerAbstract
{
/**
* Transform resource data.
*
* @param \Rogue\Models\Photo $photo
* @return array
*/
public function transform(Post... |
Move imports in alphabet order | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
class Sheldon:
"""
Main ... | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.config import *
from sheldon.adapter import *
from sheldon.storage import *
class Sheldon:
"""
Main ... |
Fix the recursion bug in KnowledgeBase after the previous refactor. | """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = pr... | """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = pr... |
Fix test valid even though it was not | var program = require('commander'),
apiController = require('./apis/apiController')
colors = require('colors'),
ran = false;
var testCb = function(result, apiCall) {
console.log('Test results for ' + apiCall.bold);
if(result !== true) {
for(var i = 0; i < result.length; i++) {
var info = resu... | var program = require('commander'),
apiController = require('./apis/apiController')
colors = require('colors'),
ran = false;
var testCb = function(result, apiCall) {
console.log('Test results for ' + apiCall.bold);
if(result === true) {
process.exit(0);
} else {
for(var i = 0; i < result.leng... |
Include more exception data on exchange rate failure | import decimal
import logging
import sys
import threading
import requests
logger = logging.getLogger('btc.priceticker.exchangerate')
class ExchangeRate(threading.Thread):
YAHOO_FINANCE_URL = "https://download.finance.yahoo.com/d/quotes.csv"
YAHOO_FINANCE_PARAMS = {'e': '.csv', 'f': 'sl1d1t1', 's': 'USDNOK=X'... | import decimal
import logging
import threading
import requests
logger = logging.getLogger('btc.priceticker.exchangerate')
class ExchangeRate(threading.Thread):
YAHOO_FINANCE_URL = "https://download.finance.yahoo.com/d/quotes.csv"
YAHOO_FINANCE_PARAMS = {'e': '.csv', 'f': 'sl1d1t1', 's': 'USDNOK=X'}
SLEEP... |
Check that params can be null | package com.github.arteam.simplejsonrpc.core.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import org.jetbrains.annotations.NotNull;
import org.jetb... | package com.github.arteam.simplejsonrpc.core.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import org.jetbrains.annotations.NotNull;
import org.jetb... |
Add comment to explain query/insert in migration | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$... |
Remove useless SelectorFunction for ISO | package io.fotoapparat.parameter.selector;
import io.fotoapparat.parameter.range.Range;
/**
* Selector functions for sensor sensitivity (ISO).
*/
public class SensorSensitivitySelectors {
/**
* @param iso the specified ISO value
* @return {@link SelectorFunction} which selects the specified ISO value... | package io.fotoapparat.parameter.selector;
import io.fotoapparat.parameter.range.Range;
/**
* Selector functions for sensor sensitivity (ISO).
*/
public class SensorSensitivitySelectors {
/**
* @param iso the specified ISO value
* @return {@link SelectorFunction} which selects the specified ISO value... |
Change selenium browser to firefox. | """
Module to hold basic home Selenium tests.
"""
from selenium import selenium
import unittest, time, re, os, sys, subprocess
def rel_to_abs(path):
"""
Function to take relative path and make absolute
"""
current_dir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(current_dir, pat... | """
Module to hold basic home Selenium tests.
"""
from selenium import selenium
import unittest, time, re, os, sys, subprocess
def rel_to_abs(path):
"""
Function to take relative path and make absolute
"""
current_dir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(current_dir, pat... |
Reduce results per page to 30 | import os
from dmutils.status import get_version_label
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
VERSION = get_version_label(
os.path.abspath(os.path.dirname(__file__))
)
AUTH_REQUIRED = True
ELASTICSEARCH_HOST = 'localhost:9200'
DM_SEARCH_API_AUTH_TOKENS = Non... | import os
from dmutils.status import get_version_label
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
VERSION = get_version_label(
os.path.abspath(os.path.dirname(__file__))
)
AUTH_REQUIRED = True
ELASTICSEARCH_HOST = 'localhost:9200'
DM_SEARCH_API_AUTH_TOKENS = Non... |
UPDATE: Throw exception if we are going to divide by 0 | <?php
/**
* This file is part of the Statistical Classifier package.
*
* (c) Cam Spiers <camspiers@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Camspiers\StatisticalClassifier\Transform;
/**
* @author C... | <?php
/**
* This file is part of the Statistical Classifier package.
*
* (c) Cam Spiers <camspiers@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Camspiers\StatisticalClassifier\Transform;
/**
* @author C... |
Remove useless TODO from codebase. | """
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The... | """
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The... |
Reposition tooltips when window is resized | define(
["jquery"],
function($) {
function Tutorial(steps, content) {
var _this = this;
var currentIdx;
function show(idx) {
var step = steps[idx];
if (step.init) step.init.apply(_this);
step.$content = $('[data-step="' + step.name + '"]', content);
step.$conte... | define(
["jquery"],
function($) {
function Tutorial(steps, content) {
var _this = this;
var currentIdx;
function show(idx) {
var step = steps[idx];
if (step.init) step.init.apply(_this);
step.$content = $('[data-step="' + step.name + '"]', content);
step.$conte... |
feat: Add method that updates all focusable elements when called | import Ember from 'ember';
import $ from 'jquery';
export default Ember.Mixin.create({
focusableElementQuery: 'select:not([disabled]), button:not([disabled]), [tabindex="0"], input:not([disabled]), a[href]',
lockBackground (obj) {
const element = document.getElementById(obj.elementId);
this.set('trapElemen... | import Ember from 'ember';
import $ from 'jquery';
export default Ember.Mixin.create({
lockBackground (obj) {
const focusableElementQuery = 'select:not([disabled]), button:not([disabled]), [tabindex="0"], input:not([disabled]), a[href]';
const element = document.getElementById(obj.elementId);
const backg... |
Add user to db.session only when it has been created | from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda *... | from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda *... |
Remove unnecessary dependency from unit test | package com.mdaniline.spring.autoproperties;
import com.mdaniline.spring.autoproperties.testclasses.TestBasicProperties;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
... | package com.mdaniline.spring.autoproperties;
import com.mdaniline.spring.autoproperties.testclasses.TestBasicProperties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.Defa... |
Fix for typing mistake of requireds which should be required in create user form | @extends(Config::get('cpanel::views.layout'))
@section('header')
<h3>
<i class="icon-user"></i>
Users
</h3>
@stop
@section('help')
<p class="lead">Users</p>
<p>
From here you can create, edit or delete users. Also you can assign custom permissions to a single user.
</p>
@sto... | @extends(Config::get('cpanel::views.layout'))
@section('header')
<h3>
<i class="icon-user"></i>
Users
</h3>
@stop
@section('help')
<p class="lead">Users</p>
<p>
From here you can create, edit or delete users. Also you can assign custom permissions to a single user.
</p>
@sto... |
Set no of records per page to 500 in search current actions call. | <?php
namespace LaravelLb;
use LaravelLb\LogicBoxes;
class LogicBoxesActions extends LogicBoxes {
public function __construct()
{
parent::__construct();
$this->resource = "actions";
}
/**
* Gets the Current Actions based on the criteria specified.
* http://manage.logicbox... | <?php
namespace LaravelLb;
use LaravelLb\LogicBoxes;
class LogicBoxesActions extends LogicBoxes {
public function __construct()
{
parent::__construct();
$this->resource = "actions";
}
/**
* Gets the Current Actions based on the criteria specified.
* http://manage.logicbox... |
Throw an error, not just a plain string | "use strict";
import Guard from './Guard';
class EventContext {
constructor(modelId, eventType, event) {
Guard.isString(modelId, "The modelId should be a string");
Guard.isString(eventType, "The eventType should be a string");
Guard.isDefined(event, "The event should be defined");
... | "use strict";
import Guard from './Guard';
class EventContext {
constructor(modelId, eventType, event) {
Guard.isString(modelId, "The modelId should be a string");
Guard.isString(eventType, "The eventType should be a string");
Guard.isDefined(event, "The event should be defined");
... |
Fix stress test which was not changed to receive one client value
Change-Id: I186f2827c91d8b1eabd0769dda4765a973bf42b4
Closes-Bug: 1413980 | # 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
# di... | # 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
# di... |
Fix for "java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority array" | /**
*
*/
package org.jenkinsci.plugins;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.kohsuke.github.GHUser;
import javax.annotation.Nonnull;
import java.io... | /**
*
*/
package org.jenkinsci.plugins;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.kohsuke.github.GHUser;
import javax.annotation.Nonnull;
import java.io... |
Use normal Resource as default for ResourceList
to avoid potential circular import. | from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
... | from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
... |
Handle the case where the user may already exist in the database | """
A management command to create a user with a given email.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from ixprofile_client.webservice import UserWebService
from optparse import make_option
class Command(Bas... | """
A management command to create a user with a given email.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from ixprofile_client.webservice import UserWebService
from optparse import make_option
class Command(BaseCommand):
"""
The command... |
Remove calculation finishing the test | <?php
namespace AppBundle\Tests\Entity;
use AppBundle\Entity\Calculation;
use AppBundle\Model\CalculationFactory;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SimpleRasterTest extends WebTestCase
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $entityManager;
/**
* @va... | <?php
namespace AppBundle\Tests\Entity;
use AppBundle\Entity\Calculation;
use AppBundle\Model\CalculationFactory;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SimpleRasterTest extends WebTestCase
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $entityManager;
/**
* @va... |
Remove some weird space in the test configuration. | <?php
use Arvici\Heart\Config\Configuration;
use Arvici\Component\View\View;
/**
* Template Configuration
*/
Configuration::define('database', function() {
return [
/**
* The default fetch type to use.
*/
'fetchType' => \Arvici\Heart\Database\Database::FETCH_ASSOC,
/*... | <?php
use Arvici\Heart\Config\Configuration;
use Arvici\Component\View\View;
/**
* Template Configuration
*/
Configuration::define('database', function() {
return [
/**
* The default fetch type to use.
*/
'fetchType' => \Arvici\Heart\Database\Database::FETCH_ASSOC,
/*... |
application: Add warning about db connection issues to the fork class | <?php
/**
* Process forking implementation
* @author M2Mobi, Heinz Wiesinger
*/
class Fork
{
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* Start multiple parallel child processes
... | <?php
/**
* Process forking implementation
* @author M2Mobi, Heinz Wiesinger
*/
class Fork
{
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* Start multiple parallel child processes
... |
Disable asyncpg prepared statement cache | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
... | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
... |
Enable toolbar buttons only within certain tags | define('scribe-plugin-image-inserter', [
'eventsWithPromises',
'rangy-core',
'rangy-selectionsaverestore',
'filter-event'
],
function (eventsWithPromises, rangy, rangySelectionSaveRestore, filterEvent) {
'use strict';
/**
* This plugin adds a command for editing/creating links via LinkEditor/LinkInserte... | define('scribe-plugin-image-inserter', [
'eventsWithPromises',
'rangy-core',
'rangy-selectionsaverestore',
'filter-event'
],
function (eventsWithPromises, rangy, rangySelectionSaveRestore, filterEvent) {
'use strict';
/**
* This plugin adds a command for editing/creating links via LinkEditor/LinkInserte... |
Add list of channels to group index | @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">All Groups</div>
<div class="panel-body">
... | @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">All Groups</div>
<div class="panel-body">
... |
Set the githubIssue field to the actual GitHub URL fo the issue instead of the issue number. | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... |
Add phonelog to postgres models copied by copy_domain | from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
from phonelog.models import DeviceReportEntry
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated with a list... | from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated with a list of doc-ids from a remote postgres
databas... |
Allow clients to provide their own function to decide whether form is valid before submission | $.fn.informantSubscribeForm = function (options) {
var settings = $.extend({
renderResults: false,
resultContainer: null,
validate: function (form, evt) { return true; }
}, options);
this.each(function () {
var self = $(this);
function renderResults(html... | $.fn.informantSubscribeForm = function (options) {
var settings = $.extend({
renderResults: false,
resultContainer: null
}, options);
this.each(function () {
var self = $(this);
function renderResults(htmlContent) {
if (settings.renderResults) {
... |
Remove redundant 'ckernel' overload match | """
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#----------------------... | """
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#----------------------... |
Put the type unwrapping into a separat method | from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('a... | from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('a... |
Add a simple UnicodeCSVWriter, probably flawed. | # -*- coding: utf-8 -*-
import csv
import itertools
def grouper(iterable, n):
"""
Slice up `iterable` into iterables of `n` items.
:param iterable: Iterable to splice.
:param n: Number of items per slice.
:returns: iterable of iterables
"""
it = iter(iterable)
while True:
chun... | # -*- coding: utf-8 -*-
import csv
import itertools
def grouper(iterable, n):
"""
Slice up `iterable` into iterables of `n` items.
:param iterable: Iterable to splice.
:param n: Number of items per slice.
:returns: iterable of iterables
"""
it = iter(iterable)
while True:
chun... |
Fix JSON serialisation problem with AJAX basket
six.moves.map returns itertools.imap which won't serialize to JSON.
This commit unpacks the list into a normal list of strings to circumvent
the issue. | import six
from django.contrib import messages
from six.moves import map
class FlashMessages(object):
"""
Intermediate container for flash messages.
This is useful as, at the time of creating the message, we don't know
whether the response is an AJAX response or not.
"""
def __init__(self):
... | import six
from django.contrib import messages
from six.moves import map
class FlashMessages(object):
"""
Intermediate container for flash messages.
This is useful as, at the time of creating the message, we don't know
whether the response is an AJAX response or not.
"""
def __init__(self):
... |
Abort when test is not found. | <?php
namespace Criterion\UI\Controller;
class TestController
{
public function view(\Silex\Application $app)
{
$data['test'] = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $data['test'])
{
return $app... | <?php
namespace Criterion\UI\Controller;
class TestController
{
public function view(\Silex\Application $app)
{
$data['test'] = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
$logs = $app['mongo']->logs->find(array(
't... |
Fix E722 error while executing flake8. | from setuptools import setup
f = open("README.rst")
try:
try:
readme_content = f.read()
except Exception:
readme_content = ""
finally:
f.close()
setup(
name='restea',
packages=['restea', 'restea.adapters'],
version='0.3.7',
description='Simple RESTful server toolkit',
l... | from setuptools import setup
f = open("README.rst")
try:
try:
readme_content = f.read()
except:
readme_content = ""
finally:
f.close()
setup(
name='restea',
packages=['restea', 'restea.adapters'],
version='0.3.7',
description='Simple RESTful server toolkit',
long_descri... |
Add Sink class to initial spotify-connect import | from __future__ import unicode_literals
import spotifyconnect
__all__ = [
'Sink'
]
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want... | from __future__ import unicode_literals
import spotifyconnect
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want to
turn the sink... |
Fix non existing Model\AlbumTableGateway::class FQN | <?php
namespace Album;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
ret... | <?php
namespace Album;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/config/module.... |
:bug: Fix by targeting zeros within values only | 'use strict';
var helpers = require('../helpers');
var units = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax',
'px', 'mm', 'cm', 'in', 'pt', 'pc'];
module.exports = {
'name': 'zero-unit',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.... | 'use strict';
var helpers = require('../helpers');
var units = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax',
'px', 'mm', 'cm', 'in', 'pt', 'pc'];
module.exports = {
'name': 'zero-unit',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.... |
Address review: Put translated line on one line. | /**
* This is the first script called by the enrollment geography page. It loads
* the libraries and kicks off the application.
*/
require(['vendor/domReady!', 'load/init-page'], function(doc, page) {
'use strict';
// this is your page specific code
require(['views/data-table-view', 'views/world-map-v... | /**
* This is the first script called by the enrollment geography page. It loads
* the libraries and kicks off the application.
*/
require(['vendor/domReady!', 'load/init-page'], function(doc, page) {
'use strict';
// this is your page specific code
require(['views/data-table-view', 'views/world-map-v... |
Allow setting cell style on isolate override | /**
* Focus on a single presentation.
*/
ds.models.transform.Isolate = function(options) {
'use strict'
var self =
limivorous.observable()
.extend(ds.models.transform.transform, {
display_name: 'Isolate',
transform_name: 'isolate',
transform_type:... | /**
* Focus on a single presentation.
*/
ds.models.transform.Isolate = function(options) {
'use strict'
var self =
limivorous.observable()
.extend(ds.models.transform.transform, {
display_name: 'Isolate',
transform_name: 'isolate',
transform_type:... |
Use the column module and just extend from that. | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
option... | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
option... |
Add support for Android back button | import React, { Component } from 'react';
import { addNavigationHelpers, NavigationActions } from 'react-navigation';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { BackAndroid, View } from 'react-native';
import * as actions from './actions';
import { AppContainerStyles } f... | import React, { Component } from 'react';
import { addNavigationHelpers } from 'react-navigation';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { View } from 'react-native';
import * as actions from './actions';
import { AppContainerStyles } from './styles/containers';
impor... |
Fix history adding too many things when clicked | import Clipboard from 'clipboard';
import React from 'react';
import { Colours } from '../../modules/colours';
import { Saved } from '../../modules/saved';
export class History extends React.Component {
constructor (props) {
super(props);
this.max = 10;
this.state = {
history: new Array(this.max... | import Clipboard from 'clipboard';
import React from 'react';
import { Colours } from '../../modules/colours';
import { Saved } from '../../modules/saved';
export class History extends React.Component {
constructor (props) {
super(props);
this.max = 10;
this.state = {
history: new Array(this.max... |
Change comment counter in CommentsContainer | 'use strict';
import React, {PropTypes} from 'react';
import Comment from './Comment.component.js';
import {isEmpty, take} from 'lodash';
class CommentsContainerComponent extends React.Component {
constructor() {
super();
this.toggleExpand = this.toggleExpand.bind(this);
this.state = {isExpanded: true};... | 'use strict';
import React, {PropTypes} from 'react';
import Comment from './Comment.component.js';
import {isEmpty, take} from 'lodash';
class CommentsContainerComponent extends React.Component {
constructor() {
super();
this.toggleExpand = this.toggleExpand.bind(this);
this.state = {isExpanded: true};... |
Remove console logging and make email required | 'use strict';
const Joi = require('joi');
const Boom = require('boom');
exports.addTicket = {
description: 'Add new support ticket',
validate: {
payload: {
subject: Joi.string().max(500).allow(''),
email: Joi.string().max(100),
description: Joi.string().max(5000).al... | 'use strict';
const Joi = require('joi');
const Boom = require('boom');
exports.addTicket = {
description: 'Add new support ticket',
validate: {
payload: {
subject: Joi.string().max(500).allow(''),
email: Joi.string().max(100).allow(''),
description: Joi.string().ma... |
Change field defaults from NULL to 0
MariaDB doesn't seem to like numeric/boolean fields to have NULL for a
default value | ->default(0)<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachineSurveydataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::c... | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachineSurveydataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machi... |
Exclude Videos article and non-scrapable info-galleries and picture-galleries via URL-pattern | from baseparser import BaseParser
from BeautifulSoup import BeautifulSoup, Tag
class RPOParser(BaseParser):
domains = ['www.rp-online.de']
feeder_pat = '(?<!(vid|bid|iid))(-1\.\d*)$'
feeder_pages = ['http://www.rp-online.de/']
def _parse(self, html):
soup = BeautifulSoup(html, convertEntitie... | from baseparser import BaseParser
from BeautifulSoup import BeautifulSoup, Tag
class RPOParser(BaseParser):
domains = ['www.rp-online.de']
feeder_pat = '1\.\d*$'
feeder_pages = ['http://www.rp-online.de/']
def _parse(self, html):
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_... |
Add support for git push --no-verify | 'use strict';
var async = require('grunt').util.async;
var grunt = require('grunt');
var ArgUtil = require('flopmang');
module.exports = function (task, exec, done) {
var argUtil = new ArgUtil(task, [
{
option: 'all',
defaultValue: false,
useAsFlag: true,
us... | 'use strict';
var async = require('grunt').util.async;
var grunt = require('grunt');
var ArgUtil = require('flopmang');
module.exports = function (task, exec, done) {
var argUtil = new ArgUtil(task, [
{
option: 'all',
defaultValue: false,
useAsFlag: true,
us... |
tests: Disable some PHP insights sniffs | <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
... | <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
... |
Create select with hook up to store | import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {updateValue} from '../actions/controls';
import {connect} from '../store';
class Select extends Component {
static propTypes = {
className: PropTypes.string,
id: PropTypes.string,
name: PropTypes.string.isRequired,
o... | import React from 'react';
import PropTypes from 'prop-types';
import Control from './Control';
class Select extends Control {
static propTypes = {
className: PropTypes.string,
id: PropTypes.string,
name: PropTypes.string.isRequired,
options: PropTypes.arrayOf(
PropTypes.shape({
name: ... |
Implement lazy continuation rule for block quotes. | <?php
namespace FluxBB\CommonMark\Parser\Block;
use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\Blockquote;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;
class BlockquoteParser extends AbstractBlockParser
{
/**
* Parse the given content.
*
*... | <?php
namespace FluxBB\CommonMark\Parser\Block;
use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\Blockquote;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;
class BlockquoteParser extends AbstractBlockParser
{
/**
* Parse the given content.
*
*... |
Use a realistic User-Agent for reddit | from plugins.categories import ISilentCommand
try:
import requests_pyopenssl
from requests.packages.urllib3 import connectionpool
connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket
except ImportError:
pass
import requests
from bs4 import BeautifulSoup
class URLGrabber (ISilentCommand... | from plugins.categories import ISilentCommand
try:
import requests_pyopenssl
from requests.packages.urllib3 import connectionpool
connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket
except ImportError:
pass
import requests
from bs4 import BeautifulSoup
class URLGrabber (ISilentCommand... |
Fix auto remove thanks to @themouette | /*global window */
define(
[
'text!templates/canvas.html',
'underscore',
'jquery',
'backbone',
'ventilator'
],
function (template, _, $, Backbone, ventilator) {
"use strict";
return new (Backbone.View.extend({
template: _.template(template... | /*global window */
define(
[
'text!templates/canvas.html',
'underscore',
'jquery',
'backbone',
'ventilator'
],
function (template, _, $, Backbone, ventilator) {
"use strict";
return new (Backbone.View.extend({
template: _.template(template... |
Remove extraneous Groups from the View in the VU Meter demo. |
from traits.api import HasTraits, Instance
from traitsui.api import View, UItem, Item, RangeEditor, Group, VGroup
from enable.api import ComponentEditor
from enable.gadgets.vu_meter import VUMeter
class Demo(HasTraits):
vu = Instance(VUMeter)
traits_view = \
View(
VGroup(
... |
from traits.api import HasTraits, Instance
from traitsui.api import View, UItem, Item, RangeEditor, Group, VGroup, HGroup
from enable.api import ComponentEditor
from enable.gadgets.vu_meter import VUMeter
class Demo(HasTraits):
vu = Instance(VUMeter)
traits_view = \
View(
HGroup(
... |
Fix issues identified by Psalm | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject\Rule;
use PHPUnit\Framework... | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject\Rule;
use PHPUnit\Framework... |
:bug: Replace deprecated node type simpleSelector with selector | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'placeholder-in-extend',
'defaults': {},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('atkeyword', function (keyword, i, parent) {
keyword.forEach(function (item) {
if (item.content ===... | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'placeholder-in-extend',
'defaults': {},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('atkeyword', function (keyword, i, parent) {
keyword.forEach(function (item) {
if (item.content ===... |
Make pivot table generation more robust | <?php namespace Way\Generators\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class PivotGeneratorCommand extends BaseGeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protec... | <?php namespace Way\Generators\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class PivotGeneratorCommand extends BaseGeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protec... |
Fix a typo in the documentation of FileReaderDecorator. | # Copyright (c) 2017-2018 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import os
from . import CallableDecorator
class FileReaderDecor... | # Copyright (c) 2017-2018 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import os
from . import CallableDecorator
class FileReaderDecor... |
Read test logs in bytes mode | import os
from datetime import datetime
def save_logs(groomer, test_description):
divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
test_log_path = 'tests/test_logs/{}.log'.format(test_description)
with open(test_log_path, 'w+') as test_log:
test_log.write(divider.format('TEST LOG'))
test_log.... | import os
from datetime import datetime
def save_logs(groomer, test_description):
divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
test_log_path = 'tests/test_logs/{}.log'.format(test_description)
with open(test_log_path, 'w+') as test_log:
test_log.write(divider.format('TEST LOG'))
test_log.... |
Tweak on seeder for categories.
5000 was too much. 200 is fine. | <?php
use Illuminate\Database\Seeder;
use App\Category;
use App\Product;
class CategoriesTableSeeder extends Seeder
{
public function run()
{
$faker = \App::make('Faker\Generator');
/**
* Clear up the tables before adding new data
*/
Category::truncate();
Produ... | <?php
use Illuminate\Database\Seeder;
use App\Category;
use App\Product;
class CategoriesTableSeeder extends Seeder
{
public function run()
{
$faker = \App::make('Faker\Generator');
/**
* Clear up the tables before adding new data
*/
Category::truncate();
Produ... |
Fix OBO serializer assuming `Ontology._terms` is properly ordered | import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
... | import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
... |
Use an instance variable instead of a non-standard argument to __repr__ | from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwargs)
class BaseEntity(object):
__repr_attrs__ = ('id',)
def __... | from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwargs)
class BaseEntity(object):
def __init__(self, provider, **kwar... |
Disable slash escaping by default | <?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files ... | <?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files ... |
Fix spelling error in API key creation modal | import React from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { Alert, Icon } from "../../../base";
const StyledCreateAPIKeyInfo = styled(Alert)`
display: flex;
margin-bottom: 5px;
i {
line-height: 20px;
}
p {
margin-left: 5px;
... | import React from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { Alert, Icon } from "../../../base";
const StyledCreateAPIKeyInfo = styled(Alert)`
display: flex;
margin-bottom: 5px;
i {
line-height: 20px;
}
p {
margin-left: 5px;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.