text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Set window title in application | package rpi.lmsgrabber;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import... | package rpi.lmsgrabber;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import... |
Handle errors in cron notifications | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from api import models
from web.utils import send_email
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
notifications = models.Notification.objects.filter(email_sent=Fa... | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from api import models
from web.utils import send_email
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
notifications = models.Notification.objects.filter(email_sent=Fa... |
Fix issue in refinery contract | <?php
namespace Michaeljennings\Refinery\Contracts;
interface Refinery
{
/**
* Refine the item(s) using the set template.
*
* @param mixed $raw
* @return mixed
*/
public function refine($raw);
/**
* Refine a collection of raw items.
*
* @param mixed $raw
* @... | <?php
namespace Michaeljennings\Refinery\Contracts;
interface Refinery
{
/**
* Refine the item(s) using the set template.
*
* @param mixed $raw
* @return mixed
*/
public function refine($raw);
/**
* Refine a collection of raw items.
*
* @param mixed $raw
* @... |
Allow to set items in AST. | from collections import OrderedDict, Mapping
import json
__all__ = ['AST']
class AST(Mapping):
def __init__(self, **kwargs):
self._elements = OrderedDict(**kwargs)
def add(self, key, value):
previous = self._elements.get(key, None)
if previous is None:
self._elements[key] ... | from collections import OrderedDict, Mapping
import json
class AST(Mapping):
def __init__(self, **kwargs):
self._elements = OrderedDict(**kwargs)
def add(self, key, value):
previous = self._elements.get(key, None)
if previous is None:
self._elements[key] = [value]
e... |
Support filtering all test cases without failing the whole test suite
If all test cases in a test suite fails, jest will complain and fail the whole suite. This can be worked around by adding a skipped test if there's no other test. | /* global describe it beforeAll beforeEach afterAll afterEach fail */
const BotiumBindings = require('../BotiumBindings')
const defaultTimeout = 60000
const setupJasmineTestCases = ({ timeout = defaultTimeout, testcaseSelector, bb } = {}) => {
bb = bb || new BotiumBindings()
bb.setupTestSuite(
(testcase, te... | /* global describe it beforeAll beforeEach afterAll afterEach fail */
const BotiumBindings = require('../BotiumBindings')
const defaultTimeout = 60000
const setupJasmineTestCases = ({ timeout = defaultTimeout, testcaseSelector, bb } = {}) => {
bb = bb || new BotiumBindings()
bb.setupTestSuite(
(testcase, te... |
Set parameters of serial class to match with kilt | #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=38400,
... | #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=9600,
... |
Add removed posts as an API attribute | <?php namespace Flarum\Api\Serializers;
class DiscussionBasicSerializer extends BaseSerializer
{
/**
* The resource type.
*
* @var string
*/
protected $type = 'discussions';
/**
* Serialize attributes of a Discussion model for JSON output.
*
* @param Discussion $discussi... | <?php namespace Flarum\Api\Serializers;
class DiscussionBasicSerializer extends BaseSerializer
{
/**
* The resource type.
*
* @var string
*/
protected $type = 'discussions';
/**
* Serialize attributes of a Discussion model for JSON output.
*
* @param Discussion $discussi... |
Add integration test via docker | 'use strict';
/*jslint nomen: true, stupid: true*/
module.exports = function (grunt) {
grunt.registerTask('integration-test', 'Run integration tests', [
'docker-integration-test'
]);
grunt.registerMultiTask('docker-integration-test', function runTask() {
/*eslint-disable no-invalid-this*/... | 'use strict';
/*jslint nomen: true, stupid: true*/
module.exports = function (grunt) {
grunt.registerTask('integration-test', 'Run integration tests', [
'docker-integration-test'
]);
grunt.registerMultiTask('docker-integration-test', function runTask() {
/*eslint-disable no-invalid-this*/... |
Add new entry in pricetable Print&Copy section. | package io.github.proxyprint.kitchen.controllers.printshops;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import io.github.proxyprint.kitchen.models.printshops.PrintShop;
import io.github.proxyprint.kitchen.models.printshops.pricetable.PaperTableItem;
import io.gi... | package io.github.proxyprint.kitchen.controllers.printshops;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import io.github.proxyprint.kitchen.models.printshops.PrintShop;
import io.github.proxyprint.kitchen.models.printshops.pricetable.PaperTableItem;
import io.gi... |
Send what state is saved | import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
... | import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
... |
Throw ValidatorExceptions instead of vanilla Exceptions for validation failures. | <?php
/**
* php-binary
* A PHP library for parsing structured binary streams
*
* @package php-binary
* @author Damien Walsh <me@damow.net>
*/
namespace Binary\Field;
use Binary\Exception\ValidatorException;
use Binary\Validator\AbstractValidator;
/**
* Field
* Abstract.
*
* @since 1.0
*/
abstract class Ab... | <?php
/**
* php-binary
* A PHP library for parsing structured binary streams
*
* @package php-binary
* @author Damien Walsh <me@damow.net>
*/
namespace Binary\Field;
use Binary\Exception\ValidatorException;
use Binary\Validator\AbstractValidator;
/**
* Field
* Abstract.
*
* @since 1.0
*/
abstract class Ab... |
Add default value parameter when getting an input variable | <?php
/**
* Input handler
*
* Very basic input handler
*
* @author Adric Schreuders
*/
class Input {
private $vars;
public function Input($vars) {
$this->vars = $vars;
}
public function get($name = null, $default = null) {
if ($name === null) {
return $this->vars;
... | <?php
/**
* Input handler
*
* Very basic input handler
*
* @author Adric Schreuders
*/
class Input {
private $vars;
public function Input($vars) {
$this->vars = $vars;
}
public function get($name) {
if (isset($this->vars[$name])) {
return $this->vars[$name];
} ... |
Add load config function to Sheldon class | # -*- 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 *
from sheldon.utils import logger
... | # -*- 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 ... |
Clean up some linter warnings | var hooks = require('hooks');
var async = require('async');
function Renderable(View) {
this.data = {};
this.mode = 'main';
this.view = {};
if (typeof View === 'function') {
this.view = new View();
}
this.render = function(cb) {
// recursively render any Renderable objects inside this.data
//... | var hooks = require('hooks');
var async = require('async');
function Renderable(View) {
this.data = {};
this.mode = 'main';
this.view = {};
if (typeof View === 'function') {
this.view = new View();
}
this.render = function(cb) {
// recursively render any Renderable objects inside this.data
//... |
Fix traits boot/destroy method names | <?php
/**
* This file is part of Railt package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Railt\Testing\Feature;
/**
* Trait BootableTraits
*/
trait BootableTraits
{
/**
* @return... | <?php
/**
* This file is part of Railt package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Railt\Testing\Feature;
/**
* Trait BootableTraits
*/
trait BootableTraits
{
/**
* @return... |
Update dumping to osf logic | from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
found, _hash = collision.already_processed(raw_doc)
if found:... | from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.dump_metdata(normalized... |
Make less verbose as going to try running sep too | <?php
namespace phpSmug\Tests;
/**
* @class
* Test properties of our codebase rather than the actual code.
*/
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function testPSR()
{
// If we can't find the command-line tool, we mark the test as skipped... | <?php
namespace phpSmug\Tests;
/**
* @class
* Test properties of our codebase rather than the actual code.
*/
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function testPSR()
{
// If we can't find the command-line tool, we mark the test as skipped... |
Change license to MIT to match the project | <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/mit-license.php MIT
*
*/
namespace Aura\Router\Helper;
use Aura\Router\Exception\RouteNotFound;
use Aura\Router\Generator;
/**
*
* Generic Url Helper class
*
* @package Aura.Router
*
*/
class Url
{
/**
*
... | <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*/
namespace Aura\Router\Helper;
use Aura\Router\Exception\RouteNotFound;
use Aura\Router\Generator;
/**
*
* Generic Url Helper class
*
* @package Aura.Router
*
*/
class Url
{
/**
*
... |
Append version to JS url to avoid caching issues when a new version is released | <?php
namespace BoomCMS\Http\Middleware;
use BoomCMS\Editor\Editor;
use BoomCMS\Support\Facades\BoomCMS;
use BoomCMS\UI;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class DefineCMSViewSharedVariables
{
private $app;
/**
* @var Ed... | <?php
namespace BoomCMS\Http\Middleware;
use BoomCMS\Editor\Editor;
use BoomCMS\UI;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class DefineCMSViewSharedVariables
{
private $app;
/**
* @var Editor
*/
private $editor;
... |
Rename locale field to language. | # -*- 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... |
Add user to auth response | <?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ODADnepr\MockServiceBundle\EventListener;
use Lex... | <?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ODADnepr\MockServiceBundle\EventListener;
use Lex... |
[chain] Improve enable module:install command execution | <?php
/**
* @file
* Contains \Drupal\Console\EventSubscriber\CallCommandListener.
*/
namespace Drupal\Console\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\Conso... | <?php
/**
* @file
* Contains \Drupal\Console\EventSubscriber\CallCommandListener.
*/
namespace Drupal\Console\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\Conso... |
feat: Delete condition of type in event as it should always be true | import time
import linkatos.parser as parser
import linkatos.printer as printer
import linkatos.firebase as fb
import linkatos.reaction as react
def is_empty(events):
return ((events is None) or (len(events) == 0))
def is_url(url_message):
return url_message['type'] == 'url'
def event_consumer(expecting_u... | import time
import linkatos.parser as parser
import linkatos.printer as printer
import linkatos.firebase as fb
import linkatos.reaction as react
def is_empty(events):
return ((events is None) or (len(events) == 0))
def is_url(url_message):
return url_message['type'] == 'url'
def event_consumer(expecting_u... |
FIX | Tirando token para inserção de provas | var ormDic = require('../../util/ormDic');
class OrmProxy {
constructor() {
this._orm = null;
}
setOrm(string) {
this._orm = ormDic[string];
}
add(req, res) {
this._orm.add(req, res);
}
delete(req, res) {
if (req.headers.token === null || req.headers.token... | var ormDic = require('../../util/ormDic');
class OrmProxy {
constructor() {
this._orm = null;
}
setOrm(string) {
this._orm = ormDic[string];
}
add(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
resp... |
Update GitHub repos from blancltd to developersociety | #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='blanc-basic-podcast',
version='0.3',
description='Blanc Basic Podcast for Django',
long_description=readme,
url='https://githu... | #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='blanc-basic-podcast',
version='0.3',
description='Blanc Basic Podcast for Django',
long_description=readme,
url='https://githu... |
Remove brackets around data and time in logs
Change-Id: Ia424eecb8a30ee9f73b9b007db2fd81f07ab509f
Reviewed-on: http://review.couchbase.org/79748
Well-Formed: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pav... | import logging.config
import sys
import types
LOGGING_CONFIG = {
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s - %(levelname)s - %(message)s',
'datefmt': '%Y-%m-%dT%H:%M:%S',
},
},
'handlers': {
'file': {
... | import logging.config
import sys
import types
LOGGING_CONFIG = {
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s - %(levelname)s - %(message)s',
'datefmt': '[%Y-%m-%dT%H:%M:%S]',
},
},
'handlers': {
'file': {
... |
Fix apply microdata for links | <?php
/**
* Created by PhpStorm.
* Date: 2017-02-01
* Time: 23:06
*/
namespace mp\bmicrodata;
use yii\widgets\Breadcrumbs;
/**
* Class BreadcrumbsMicrodata
* @package mp\bmicrodata
*/
class BreadcrumbsMicrodata extends Breadcrumbs
{
/**
* BreadcrumbsMicrodata constructor.
* @param array $config
... | <?php
/**
* Created by PhpStorm.
* Date: 2017-02-01
* Time: 23:06
*/
namespace mp\bmicrodata;
use yii\widgets\Breadcrumbs;
/**
* Class BreadcrumbsMicrodata
* @package mp\bmicrodata
*/
class BreadcrumbsMicrodata extends Breadcrumbs
{
/**
* BreadcrumbsMicrodata constructor.
* @param array $config
... |
Update @BeforeMethod test to use dependsOnMethods and removed page load | package com.frameworkium.integration.frameworkium.tests;
import com.frameworkium.core.ui.tests.BaseUITest;
import com.frameworkium.integration.frameworkium.pages.JQueryDemoPage;
import com.frameworkium.integration.seleniumhq.pages.SeleniumDownloadPage;
import org.testng.annotations.BeforeMethod;
import org.testng.anno... | package com.frameworkium.integration.frameworkium.tests;
import com.frameworkium.core.ui.tests.BaseUITest;
import com.frameworkium.integration.frameworkium.pages.JQueryDemoPage;
import com.frameworkium.integration.seleniumhq.pages.SeleniumDownloadPage;
import com.frameworkium.integration.theinternet.pages.WelcomePage;... |
Add Id field to ProtoServer
Keep it at uuid.UUID for now. Conversion to string will happen
together with soma and somaadm server implementation/fixes. | package somaproto
import "github.com/satori/go.uuid"
type ProtoRequestServer struct {
Server ProtoServer `json:"server,omitempty"`
Filter ProtoServerFilter `json:"filter,omitempty"`
Purge bool `json:"purge,omitempty"`
}
type ProtoResultServer struct {
Code uint16 `json:"code,omitemp... | package somaproto
type ProtoRequestServer struct {
Server ProtoServer `json:"server,omitempty"`
Filter ProtoServerFilter `json:"filter,omitempty"`
Purge bool `json:"purge,omitempty"`
}
type ProtoResultServer struct {
Code uint16 `json:"code,omitempty"`
Status string `json:"s... |
Fix Flashmessage return int instead of Message array
git-svn-id: a31028ace08b9bd728961381d3e3adab14c71477@50 85223511-97c2-6742-acd2-766018259031 | <?php
namespace FMUP\FlashMessenger\Driver;
use FMUP\FlashMessenger\DriverInterface;
use FMUP\FlashMessenger\Message;
/**
* Description of Session
*
* @author sweffling
*/
class Session implements DriverInterface
{
private $session;
/**
* @return \FMUP\Session
*/
private f... | <?php
namespace FMUP\FlashMessenger\Driver;
use FMUP\FlashMessenger\DriverInterface;
use FMUP\FlashMessenger\Message;
/**
* Description of Session
*
* @author sweffling
*/
class Session implements DriverInterface
{
private $session;
/**
* @return \FMUP\Session
*/
private f... |
Use L&F that is available on JDK 1.3
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1344 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | package com.thoughtworks.acceptance;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class SwingTest extends AbstractAcceptanceTest {
// JTable is one of the nastiest components to ser... | package com.thoughtworks.acceptance;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.synth.SynthLookAndFeel;
public class SwingTest extends AbstractAcceptanceTest {
// JTable is one of the nastiest components to ser... |
Add handling for invalid JSON returned | import queryString from "query-string";
class Api {
static get(url, data = {}) {
return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET");
}
static post(url, data = {}) {
return this.request(url, data, "POST");
}
stati... | import queryString from "query-string";
class Api {
static get(url, data = {}) {
return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET");
}
static post(url, data = {}) {
return this.request(url, data, "POST");
}
stati... |
Refresh page when creating menus, module bi_view_editor | # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
... | # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
... |
Fix ivory geocoder reverse method... | <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <geloen.eric@gmail.com>
*/
class Geocoder extends ... | <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <geloen.eric@gmail.com>
*/
class Geocoder extends ... |
Set notification.backends.EmailBackend.sensitivity = 3, so that it has a different sensitivity from the WebBackend | from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
sensitivity = 3
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, rec... | from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
sensitivity = 2
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, rec... |
Update receiver to catch value error | from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k val... | from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k val... |
Remove unneeded -p from mkdir call | const FS = require('fs');
const Child = require('child_process').execSync;
// Copy local package files
Child('npm run clean');
Child('npm run compile');
Child('npm run compile:module');
Child('npm run compile:rollup');
Child('npm run compile:rollup-browser');
Child('mkdir dist/npm');
Child('cp -r dist/cjs/* dist/npm/'... | const FS = require('fs');
const Child = require('child_process').execSync;
// Copy local package files
Child('npm run clean');
Child('npm run compile');
Child('npm run compile:module');
Child('npm run compile:rollup');
Child('npm run compile:rollup-browser');
Child('mkdir -p dist/npm');
Child('cp -r dist/cjs/* dist/np... |
Rename translations to translations_select, switch to HTTPS | """
VerseBot for reddit
By Matthieu Grieger
webparser.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations att... | """
VerseBot for reddit
By Matthieu Grieger
webparser.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations att... |
docs: Add source for geolocation function | // use strict:
"use strict";
// Function gets the location of the user provided the user opts in
// function adapted from Sitepoint; https://www.sitepoint.com/html5-geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPosition, showError);
} else {
alert('Geolocation is not sup... | // use strict:
"use strict";
// Function gets the location of the user provided the user opts in
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPosition, showError);
} else {
alert('Geolocation is not supported in your browser so cannot display your local weather');
}
// Success cal... |
Fix isset POST key for remove and send template | <?php
namespace App\Controller;
class Templates extends \App\Controller\App
{
public function action_index()
{
$this->view->title = 'SMS Templates';
if ($this->request->method == 'POST') {
foreach ($this->request->post('templatesId') as $templateId) {
$template = ... | <?php
namespace App\Controller;
class Templates extends \App\Controller\App
{
public function action_index()
{
$this->view->title = 'SMS Templates';
if ($this->request->method == 'POST') {
foreach ($this->request->post('templatesId') as $templateId) {
$template = ... |
Update slack username for JD | import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty.dawson", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def ... | import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def process... |
Move $app['storage.metadata']->setDefaultAlias into storage extend | <?php
namespace Bolt\Extension;
use Pimple as Container;
/**
* Storage helpers.
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
*/
trait StorageTrait
{
/**
* Return a list of entities to map to repositories.
*
* <pre>
* return [
* 'alias' => [\Entity\Class\Name => \Repository... | <?php
namespace Bolt\Extension;
use Pimple as Container;
/**
* Storage helpers.
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
*/
trait StorageTrait
{
/**
* Return a list of entities to map to repositories.
*
* <pre>
* return [
* 'alias' => [\Entity\Class\Name => \Repository... |
Add default view for camera | from traits.api import HasTraits, Int, Str, Tuple, Array, Range
from traitsui.api import View, Label
class CameraError(Exception):
def __init__(self, msg, cam):
self.msg = msg
self.camera_number = cam
def __str__(self):
return '{0} on camera {1}'.format(self.msg, self.camera_n... | from traits.api import HasTraits, Int, Str, Tuple, Array, Range
class CameraError(Exception):
def __init__(self, msg, cam):
self.msg = msg
self.camera_number = cam
def __str__(self):
return '{0} on camera {1}'.format(self.msg, self.camera_number)
class Camera(HasTraits):... |
Fix bug in sentiment calculation
Signed-off-by: Itai Koren <7a3f8a9ea5df78694ad87e4c8117b31e1b103a24@gmail.com> | // Include The 'require.async' Module
require("require.async")(require);
/**
* Tokenizes an input string.
*
* @param {String} Input
*
* @return {Array}
*/
function tokenize (input) {
return input
.replace(/[^a-zA-Z ]+/g, "")
.replace("/ {2,}/", " ")
.toLowerCase()
... | // Include The 'require.async' Module
require("require.async")(require);
/**
* Tokenizes an input string.
*
* @param {String} Input
*
* @return {Array}
*/
function tokenize (input) {
return input
.replace(/[^a-zA-Z ]+/g, "")
.replace("/ {2,}/", " ")
.toLowerCase()
... |
Add test names for parametrized tests | import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import R from 'ramda';
import { Link } from 'react-router';
import EntityListItem from '../../../src/components/EntityListItem';
describe('EntityListItem', function () {
function createDefaultProps() {
return {
... | import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import R from 'ramda';
import { Link } from 'react-router';
import EntityListItem from '../../../src/components/EntityListItem';
describe('EntityListItem', function () {
function createDefaultProps() {
return {
... |
Remove tox and pep8 from "install" requires.
https://github.com/jdowner/requires-provides/issues/2 | #!/usr/bin/env python
import setuptools
setuptools.setup(
name='requires-provides',
version='0.1',
description='Flexible dependency decorators',
license='MIT',
author='Joshua Downer',
author_email='joshua.downer@gmail.com',
url='http://github.com/jdowner/requir... | #!/usr/bin/env python
import setuptools
setuptools.setup(
name='requires-provides',
version='0.1',
description='Flexible dependency decorators',
license='MIT',
author='Joshua Downer',
author_email='joshua.downer@gmail.com',
url='http://github.com/jdowner/requir... |
Fix error with minified JS | /* This file is part of Indico.
* Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
*
* Indico is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License... | /* This file is part of Indico.
* Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
*
* Indico is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License... |
Make NickServIdentify play nice with service specific configs | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
import logging
class NickServIdentify(BotModule):
implements(IPlugin, IBotModule)
name = "NickServIdentify"
def hookBot(self, bot):
self.bot = bot
def actions(... | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
import logging
class NickServIdentify(BotModule):
implements(IPlugin, IBotModule)
name = "NickServIdentify"
def hookBot(self, bot):
self.bot = bot
def actions(... |
Add missing requirement for libvirt-python
libvirt-python is missing from setup.py
Change-Id: I41c2e29d612ba0b45f94c2340b9a6a3472d5bbdc
Closes-bug: #1385439 | # Copyright 2013 - 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | # Copyright 2013 - 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
Prepare elements for new styles | import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux';
import SelectGender from './components/SelectGender.js';
import store from './store.js';
import Restart from './components/Restart.js';
import Action from './components/Action.js';
import AcceptedList from './components... | import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux';
import SelectGender from './components/SelectGender.js';
import store from './store.js';
import Restart from './components/Restart.js';
import Action from './components/Action.js';
import AcceptedList from './components... |
Reduce number of database queries | from django import forms
from django.conf import settings
from django.utils.dateparse import parse_datetime
import os
from .saltedge import SaltEdge
from .models import Transaction, Category
from decimal import Decimal
class ImportTransactionsForm(forms.Form):
def import_transactions(self):
app = SaltEdge... | from django import forms
from django.conf import settings
from django.utils.dateparse import parse_datetime
import os
from .saltedge import SaltEdge
from .models import Transaction, Category
from decimal import Decimal
class ImportTransactionsForm(forms.Form):
def import_transactions(self):
app = SaltEdge... |
Use spree/spree source for spec | import * as React from 'react'
import { RedocStandalone } from 'redoc'
import Layout from '../../components/Layout'
const IndexPage = () => (
<Layout activeRootSection="api/v2">
<RedocStandalone
specUrl="https://raw.githubusercontent.com/spree/spree/master/api/docs/v2/storefront/index.yaml"
options=... | import * as React from 'react'
import { RedocStandalone } from 'redoc'
import Layout from '../../components/Layout'
const IndexPage = () => (
<Layout activeRootSection="api/v2">
<RedocStandalone
specUrl="https://raw.githubusercontent.com/spark-solutions/spree/master/api/docs/v2/storefront/index.yaml"
... |
Add neighbrhood property to row | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... |
MB-13234: Make `top` work on Ubuntu 12.04
The `top` in Ubuntu12.04 seems to do different command line parsing
than the one on CentOS. Separating the parameters should work on
both.
Change-Id: I8f9ec022bcb8e0158316fdaac226acbfb0d9d004
Reviewed-on: http://review.couchbase.org/50126
Reviewed-by: Dave Rigby <a09264da4832... | from fabric.api import run
from cbagent.collectors.libstats.remotestats import (
RemoteStats, multi_node_task)
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
def __init__(self, hosts, user, password):
super(PSStats, self).__init__(host... | from fabric.api import run
from cbagent.collectors.libstats.remotestats import (
RemoteStats, multi_node_task)
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
def __init__(self, hosts, user, password):
super(PSStats, self).__init__(host... |
Handle compatibility for symfony <= 2.5 | <?php
namespace JBen87\ParsleyBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* @author Benoit Jouhaud <bjouhaud@prestaconcept.net>
*/
class Pa... | <?php
namespace JBen87\ParsleyBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* @author Benoit Jouhaud <bjouhaud@prestaconcept.net>
*/
class Pa... |
IFS-5827: Hide button for single applicant | package org.innovateuk.ifs.application.overview.viewmodel;
import org.innovateuk.ifs.application.viewmodel.AssignButtonsViewModel;
import java.util.Optional;
/**
* View model for each row with a link in the application overview page.
*/
public class ApplicationOverviewRowViewModel {
private final String title... | package org.innovateuk.ifs.application.overview.viewmodel;
import org.innovateuk.ifs.application.viewmodel.AssignButtonsViewModel;
import java.util.Optional;
/**
* View model for each row with a link in the application overview page.
*/
public class ApplicationOverviewRowViewModel {
private final String title... |
Add subordinate pages to Entry page in navigation. | <?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initViewHeadTitle()
{
$this->bootstrap('view');
/* @var $view Zend_View_Abstract */
$view = $this->getResource('view');
$view->headTitle()->setSeparator(' :: ');
$view->headTitle()->... | <?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initViewHeadTitle()
{
$this->bootstrap('view');
/* @var $view Zend_View_Abstract */
$view = $this->getResource('view');
$view->headTitle()->setSeparator(' :: ');
$view->headTitle()->... |
Introduce variable for plan id. formatting. | <?php
require_once('./config.php');
var_dump($_POST);
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$amount = $_POST['amount'];
$recurring = $_POST['recurring'];
// validate the amount
$plan_id = "monthly{$amount}";
$plan_name = "Monthly {$amount}";
if ( !empty($recurr... | <?php
require_once('./config.php');
var_dump($_POST);
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$amount = $_POST['amount'];
$recurring = $_POST['recurring'];
// validate the amount
if ( !empty($recurring) ) {
try {
$plan = Stripe_Plan::retrieve("monthly{$am... |
Fix unit test for when robotframework is not installed. | import unittest
import robotide.lib.robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
... | import unittest
import robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
def test_... |
Select top most version if non selected for top crashers | $(document).ready(function () {
var url_base = $("#url_base").val(),
url_site = $("#url_site").val(),
product,
product_version,
report;
$("#q").focus(function () {
$(this).attr('value', '');
});
// Used to handle the selection of specific product.
if ($("#pr... | $(document).ready(function () {
var url_base = $("#url_base").val(),
url_site = $("#url_site").val(),
product,
product_version,
report;
$("#q").focus(function () {
$(this).attr('value', '');
});
// Used to handle the selection of specific product.
if ($("#pr... |
Add source elements url + jwt to resource model | <?php
namespace Hub\Client\Model;
class Resource
{
protected $type;
protected $shares = array();
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
private $properties =... | <?php
namespace Hub\Client\Model;
class Resource
{
protected $type;
protected $shares = array();
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
private $properties =... |
Add function to get profile. Refactor. | /*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");
class FBMessenger {
constructor(token) {
this._fbBase = "https://graph.facebook.com/v2.6/";
this._token = token;
this._q = qs.stringify({access_token: token});
... | /*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");
class FBMessenger {
constructor(token) {
this._fbBase = "https://graph.facebook.com/v2.6/me/";
this._token = token;
this._q = qs.stringify({access_token: token}... |
Add level attribute and proper sorting. | <?php
namespace common\models\comments;
class AdjacencyListComment extends Comment
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%comment_al}}';
}
public static function findByPostInternal($postId)
{
$comments = static::find()
->se... | <?php
namespace common\models\comments;
class AdjacencyListComment extends Comment
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%comment_al}}';
}
public static function findByPostInternal($postId)
{
$comments = static::find()
->se... |
Fix regex for pyflakes output format since `2.2.0` | from SublimeLinter.lint import PythonLinter
import re
class Pyflakes(PythonLinter):
cmd = 'pyflakes'
regex = r'''(?x)
^(?P<filename>.+):(?P<line>\d+):((?P<col>\d+):?)?\s
# The rest of the line is the error message.
# Within that, capture anything within single quotes as `near`.
... | from SublimeLinter.lint import PythonLinter
import re
class Pyflakes(PythonLinter):
cmd = 'pyflakes'
regex = r'''(?x)
^(?P<filename>[^:\n]+):(?P<line>\d+):((?P<col>\d+):)?\s
# The rest of the line is the error message.
# Within that, capture anything within single quotes as `near`.
... |
Fix source and destination paths for installing plugins from local disk
They were installing into eg. my.plugin.id/plugman_dir_basename/*
instead of just my.plugin.id/*. | var shell = require('shelljs'),
fs = require('fs'),
plugins = require('./util/plugins'),
xml_helpers = require('./util/xml-helpers'),
path = require('path');
module.exports = function fetchPlugin(plugin_dir, plugins_dir, link, subdir, callback) {
// Ensure the containing directory exists.... | var shell = require('shelljs'),
fs = require('fs'),
plugins = require('./util/plugins'),
xml_helpers = require('./util/xml-helpers'),
path = require('path');
module.exports = function fetchPlugin(plugin_dir, plugins_dir, link, subdir, callback) {
// Ensure the containing directory exists.... |
Add attributes for 'font' tag to the whitelist | package com.fsck.k9.message.html;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;
public class HtmlSanitizer {
private final HeadCleaner headCleaner;
private final Cleaner cleaner;
HtmlSanitizer() {
Whitelist whitelist... | package com.fsck.k9.message.html;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;
public class HtmlSanitizer {
private final HeadCleaner headCleaner;
private final Cleaner cleaner;
HtmlSanitizer() {
Whitelist whitelist... |
requireTrailingComma: Fix incorrect option name in error message | var assert = require('assert');
var tokenHelper = require('../token-helper');
module.exports = function() {};
module.exports.prototype = {
configure: function(requireTrailingComma) {
if (typeof requireTrailingComma === 'object') {
assert(
requireTrailingComma.ignoreSingleValue ... | var assert = require('assert');
var tokenHelper = require('../token-helper');
module.exports = function() {};
module.exports.prototype = {
configure: function(requireTrailingComma) {
if (typeof requireTrailingComma === 'object') {
assert(
requireTrailingComma.ignoreSingleValue ... |
Use game.queue.is_turn(name) to build player or enemies | import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. "... | import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game st... |
Update local Date automatically each 60s | import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: 'ctw@ctwhome.com',
picture: '//icons.iconarchive.com/i... | import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: 'ctw@ctwhome.com',
picture: '//icons.iconarchive.com/i... |
Use self instead of class name | <?php
namespace MicroFW\Templates;
use MicroFW\Core\TemplateDoesNotExistException;
class Template
{
/** @var string */
private $templatePath;
/** @var array */
private $context;
/** @var MicroFW\Core\IConfigurator */
private static $configurator;
/**
* @param $templatePath string
... | <?php
namespace MicroFW\Templates;
use MicroFW\Core\TemplateDoesNotExistException;
class Template
{
/** @var string */
private $templatePath;
/** @var array */
private $context;
/** @var MicroFW\Core\IConfigurator */
private static $configurator;
/**
* @param $templatePath string
... |
Fix potential bug when key returns null | <?php
namespace Styde\Html\Alert;
use Illuminate\Session\Store as Session;
class SessionHandler implements Handler
{
/**
* Laravel's component to handle sessions
*
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* Reserved session key for this component
*
* ... | <?php
namespace Styde\Html\Alert;
use Illuminate\Session\Store as Session;
class SessionHandler implements Handler
{
/**
* Laravel's component to handle sessions
*
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* Reserved session key for this component
*
* ... |
Print devices example - change out format | # import PyOpenCL and Numpy. An OpenCL-enabled GPU is not required,
# OpenCL kernels can be compiled on most CPUs thanks to the Intel SDK for OpenCL
# or the AMD APP SDK.
import pyopencl as cl
def main():
dev_type_str = {}
for dev_type in ['ACCELERATOR', 'ALL', 'CPU', 'CUSTOM', 'DEFAULT', 'GPU']:
dev_t... | # import PyOpenCL and Numpy. An OpenCL-enabled GPU is not required,
# OpenCL kernels can be compiled on most CPUs thanks to the Intel SDK for OpenCL
# or the AMD APP SDK.
import pyopencl as cl
def main():
dev_type_str = {}
for dev_type in ['ACCELERATOR', 'ALL', 'CPU', 'CUSTOM', 'DEFAULT', 'GPU']:
dev_t... |
Rename class attribute, method and variable | <?php
namespace Bauhaus;
use InvalidArgumentException;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
class Application
{
private $middlewareStack = [];
public fu... | <?php
namespace Bauhaus;
use InvalidArgumentException;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
class Application
{
private $stack = [];
public function sta... |
Fix form field custom kwarg | # coding=utf-8
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.itercompat import is_iterable
from six import string_types
from . import settings
from .forms import StdnumField
__all__ = [
'StdNumField',
]
class StdNumField(models.CharField):
"""Model f... | # coding=utf-8
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.itercompat import is_iterable
from six import string_types
from . import settings
from .forms import StdnumField
__all__ = [
'StdNumField',
]
class StdNumField(models.CharField):
"""Model f... |
Fix debug mode on application | <?php
namespace HeyDoc;
use dflydev\markdown\MarkdownExtraParser;
use HeyDoc\Exception\NotFoundException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
class Application
{
/** @var **/
protected $container;
/** @var **/
protected $page;
/**
* Con... | <?php
namespace HeyDoc;
use dflydev\markdown\MarkdownExtraParser;
use HeyDoc\Exception\NotFoundException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
class Application
{
/** @var **/
protected $container;
/** @var **/
protected $page;
/**
* Con... |
Increase watermark by one everytime when an entry is written | package uk.gov;
import org.postgresql.util.PGobject;
import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class DestinationPostgresDB extends PostgresDB {
private final String indexedEntriesTableName;
private f... | package uk.gov;
import org.postgresql.util.PGobject;
import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class DestinationPostgresDB extends PostgresDB {
private final String indexedEntriesTableName;
private f... |
Fix element lookup and add docstrings | /*jslint browser:true */
/*global $, Spinner*/
(function mplStyleGallery() {
'use strict';
/**
* Create simple lightbox for viewing images.
*
* @param {JQuery} Target lightbox div containing single `img` element.
*/
function createLightbox($el) {
var ESCAPE_KEY = 27,
... | /*jslint browser:true */
/*global $, Spinner*/
(function mplStyleGallery() {
'use strict';
function createLightbox($el) {
var ESCAPE_KEY = 27,
lightboxFacade;
// Press ESCAPE to hide the lightbox window.
$(document).keyup(function (event) {
if (event.keyCode ==... |
Handle IOError in run_once mode so paging works
Signed-off-by: Raul Gutierrez S <f25f6873bbbde69f1fe653b3e6bd40d543b8d0e0@itevenworks.net> | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... |
Set action to information when routing to workshop details | // Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopController from './workshop.controller';
import WorkshopHeaderController from './workshop-header.controller';
import { workshop } from './workshop.resolve';
import { carBrands } from '../home/home.resolve';
/**
* @ngInject
* @para... | // Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopController from './workshop.controller';
import WorkshopHeaderController from './workshop-header.controller';
import { workshop } from './workshop.resolve';
import { carBrands } from '../home/home.resolve';
/**
* @ngInject
* @para... |
CHANGE the refs of dev-kit example to the next branch | module.exports = {
stories: ['./stories/*.*'],
refs: {
ember: {
id: 'ember',
title: 'Ember',
url: 'https://next--storybookjs.netlify.app/ember-cli',
},
cra: 'https://next--storybookjs.netlify.app/cra-ts-kitchen-sink',
},
webpack: async (config) => ({
...config,
module: {
... | module.exports = {
stories: ['./stories/*.*'],
refs: {
ember: {
id: 'ember',
title: 'Ember',
url: 'https://deploy-preview-9210--storybookjs.netlify.app/ember-cli',
},
cra: 'https://deploy-preview-9210--storybookjs.netlify.app/cra-ts-kitchen-sink',
},
webpack: async (config) => ({
... |
Mark the py.test test as not to be run in nose. | """Tests of the test-runner plugins."""
import py
import unittest
from nose.plugins import PluginTester
from coverage.runners.noseplugin import Coverage
class TestCoverage(PluginTester, unittest.TestCase):
"""Test the nose plugin."""
activate = '--with-coverage' # enables the plugin
plugins = [Coverage()... | """Tests of the test-runner plugins."""
import py
import unittest
from nose.plugins import PluginTester
from coverage.runners.noseplugin import Coverage
class TestCoverage(PluginTester, unittest.TestCase):
"""Test the nose plugin."""
activate = '--with-coverage' # enables the plugin
plugins = [Coverage()... |
Use dictionary update instead of addition | import re
from regparser.layer.layer import Layer
import settings
class Meta(Layer):
shorthand = 'meta'
def __init__(self, tree, cfr_title, version, **context):
super(Meta, self).__init__(tree, **context)
self.cfr_title = cfr_title
self.version = version
def process(self, node):... | import re
from regparser.layer.layer import Layer
import settings
class Meta(Layer):
shorthand = 'meta'
def __init__(self, tree, cfr_title, version, **context):
super(Meta, self).__init__(tree, **context)
self.cfr_title = cfr_title
self.version = version
def process(self, node):... |
Append nominator user id when nominating a household | <?php
namespace App\Http\Controllers\Admin;
use App\Base\Controllers\AdminController;
use App\Http\Controllers\Api\DataTables\HouseholdDataTable;
use App\Http\Requests\Admin\HouseholdRequest;
use App\Household;
use Auth;
class HouseholdController extends AdminController
{
/**
* Display a listing of the user... | <?php
namespace App\Http\Controllers\Admin;
use App\Base\Controllers\AdminController;
use App\Http\Controllers\Api\DataTables\HouseholdDataTable;
use App\Http\Requests\Admin\HouseholdRequest;
use App\Household;
use Auth;
class HouseholdController extends AdminController
{
/**
* Display a listing of the user... |
chore: Refactor Bukkit to MCPR conversion so that it is readable | const slugify = require('./slug.js')
const bukkitApi = require('./bukkitApi')
const convertModel = async bukkitPlugins => {
try {
const processPlugins = bukkitPlugins.map(async bukkitPlugin => {
const data = await Promise.all([
bukkitApi.getPlugin(bukkitPlugin.slug),
bukkitApi.getPluginFile... | const slugify = require('./slug.js')
const bukkitApi = require('./bukkitApi')
function convertModel (bukkit) {
return new Promise(function (resolve, reject) {
let plugins = []
let itemsProcessed = 0
for (let i = 0; i < bukkit.length; i++) {
;(() => {
let bukkitPlugin = bukkit[i]
ret... |
Remove a debug statement (1/0.) | from __future__ import print_function
import sys, os
from setuptools import setup, find_packages
with open('requirements.txt') as f:
INSTALL_REQUIRES = [l.strip() for l in f.readlines() if l]
try:
import numpy
except ImportError:
print('numpy is required during installation')
sys.exit(1)
try:
imp... | from __future__ import print_function
import sys, os
from setuptools import setup, find_packages
with open('requirements.txt') as f:
INSTALL_REQUIRES = [l.strip() for l in f.readlines() if l]
try:
import numpy
except ImportError:
print('numpy is required during installation')
sys.exit(1)
try:
imp... |
Print stack traces on failure | var RSVP = require('rsvp'),
utils = require('./lib')
fs = require('fs'),
GoogleSpreadsheet = require("google-spreadsheet"),
config = require('./config.js'),
doc = new GoogleSpreadsheet(config['google_spreadsheet_key']);
RSVP.hash({
currentItems: utils.getWishlistFromAmazon(config['amazon_w... | var RSVP = require('rsvp'),
utils = require('./lib')
fs = require('fs'),
GoogleSpreadsheet = require("google-spreadsheet"),
config = require('./config.js'),
doc = new GoogleSpreadsheet(config['google_spreadsheet_key']);
RSVP.hash({
currentItems: utils.getWishlistFromAmazon(config['amazon_w... |
FIX withholdings computation when payment come from invoices | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, fields
class Ac... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, fields
class Ac... |
Use Request instead of input comment out examples | <?php
namespace Kordy\Ticketit\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
class UserSearchController extends Controller {
public function userSearch(Request $request) {
$keyword = $request->get('q');
// If you wanted to search multiple Terms yo... | <?php
namespace Kordy\Ticketit\Controllers;
use App\Http\Controllers\Controller;
use Input;
use App\User;
class UserSearchController extends Controller {
public function userSearch() {
$keyword = Input::get('q');
// If you wanted to search multiple Terms you could do something like the followi... |
Fix bug with fan turning itself off
This would happen when the service was restarted. In the stopping code,
I added a call to clean up. | import logging
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.UART as UART
import serial
DYLOS_POWER_PIN = "P8_10"
LOGGER = logging.getLogger(__name__)
class Dylos:
def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5):
self.running = True
# Setup UART
UART.setup("UART1... | import logging
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.UART as UART
import serial
DYLOS_POWER_PIN = "P8_10"
LOGGER = logging.getLogger(__name__)
class Dylos:
def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5):
self.running = True
# Setup UART
UART.setup("UART1... |
Fix FF issues with doghouse.
Dog House loading for latest versions of FF, Chrome and even IE (likely works on safari too). Basically make it so that the popstate event is ignored on the first load of the page (which is what FF does)...that made all the other browsers fall in line. | require(
[
"domReady",
"rexster/history",
"rexster/template/template",
"rexster/ui/main-menu",
"order!has",
"order!has-detect-features"
],
function (domReady, history, template, mainMenu) {
domReady(function () {
// only make this feature ... | require(
[
"domReady",
"rexster/history",
"rexster/template/template",
"rexster/ui/main-menu",
"order!has",
"order!has-detect-features"
],
function (domReady, history, template, mainMenu) {
domReady(function () {
// only make this feature ... |
Drop unnecessary reference to popped elements to allow finalization through GC (XSTR-264). | package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
... | package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
... |
Add better commenting to floorMult filter. | /* Filter for finding the next-smallest multiple of input number */
angular.module('sknFloorMultFilter', []).filter('floorMult', function() {
return function(input, multSize) {
/* if input is already a multiple of multSize, return */
if(input % multSize === 0) {
return input;
}
... | /* Filter for finding the next-smallest multiple of input number */
angular.module('sknFloorMultFilter', []).filter('floorMult', function() {
return function(input, multSize) {
if(input % multSize === 0) {
return input;
}
else {
var inputFloor = Math.floor(input);
... |
Fix the `firstofas` template tag returning '' too early. | # -*- coding: utf-8 -*-
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, args, variable_name=None):
self.vars = args
self.variable_name =... | # -*- coding: utf-8 -*-
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, vars, variable_name=None):
self.vars = vars
self.variable_name =... |
Remove unused moment locales from webpack bundle | var path = require('path');
var fs = require('fs');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: path.join(__dirname, 'src/frontend/app'),
cache: true,
output: {
path: path.join(__dirname, '/public/'),
filename:... | var path = require('path');
var fs = require('fs');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: path.join(__dirname, 'src/frontend/app'),
cache: true,
output: {
path: path.join(__dirname, '/public/'),
filename: 'bundle.[hash].js'
},
mo... |
Add main app module first to js files that will be concatenated | (function() {
'use strict';
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('bundle', bundle);
gulp.task('start-webserver', startWebServer);
gulp.task('watch', watch);
gulp.task('default', ['bundle', 'start-webserver', 'watch']);
/////////////////////////
var js... | (function() {
'use strict';
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('bundle', bundle);
gulp.task('start-webserver', startWebServer);
gulp.task('watch', watch);
gulp.task('default', ['bundle', 'start-webserver', 'watch']);
/////////////////////////
var js... |
Fix lightbox on two col page. | <?php
/*
Template Name: 2 Spalten und Bilder
*/
?>
<div class="row">
<div class="medium-8 small-12 column">
<div class="white-bg vines">
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/page', 'header'); ?>
<ul class="large-block-grid-2 med... | <?php
/*
Template Name: 2 Spalten und Bilder
*/
?>
<div class="row">
<div class="medium-8 small-12 column">
<div class="white-bg vines">
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/page', 'header'); ?>
<ul class="large-block-grid-2 med... |
Use constants with "getRepository()" methods. | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\Slu... | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\Slu... |
Revert "Revert "update to remove client type hinting""
This reverts commit 4442314687fb05190a7dd6dfeb58ae4a6c4e87e9. | <?php
namespace hceudevs\RateLimitBundle\Service\Storage;
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;
class Redis implements StorageInterface
{
/**
* @var \Predis\Client
*/
protected $client;
public function __construct($client)
{
$this->client = $client;... | <?php
namespace hceudevs\RateLimitBundle\Service\Storage;
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;
class Redis implements StorageInterface
{
/**
* @var \Predis\Client
*/
protected $client;
public function __construct(Client $client)
{
$this->client = $... |
Make addon lookup external data same as YUIDoc tool
YUIDoc tool and the addon will both find "external.data" at the top-level
of yuidoc.json, but unfortunately the YUIDoc documentation says it's
support to go in "options". The tool will find it here, but this addon
won't. This fixes that and makes the lookup order the... | 'use strict';
var getVersion = require('git-repo-version');
var fs = require('fs');
var Y = require('yuidocjs');
module.exports = {
generate: function generateYuidocOptions(){
var config;
var exclusions = [
'.DS_Store',
'.git',
'node_modules',
'vendor',
'bow... | 'use strict';
var getVersion = require('git-repo-version');
var fs = require('fs');
var Y = require('yuidocjs');
module.exports = {
generate: function generateYuidocOptions(){
var config;
var exclusions = [
'.DS_Store',
'.git',
'node_modules',
'vendor',
'bow... |
Add basic test for read_file method | import unittest
import tempfile
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n... | import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n' + \
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.