text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add select part test for invalid column name | <?php
use Mdd\QueryBuilder\Queries\Parts;
class SelectPartBuilderTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider providerTestSelectViaConstructor
*/
public function testSelectViaConstructor($expected, $columns)
{
$select = new Parts\Select($columns);
$this->assertS... | <?php
use Mdd\QueryBuilder\Queries\Parts;
class SelectPartBuilderTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider providerTestSelectViaConstructor
*/
public function testSelectViaConstructor($expected, $columns)
{
$select = new Parts\Select($columns);
$this->assertS... |
Simplify loading of Quarkus CLI version | package io.quarkus.cli.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Properties;
import io.smallrye.common.classloader.ClassPathUtils;
import picocli.CommandLine;
public class QuarkusCliVersion implements CommandLine.IVersionProvide... | package io.quarkus.cli.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Properties;
import io.smallrye.common.classloader.ClassPathUtils;
import picocli.CommandLine;
public class QuarkusCliVersion implements CommandLine.IVersionProvide... |
Use justify-content-center on the manga list row.
Basically just centers the columns. | <div class="row">
<div class="col-12">
@if (isset($header))
<h3 class="text-center">
<b>{{ $header }}</b>
</h3>
@endif
</div>
</div>
<div class="row justify-content-center">
@if (isset($manga_list))
@foreach ($manga_list as $manga)
... | <div class="row">
<div class="col-12">
@if (isset($header))
<h3 class="text-center">
<b>{{ $header }}</b>
</h3>
@endif
</div>
</div>
<div class="row">
@if (isset($manga_list))
@foreach ($manga_list as $manga)
<div class="col-6 col-... |
Delete unnecessary vars attr of Proj | """proj.py: aospy.Proj class for organizing work in single project."""
import time
from .utils import dict_name_keys
class Proj(object):
"""Project parameters: models, regions, directories, etc."""
def __init__(self, name, vars={}, models={}, default_models={}, regions={},
direc_out='', nc_d... | """proj.py: aospy.Proj class for organizing work in single project."""
import time
from .utils import dict_name_keys
class Proj(object):
"""Project parameters: models, regions, directories, etc."""
def __init__(self, name, vars={}, models={}, default_models={}, regions={},
direc_out='', nc_d... |
Test requests don't have a charset attribute | import json
import functools
from django.conf import settings
from django.test import Client, TestCase
__all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase']
class JsonTestClient(Client):
def _json_request(self, method, url, data=None, *args, **kwargs):
method_func = getattr(super(JsonTestClient,... | import json
import functools
from django.conf import settings
from django.test import Client, TestCase
__all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase']
class JsonTestClient(Client):
def _json_request(self, method, url, data=None, *args, **kwargs):
method_func = getattr(super(JsonTestClient,... |
Fix test to reflect changes to welcome email | import time
from ..utils.log import log, INFO, ERROR, PASS
from ..utils.i_selenium import assert_tab, image_div
from ..tests import TestWithDependency
__all__ = ["welcome_email"]
#####
# Test : Welcome Email Recieved
#####
@TestWithDependency("WELCOME_EMAIL", ["SIGNUP"])
def welcome_email(driver, inbox, GUERRILLAMAI... | import time
from ..utils.log import log, INFO, ERROR, PASS
from ..utils.i_selenium import assert_tab, image_div
from ..tests import TestWithDependency
__all__ = ["welcome_email"]
#####
# Test : Welcome Email Recieved
#####
@TestWithDependency("WELCOME_EMAIL", ["SIGNUP"])
def welcome_email(driver, inbox, GUERRILLAMAI... |
Allow to disable events persistence at app class | from abc import abstractmethod, ABCMeta
from six import with_metaclass
from eventsourcing.infrastructure.event_store import EventStore
from eventsourcing.infrastructure.persistence_subscriber import PersistenceSubscriber
class EventSourcingApplication(with_metaclass(ABCMeta)):
persist_events = True
def __i... | from abc import abstractmethod, ABCMeta
from six import with_metaclass
from eventsourcing.infrastructure.event_store import EventStore
from eventsourcing.infrastructure.persistence_subscriber import PersistenceSubscriber
class EventSourcingApplication(with_metaclass(ABCMeta)):
def __init__(self, json_encoder_c... |
Use System.get instead of System.import
All of the modules we import should already be loaded, and we don't
want to ever attempt to import them anyway because we do not include a
Promise polyfill. | <!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ $title }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
<meta name="theme-c... | <!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ $title }}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
<meta name="theme-c... |
Remove printing of topics in bridge | import zmq
from argparse import ArgumentParser
from pymavlink import mavutil
def main():
parser = ArgumentParser()
parser.add_argument("--device", help="MAVLink device to add to zmq", required=True)
parser.add_argument("--zmq", help="zmq url", required=True)
args = parser.parse_args()
try:
... | import zmq
from argparse import ArgumentParser
from pymavlink import mavutil
def main():
parser = ArgumentParser()
parser.add_argument("--device", help="MAVLink device to add to zmq", required=True)
parser.add_argument("--zmq", help="zmq url", required=True)
args = parser.parse_args()
try:
... |
Fix message escaping to be the same as in the init script
This adjustment is done to have the same character escaping as in the PR provided by the TeamCity folks from JetBrains, assuming their encoding code is correct and not the one that was previously used by this plugin. | package nu.studer.teamcity.buildscan.agent.servicemessage;
final class ServiceMessage {
private static final String SERVICE_MESSAGE_START = "##teamcity[";
private static final String SERVICE_MESSAGE_END = "]";
private final String name;
private final String argument;
private ServiceMessage(Strin... | package nu.studer.teamcity.buildscan.agent.servicemessage;
final class ServiceMessage {
private static final String SERVICE_MESSAGE_START = "##teamcity[";
private static final String SERVICE_MESSAGE_END = "]";
private final String name;
private final String argument;
private ServiceMessage(Strin... |
Make sure the package is exported by distutils | from distutils.core import setup, Extension
import numpy.distutils.misc_util
module = Extension(
'cnaturalneighbor',
include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(),
library_dirs=['/usr/local/lib'],
extra_compile_args=['--std=c++11'],
sources=[
'naturalneighbor/cnaturalnei... | from distutils.core import setup, Extension
import numpy.distutils.misc_util
module = Extension(
'cnaturalneighbor',
include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(),
library_dirs=['/usr/local/lib'],
extra_compile_args=['--std=c++11'],
sources=[
'naturalneighbor/cnaturalnei... |
Fix existing auto join specification tests. | <?php
namespace spec\RulerZ\Executor\DoctrineQueryBuilder;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Join;
use PhpSpec\ObjectBehavior;
use RulerZ\Executor\DoctrineQueryBuilder\AutoJoin;
class AutoJoinSpec extends ObjectBehavior
{
function let(QueryBuilder $target)
{
$this->beConstru... | <?php
namespace spec\RulerZ\Executor\DoctrineQueryBuilder;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Join;
use PhpSpec\ObjectBehavior;
use RulerZ\Executor\DoctrineQueryBuilder\AutoJoin;
class AutoJoinSpec extends ObjectBehavior
{
function let(QueryBuilder $target)
{
$this->beConstru... |
Remove the icon from the title bar on macOS | const {remote} = require('electron');
const Titlebar = React.createClass({
render: function () {
const w = {
min: () => {
const win = remote.getCurrentWindow()
win.minimize()
},
max: () => {
const win = remote.getCurrentWindow()
if (!win.i... | const {remote} = require('electron');
const Titlebar = React.createClass({
render: function () {
const w = {
min: () => {
const win = remote.getCurrentWindow()
win.minimize()
},
max: () => {
const win = remote.getCurrentWindow()
if (!win.i... |
Add TODO task to security configuration. | package by.triumgroup.recourse.configuration.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import ... | package by.triumgroup.recourse.configuration.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import ... |
Add back the xstyle and dojox svg modules correctly | // saves some loading time by loading most of the commonly-used
// JBrowse modules at the outset
require([
'JBrowse/Browser',
'JBrowse/ConfigAdaptor/JB_json_v1',
// default tracklist view
'JBrowse/View/TrackList/Hierarchical',
// common stores
'J... | // saves some loading time by loading most of the commonly-used
// JBrowse modules at the outset
require([
'JBrowse/Browser',
'JBrowse/ConfigAdaptor/JB_json_v1',
// default tracklist view
'JBrowse/View/TrackList/Hierarchical',
// common stores
'J... |
Add TODO about using an enum instead of an unconstrained string | package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
// TODO: This o... | package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
private String ... |
Add quick return if no trait entry ids are provided | <?php
namespace AppBundle\API\Details;
use AppBundle\Entity\Data\TraitCategoricalEntry;
use AppBundle\Entity\Data\TraitNumericalEntry;
use AppBundle\Service\DBVersion;
/**
* Web Service.
* Returns Trait Entry information
*/
class TraitEntries
{
private $manager;
private $known_trait_formats;
const ERR... | <?php
namespace AppBundle\API\Details;
use AppBundle\Entity\Data\TraitCategoricalEntry;
use AppBundle\Entity\Data\TraitNumericalEntry;
use AppBundle\Service\DBVersion;
/**
* Web Service.
* Returns Trait Entry information
*/
class TraitEntries
{
private $manager;
private $known_trait_formats;
const ERR... |
Remove whitespace, and also add JSON url | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/json/$',
views.CalendarJSONView.as_view(),
name='swingtime-calendar-json'... | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/(?P<year>\d{4})/$',
views.year_view,
name='swingtime-yearly-view'
... |
Revert "Fix bug in strategy"
This reverts commit 706d13192eff33a3c71d5279e50a2830fc9d6568.
Conflicts:
src/Engine/Strategy.java | package Engine;
import java.util.HashMap;
public class Strategy {
HashMap<String, Double> hotnessMap;
// bettingFunction is an array of length 5;
<<<<<<< HEAD
<<<<<<< HEAD
public Strategy() {
hotnessMap = new HashMap<String, Double>();
for (int i = 1; i < 14; i++) {
if (i ==... | package Engine;
import java.util.HashMap;
public class Strategy {
HashMap<String, Double> hotnessMap;
// bettingFunction is an array of length 5;
<<<<<<< HEAD
public Strategy() {
hotnessMap = new HashMap<String, Double>();
for (int i = 1; i < 14; i++) {
if (i == 1)
... |
Support custom initializer in links.CRF1d | from chainer.functions.loss import crf1d
from chainer import link
from chainer import variable
class CRF1d(link.Link):
"""Linear-chain conditional random field loss layer.
This link wraps the :func:`~chainer.functions.crf1d` function.
It holds a transition cost matrix as a parameter.
Args:
... | from chainer.functions.loss import crf1d
from chainer import link
from chainer import variable
class CRF1d(link.Link):
"""Linear-chain conditional random field loss layer.
This link wraps the :func:`~chainer.functions.crf1d` function.
It holds a transition cost matrix as a parameter.
Args:
... |
Check for null exception on getSearchQuery | // Backbone.Collection.search-ajax v0.2
// by Joe Vu - joe.vu@homeslicesolutions.com
// For all details and documentation:
// https://github.com/homeslicesolutions/backbone-collection-search
!function(_, Backbone){
// Extending out
_.extend(Backbone.Collection.prototype, {
//@ Search for AJ... | // Backbone.Collection.search-ajax v0.2
// by Joe Vu - joe.vu@homeslicesolutions.com
// For all details and documentation:
// https://github.com/homeslicesolutions/backbone-collection-search
!function(_, Backbone){
// Extending out
_.extend(Backbone.Collection.prototype, {
//@ Search for AJ... |
Update token renewal due to demo.scitokens.org API update | #!/usr/bin/python3
import os
import json
import time
from urllib import request
# Request payload
payload = {"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
# Convert the format from... | #!/usr/bin/python3
import os
import json
import time
from urllib import request
# Create the requested json
demo_json = {
"payload": {
"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
}
# Co... |
Make sure not to find the same error twice when comparing errors | const _ = require('lodash');
const chai = require('chai');
chai.use(function(_chai, utils) {
utils.addChainableMethod(chai.Assertion.prototype, 'haveErrors', function(...expectedErrors) {
const obj = utils.flag(this, 'object');
const actualErrors = obj.errors;
new chai.Assertion(actualErrors).to.be.an(... | const _ = require('lodash');
const chai = require('chai');
chai.use(function(_chai, utils) {
utils.addChainableMethod(chai.Assertion.prototype, 'haveErrors', function(...expectedErrors) {
const obj = utils.flag(this, 'object');
const actualErrors = obj.errors;
new chai.Assertion(actualErrors).to.be.an(... |
Fix nullPointerException on "edit" command | package seedu.task.model.task;
import seedu.task.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class TaskName {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task na... | package seedu.task.model.task;
import seedu.task.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class TaskName {
public static final String MESSAGE_NAME_CONSTRAINTS = "Task na... |
Use === to test true | "use strict";
var React = require("react"),
request = require("superagent");
module.exports = React.createClass({
componentDidMount: function() {
request
.get("/api/ping/" + this.props.boardIp)
.end(function(err, res) {
if (err) {
console.log... | "use strict";
var React = require("react"),
request = require("superagent");
module.exports = React.createClass({
componentDidMount: function() {
request
.get("/api/ping/" + this.props.boardIp)
.end(function(err, res) {
if (err) {
console.log... |
Modify commit count str format | import datetime
from github import Github
from slack.slackbot import SlackerAdapter
from utils.config import Config
from utils.resource import MessageResource
class GithubManager(object):
def __init__(self):
self.config = Config().github
self.username = self.config["USERNAME"]
password =... | import datetime
from github import Github
from slack.slackbot import SlackerAdapter
from utils.config import Config
from utils.resource import MessageResource
class GithubManager(object):
def __init__(self):
self.config = Config().github
self.username = self.config["USERNAME"]
password =... |
[showcase] Support ES7 in live example | /* globals babel */
// Dependencies
const {types} = Focus.component;
const LivePreview = React.createClass({
displayName: 'LivePreview',
propTypes: {
code: types('string'),
style: types('object')
},
style: {
title: {
margin: '15px',
color: '#372B3F'
... | /* globals babel */
// Dependencies
const {types} = Focus.component;
const LivePreview = React.createClass({
displayName: 'LivePreview',
propTypes: {
code: types('string'),
style: types('object')
},
style: {
title: {
margin: '15px',
color: '#372B3F'
... |
Add update method, remove getters..
This makes the osmNote work a bit more like other osm objects in iD.
- When working with the osm objects, we'll treat them as immutable.
So all modifications will be through the update method:
e.g. can do this in a repl, like chrome devtools console:
> n = iD.osmNote()
osm... | import _extend from 'lodash-es/extend';
import { geoExtent } from '../geo';
export function osmNote() {
if (!(this instanceof osmNote)) {
return (new osmNote()).initialize(arguments);
} else if (arguments.length) {
this.initialize(arguments);
}
}
osmNote.id = function() {
return osm... | import _extend from 'lodash-es/extend';
import { geoExtent } from '../geo';
export function osmNote() {
if (!(this instanceof osmNote)) {
return (new osmNote()).initialize(arguments);
} else if (arguments.length) {
this.initialize(arguments);
}
}
osmNote.id = function() {
return osm... |
Add cassette and failed request as properties of thrown CannotOverwriteCassetteException | class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
self.cassette = kwargs["cassette"]
self.failed_request = kwargs["failed_request"]
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCas... | class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCassetteException, self).__init__(message)
def _get_message(self, cassette, failed_request):
... |
Mark pre-selected topics on form |
from django.db import transaction
from django.shortcuts import render, redirect
from preferences.views import _mark_selected
from bills.utils import get_all_subjects, get_all_locations
from opencivicdata.models import Bill
def bill_list(request):
subjects = get_all_subjects()
if request.POST.getlist('bill... |
from django.shortcuts import render, redirect
from bills.utils import get_all_subjects, get_all_locations
from opencivicdata.models import Bill
def bill_list(request):
subjects = get_all_subjects()
if request.POST.getlist('bill_subjects'):
filter_subjects = request.POST.getlist('bill_subjects')
... |
Remove double binding in custom view example. | package com.example.zipper.customview;
import com.example.zipper.R;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import se.snylt.zipper.annotations.BindToView;... | package com.example.zipper.customview;
import com.example.zipper.R;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import se.snylt.zipper.annotations.BindToView;... |
Fix indentation in the text-fill directive. | /*global angular*/
(function () {
'use strict';
// min-font-size attribute = minimum font size in pixels
// max-font-size attribute = maximum font size in pixels
// Directive must be used on the parent of an element with the .text-fill class
angular.module('core').directive('textFill', ["$timeout",... | /*global angular*/
(function () {
'use strict';
// min-font-size attribute = minimum font size in pixels
// max-font-size attribute = maximum font size in pixels
// Directive must be used on the parent of an element with the .text-fill class
angular.module('core').directive('textFill', ["$timeout",... |
Allow more discourse hostnames to fix CSP error | csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\''
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net',... | csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\''
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net',... |
Fix templates and add newlines | export function CORDOVA_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<${assetType} src="${src}" platform="${platform}"${d?` density="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}"`:``} />`;
}
export function PGBUILD_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<... | export function CORDOVA_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<${assetType} src="${src}" platform="${platform}"${d?` density="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}`:``}" />`;
}
export function PGBUILD_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) {
return `<... |
Remove Java 8 string join method | package org.commonmark.ext.heading.anchor.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.commonmark.html.AttributeProvider;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.Code;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
i... | package org.commonmark.ext.heading.anchor.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.commonmark.html.AttributeProvider;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.Code;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
i... |
Use collections instead of models for tags | "use strict";
define(['jquery',
'underscore',
'backbone',
'jquery.tagsinput'
], function ($, _, Backbone, TagsInput) {
var Recipe = Backbone.Model.extend({
urlRoot: '/',
defaults: {
ingredients: [],
method: ''
}
});
var Recipes = Back... | "use strict";
define(['jquery',
'underscore',
'backbone',
'jquery.tagsinput'
], function ($, _, Backbone, TagsInput) {
var Recipe = Backbone.Model.extend({
urlRoot: '/',
defaults: {
ingredients: [],
method: ''
}
});
var Recipes = Back... |
test: Use generator for IAM template names
See also: #208 | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TE... | """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def test_all_iam_templates():
"""Verify all IAM templates render as proper JSON."""
jinjaenv = jinja2.Environment(loader=jinja2.F... |
Add in new Kazuto Kirigia spam | import BaseWatcher from './BaseWatcher';
import config from '../config';
/**
* This checks for people spamming text stuff.
*/
class TextSpamWatcher extends BaseWatcher {
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string[]}
*/
method = [
... | import BaseWatcher from './BaseWatcher';
import config from '../config';
/**
* This checks for people spamming text stuff.
*/
class TextSpamWatcher extends BaseWatcher {
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string[]}
*/
method = [
... |
Change namespace image app, use opps image | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Article
from opps.image.models import Image
from opps.core.models import Source
class Post(Article):
images = models.ManyToManyField(Image, null=True, blank=True,
... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Article
from opps.core.models.image import Image
from opps.core.models import Source
class Post(Article):
images = models.ManyToManyField(Image, null=True, blank=True,
... |
Clean up ACL code for axo 20483 | <?php
namespace Rcm\Api\Acl;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Rcm\Acl\AclActions;
use Rcm\Acl\AssertIsAllowed;
use Rcm\Acl\NotAllowedException;
use Rcm\Acl\ResourceName;
use Rcm\Acl2\SecurityPropertyConstants;
use Rcm\Api\GetPsrRequest;
use Rcm\Entity\Site;
use Rc... | <?php
namespace Rcm\Api\Acl;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Rcm\Acl\AclActions;
use Rcm\Acl\AssertIsAllowed;
use Rcm\Acl\NotAllowedException;
use Rcm\Acl\ResourceName;
use Rcm\Acl2\SecurityPropertyConstants;
use Rcm\Api\GetPsrRequest;
use Rcm\Entity\Site;
use Rc... |
Remove extension of webservice class and update parameters of execute function | <?php
namespace AppBundle\API\Listing;
use AppBundle\API\Webservice;
use AppBundle\Entity\WebuserData;
use AppBundle\Entity\FennecUser;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\ParameterBag;
/**
* Web Service.
* Returns information of all users projects
*/
class Projects
{
... | <?php
namespace AppBundle\API\Listing;
use AppBundle\API\Webservice;
use AppBundle\Entity\WebuserData;
use AppBundle\Entity\FennecUser;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\ParameterBag;
/**
* Web Service.
* Returns information of all users projects
*/
class Projects ex... |
Move emmity config to upper level | import gulp from "gulp";
import plumber from "gulp-plumber";
import pug from "gulp-pug";
import posthtml from "gulp-posthtml";
import prettify from "gulp-prettify";
import gulpIf from "gulp-if";
import { setup as emittySetup } from "emitty";
import getJsonData from "../util/getJsonData";
import { plumberConfig, postht... | import gulp from "gulp";
import plumber from "gulp-plumber";
import pug from "gulp-pug";
import posthtml from "gulp-posthtml";
import prettify from "gulp-prettify";
import gulpIf from "gulp-if";
import { setup as emittySetup } from "emitty";
import getJsonData from "../util/getJsonData";
import { plumberConfig, postht... |
Move unit tests data in setUp
When unit testing the various methods of cat2cohort,
we need some example data (input and expected output).
It makes sense to share it among testing methods through
the setUp method mechanism. | """Unit tests for cat2cohort."""
import unittest
from wm_metrics.cat2cohort import api_url, _make_CSV_line, _userlist_to_CSV_cohort
class TestCat2Cohort(unittest.TestCase):
"""Test methods from Cat2Cohort."""
def setUp(self):
"""Set up the tests."""
self.userlist = [('Toto', 'fr'), ('Titi',... | """Unit tests for cat2cohort."""
import unittest
from wm_metrics.cat2cohort import api_url, _make_CSV_line, _userlist_to_CSV_cohort
class TestCat2Cohort(unittest.TestCase):
"""Test methods from Cat2Cohort."""
def test_api_url(self):
"""Test api_url."""
values = [
('fr', 'https:/... |
Remove console.debug from jshint spec | // Thanks to Brandon Keepers -
describe('JSHint', function () {
var options = {curly: true, white: false, indent: 2},
files = /^\/public\/javascripts\/(models|collections|views)|.*spec\.js$/;
function get(path) {
path = path + "?" + new Date().getTime();
var xhr;
try {
xhr = new jasmine.X... | // Thanks to Brandon Keepers -
describe('JSHint', function () {
var options = {curly: true, white: false, indent: 2},
files = /^\/public\/javascripts\/(models|collections|views)|.*spec\.js$/;
function get(path) {
path = path + "?" + new Date().getTime();
var xhr;
try {
xhr = new jasmine.X... |
Make sure client gets update after a refresh | var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
app.use(express.static(__dirname + '/'));
var server = http.createServer(app);
server.listen(port);
console.log('http server listening on %d', port);
var ma... | var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
app.use(express.static(__dirname + '/'));
var server = http.createServer(app);
server.listen(port);
console.log('http server listening on %d', port);
var ma... |
Fix getMatchAllQuery to return according to pageNumber | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates, streaming) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
var _source = !streaming ? `${fieldName}` : null;
return ({
type... | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates, streaming) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
var _source = !streaming ? `${fieldName}` : null;
return ({
type... |
BAP-9269: Fix unit tests after doctrine/cache package was update | <?php
namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Mapping;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Mapping\ClassMetadata;
use Oro\Bundle\EntityExtendBundle\Mapping\ExtendClassMetadataFactory;
class ExtendClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ExtendC... | <?php
namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Mapping;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Mapping\ClassMetadata;
use Oro\Bundle\EntityExtendBundle\Mapping\ExtendClassMetadataFactory;
class ExtendClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ExtendC... |
REFACTOR : Changed the name of step name from 'name' to 'step_name' to avoid clashing with a potential use of the word 'name' in kwargs. | from hitchdoc.database import Database
from hitchdoc import exceptions
import pickle
import base64
class Recorder(object):
def __init__(self, story, sqlite_filename):
self._story = story
self._db = Database(sqlite_filename)
if self._db.Recording.filter(name=story.name).first() is not None... | from hitchdoc.database import Database
from hitchdoc import exceptions
import pickle
import base64
class Recorder(object):
def __init__(self, story, sqlite_filename):
self._story = story
self._db = Database(sqlite_filename)
if self._db.Recording.filter(name=story.name).first() is not None... |
Fix broken content rendered by PhJS | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escap... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escap... |
Remove unused argument to internal destroyInstance | import { select, local } from "d3-selection";
var instanceLocal = local(),
noop = function (){};
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
createInstance = function (){
var instance = instanceLocal.set(this, {
selection: se... | import { select, local } from "d3-selection";
var instanceLocal = local(),
noop = function (){};
export default function (tagName, className){
var create = noop,
render = noop,
destroy = noop,
createInstance = function (){
var instance = instanceLocal.set(this, {
selection: se... |
Sort by name, fix vacancy (values in api are occupancy) | from irc3.plugins.command import command
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
from irc3 import asyncio
import aiohttp
import xml.etree.ElementTree as ET
@command(permission="view")
@asyncio.coroutine
def parking(bot, mask, target, args):
"""Show the current parking lot status
%%parking
... | from irc3.plugins.command import command
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
from irc3 import asyncio
import aiohttp
import xml.etree.ElementTree as ET
@command(permission="view")
@asyncio.coroutine
def parking(bot, mask, target, args):
"""Show the current parking lot status
%%parking
... |
Update RandomSampler to use the new Sampler abc | """
RandomSampler
-------------
A random sampler that can be used for unit testing and debugging.
"""
import numpy as np
from dimod.core.sampler import Sampler
from dimod.response import Response, SampleView
__all__ = ['RandomSampler']
class RandomSampler(Sampler):
"""Gives random samples.
Note that this ... | """
RandomSampler
-------------
A random sampler that can be used for unit testing and debugging.
"""
import numpy as np
from dimod.core.sampler import Sampler
from dimod.response import Response, SampleView
__all__ = ['RandomSampler']
class RandomSampler(Sampler):
"""Gives random samples.
Note that this ... |
Use creation date of mining activity, not update date. | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MiningActivity;
use App\Payment;
use Illuminate\Support\Facades\DB;
class ReportsController extends Controller
{
/**
* Default report view. Show a table of dates with amount mined per day.
*/
public function main()
{
... | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MiningActivity;
use App\Payment;
use Illuminate\Support\Facades\DB;
class ReportsController extends Controller
{
/**
* Default report view. Show a table of dates with amount mined per day.
*/
public function main()
{
... |
Revert "rollback change after [byte_sequence -> byteSeq]" | import { generateGame } from "./";
import PlayerModel from "../../model/player_model";
describe(`generator:: Game`, () => {
describe(`::generate`, () => {
[0, 1, 2, 10].forEach((v) => {
it(`expected ${v} battlefields`, () => {
const model = generateGame(v, 0);
e... | import { generateGame } from "./";
import PlayerModel from "../../model/player_model";
describe(`generator:: Game`, () => {
describe(`::generate`, () => {
[0, 1, 2, 10].forEach((v) => {
it(`expected ${v} battlefields`, () => {
const model = generateGame(v, 0);
e... |
Check SHAP Model call type | import numpy as np
from .._serializable import Serializable, Serializer, Deserializer
from torch import Tensor
class Model(Serializable):
""" This is the superclass of all models.
"""
def __init__(self, model=None):
""" Wrap a callable model as a SHAP Model object.
"""
if isinstan... | import numpy as np
from .._serializable import Serializable, Serializer, Deserializer
class Model(Serializable):
""" This is the superclass of all models.
"""
def __init__(self, model=None):
""" Wrap a callable model as a SHAP Model object.
"""
if isinstance(model, Model):
... |
CUDA: Reorder FloatModel checks in ascending order | from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, f... | from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, f... |
Remove static var from side effect | import React, { Component } from 'react'
import { getDisplayName } from './utils'
const canUseDOM = typeof window !== 'undefined'
export default function withSideEffect (reduceComponentsToState, handleStateChangeOnClient) {
return function wrap (WrappedComponent) {
let mountedInstances = []
let state
f... | import React, { Component } from 'react'
import { getDisplayName } from './utils'
export default function withSideEffect (reduceComponentsToState, handleStateChangeOnClient) {
return function wrap (WrappedComponent) {
let mountedInstances = []
let state
function emitChange (component) {
state = re... |
Add in a way to specify the utmp file path for unit testing | # coding=utf-8
"""
Collects the number of users logged in and shells per user
#### Dependencies
* [pyutmp](http://software.clapper.org/pyutmp/)
"""
import diamond.collector
from pyutmp import UtmpFile
class UsersCollector(diamond.collector.Collector):
def get_default_config_help(self):
"""
... | # coding=utf-8
"""
Collects the number of users logged in and shells per user
#### Dependencies
* [pyutmp](http://software.clapper.org/pyutmp/)
"""
import diamond.collector
from pyutmp import UtmpFile
class UsersCollector(diamond.collector.Collector):
def get_default_config_help(self):
"""
... |
Fix ComponentBuilder order in registry | /*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.plugin.idea.ui.component;
import org.jboss.forge.addon.ui.input.InputComponent;
/**
* A factory for {@link Compo... | /*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.plugin.idea.ui.component;
import org.jboss.forge.addon.ui.input.InputComponent;
/**
* A factory for {@link Compo... |
Add get dice roll function | import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = random.randint(1, self.sides)
... | import random
class Die(object):
def __init__(self, sides = 6):
self.sides = sides
self.held = False
self.die_face = 1
def change_held(self, held):
self.held = held
def roll_die(self):
if (self.held == False):
self.die_face = random.randint(1, self.sides)
... |
Exclude more unneeded files from default plan
This patch exludes more file types from the tarball uploaded to swift as
the default deployment plan.
Change-Id: I8b6d8de8d7662604cdb871fa6a4fb872c7937e25
Closes-Bug: #1613286 | # Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | # Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
Include minified file in grunt bump-commit | module.exports = function (grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'./src/paginate-anything.js', '*.json', './test/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
karma: {
travis: {
conf... | module.exports = function (grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'./src/paginate-anything.js', '*.json', './test/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
karma: {
travis: {
conf... |
Increase theme zip file upload limit to 10MB | <?php
declare(strict_types=1);
/*
* This file is part of the Superdesk Web Publisher Core Bundle.
*
* Copyright 2017 Sourcefabric z.ú. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code.
*
* @copyright 2017 Sourcef... | <?php
declare(strict_types=1);
/*
* This file is part of the Superdesk Web Publisher Core Bundle.
*
* Copyright 2017 Sourcefabric z.ú. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code.
*
* @copyright 2017 Sourcef... |
Allow to overwrite the pipeline processor return value | import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
rais... | import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
rais... |
Remove double slashes in the Redis commands urls | #!/usr/bin/python
# -*- coding: utf-8 -*-
import lxml.etree, lxml.html
import re
url = "http://redis.io"
output = "output.txt"
f = open(output, "w");
tree = lxml.html.parse("download/raw.dat").getroot()
commands = tree.find_class("command")
data = {}
for command in commands:
for row in command.findall('a'):
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import lxml.etree, lxml.html
import re
url = "http://redis.io"
output = "output.txt"
f = open(output, "w");
tree = lxml.html.parse("download/raw.dat").getroot()
commands = tree.find_class("command")
data = {}
for command in commands:
for row in command.findall('a'):
... |
Move health check route first, otherwise it gets shadowed | <?php
// Health check
$app->get('/health', function() {
return 'OK';
});
// Shows the dashboard, if enabled
$app->get('/', [
'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
'uses' => 'DashboardController@dashboard',
]);
// Shows the upload page,... | <?php
// Shows the dashboard, if enabled
$app->get('/', [
'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
'uses' => 'DashboardController@dashboard',
]);
// Shows the upload page, if enabled
$app->get('/upload', [
'middleware' => \Nord\ImageManipu... |
Use correct method name. [rev: matthew.gordon2] | /**
* @module js-utils/js/repeater
*/
define([
'underscore'
], function () {
/**
* @name module:js-utils/js/repeater.Repeater
* @desc Wrapper around setTimeout that allows for the control of the timeout
* @param {function} f The function to be called
* @param {number} interval The number o... | /**
* @module js-utils/js/repeater
*/
define([
'underscore'
], function () {
/**
* @name module:js-utils/js/repeater.Repeater
* @desc Wrapper around setTimeout that allows for the control of the timeout
* @param {function} f The function to be called
* @param {number} interval The number o... |
Fix leave that returns callback. | var slice = [].slice
function Vestibule () {
this._waiting = []
this.occupied = false
this.open = null
}
Vestibule.prototype.enter = function (timeout, callback) {
if (callback == null) {
callback = timeout
timeout = null
}
if (this.open == null) {
if (timeout != null) ... | var slice = [].slice
function Vestibule () {
this._waiting = []
this.occupied = false
this.open = null
}
Vestibule.prototype.enter = function (timeout, callback) {
if (callback == null) {
callback = timeout
timeout = null
}
if (this.open == null) {
if (timeout != null) ... |
Add encoding to README read | import os
from pathlib import Path
from setuptools import Extension, find_packages, setup
PROJECT_ROOT = Path(__file__).parent
long_description = (PROJECT_ROOT / "README.md").read_text(encoding="utf8")
setup(
name="pyinstrument",
packages=find_packages(include=["pyinstrument", "pyinstrument.*"]),
version... | import os
from setuptools import Extension, find_packages, setup
with open(os.path.join(os.path.dirname(__file__), "README.md")) as f:
long_description = f.read()
setup(
name="pyinstrument",
packages=find_packages(include=["pyinstrument", "pyinstrument.*"]),
version="4.1.1",
ext_modules=[
... |
Disable antialias for GL drawing lines | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas... |
Add a <reviewer, revision> key to the reviewers table
Summary:
Ref T10967. I'm not 100% sure we need this, but the old edge table had it and I recall an issue long ago where not having this key left us with a bad query plan.
Our data doesn't really provide a way to test this key (we have many revisions and few review... | <?php
final class DifferentialReviewer
extends DifferentialDAO {
protected $revisionPHID;
protected $reviewerPHID;
protected $reviewerStatus;
protected $lastActionDiffPHID;
protected $lastCommentDiffPHID;
private $authority = array();
protected function getConfiguration() {
return array(
s... | <?php
final class DifferentialReviewer
extends DifferentialDAO {
protected $revisionPHID;
protected $reviewerPHID;
protected $reviewerStatus;
protected $lastActionDiffPHID;
protected $lastCommentDiffPHID;
private $authority = array();
protected function getConfiguration() {
return array(
s... |
Include tiles in menu response | /*global FormplayerFrontend, Util */
FormplayerFrontend.module("Menus.Collections", function (Collections, FormplayerFrontend, Backbone, Marionette, $) {
Collections.MenuSelect = Backbone.Collection.extend({
model: FormplayerFrontend.Menus.Models.MenuSelect,
commonProperties: [
'titl... | /*global FormplayerFrontend, Util */
FormplayerFrontend.module("Menus.Collections", function (Collections, FormplayerFrontend, Backbone, Marionette, $) {
Collections.MenuSelect = Backbone.Collection.extend({
model: FormplayerFrontend.Menus.Models.MenuSelect,
commonProperties: [
'titl... |
Use Pager.Item instead of PageItem. | import React from 'react';
import PropTypes from 'prop-types';
import {Pager} from 'react-bootstrap';
const Paging = ({pending, paging, onSelect}) => {
let newer, older;
if (!paging) {
return null;
}
if (paging.before !== undefined) {
newer = (
<Pager.Item previous disabl... | import React from 'react';
import PropTypes from 'prop-types';
import {Pager} from 'react-bootstrap';
const Paging = ({pending, paging, onSelect}) => {
let newer, older;
if (!paging) {
return null;
}
if (paging.before !== undefined) {
newer = (
<PageItem previous disabled... |
Fix syntax for python 2.6 | from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in ["Linux", "Darwin"], "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
ll... | from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
ll... |
Set up console script for main | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "{{cookiecutter.repo_name}}",
version = "{{cookiecutter.version}}",
author = "{{cookiecutter.full_name}}",
author_email = "{{cookiecutter.email}}"... | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "{{cookiecutter.repo_name}}",
version = "{{cookiecutter.version}}",
author = "{{cookiecutter.full_name}}",
author_email = "{{cookiecutter.email}}"... |
Update registrar to dynamically fetch registered `_User` subclass | <?php
namespace LaraParse\Auth;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use LaraParse\Subclasses\User;
use Parse\ParseObject;
class Registrar implements RegistrarContract
{
/**
* @var \Illuminate\Contracts\Validation\Fac... | <?php
namespace LaraParse\Auth;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Support\MessageBag;
use LaraParse\Subclasses\User;
use Parse\ParseException;
class Registrar implements RegistrarContract
{
/**
* @va... |
Drop threads down to limit memory consumption | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
from gratipay.utils import markdown
from gratipay.utils.threaded_map import threaded_map
from threading import Lock
log_lock = Lock()
def log(*a, **kw):
with log_lock:
print(*a, file=sys.stder... | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
from gratipay.utils import markdown
from gratipay.utils.threaded_map import threaded_map
from threading import Lock
log_lock = Lock()
def log(*a, **kw):
with log_lock:
print(*a, file=sys.stder... |
Move export to a background process | from itertools import chain
from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader
from corehq.apps.reports.generic import GenericTabularReport
from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin
class MultiTabularReport(DatespanMixin, CustomProjectReport, GenericTabula... | from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader
from corehq.apps.reports.generic import GenericTabularReport
from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin
class MultiTabularReport(DatespanMixin, CustomProjectReport, GenericTabularReport):
report_template... |
Add custom success and faluire messages | /*
* grunt-perl-tidy
* https://github.com/rabrooks/grunt-perl-tidy
*
* Copyright (c) 2014 Aaron Brooks
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tas... | /*
* grunt-perl-tidy
* https://github.com/rabrooks/grunt-perl-tidy
*
* Copyright (c) 2014 Aaron Brooks
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tas... |
Add is_active() method to the Baro class | from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation'... | from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation'... |
Check if the remote_repo was updated or not and log error | import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relations... | import json
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
class Command(BaseCommand):
help = "Load Project and RemoteRepository Relationship from JSON file"
def add_arguments(self, parser):
# File path of the json file containing relations... |
Use a name param instead of a boolean value | 'use strict';
var Node = require('../node');
var debug = require('../../util/debug')('analysis:line-to-single-point');
var TYPE = 'line-to-single-point';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.POINT),
destination_longitude: Node.PARAM.NUMBER(),
destination_latitude: Node.PARAM.NUMBER(),
};
... | 'use strict';
var Node = require('../node');
var debug = require('../../util/debug')('analysis:line-to-single-point');
var TYPE = 'line-to-single-point';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.POINT),
destination_longitude: Node.PARAM.NUMBER(),
destination_latitude: Node.PARAM.NUMBER(),
};
... |
Set a unique id to each Trackable Brand | package cgeo.geocaching.connector.trackable;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import org.eclipse.jdt.annotation.NonNull;
public enum TrackableBrand {
TRAVELBUG(1, R.drawable.trackable_travelbug, R.string.trackable_travelbug),
GEOKRETY(2, R.drawable.trackable_geokrety, R.strin... | package cgeo.geocaching.connector.trackable;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import org.eclipse.jdt.annotation.NonNull;
public enum TrackableBrand {
TRAVELBUG(1, R.drawable.trackable_travelbug, R.string.trackable_travelbug),
GEOKRETY(2, R.drawable.trackable_geokrety, R.strin... |
Use encodeURIComponent() on selected text variable; move result url to variable. | var { Hotkey } = require("sdk/hotkeys");
var { ActionButton } = require("sdk/ui/button/action");
var Request = require("sdk/request").Request;
var tabs = require("sdk/tabs");
var selection = require("sdk/selection");
var notifications = require("sdk/notifications");
var notifyImg = "./icon-32-white.png";
var apiKey = ... | var { Hotkey } = require("sdk/hotkeys");
var { ActionButton } = require("sdk/ui/button/action");
var Request = require("sdk/request").Request;
var tabs = require("sdk/tabs");
var selection = require("sdk/selection");
var notifications = require("sdk/notifications");
var notifyImg = "./icon-32-white.png";
var apiKey = ... |
Address review comment: More standard assertions. | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Test validation of keys generated by flocker-ca.
"""
from twisted.trial.unittest import SynchronousTestCase
from .. import amp_server_context_factory, rest_api_context_factory
from ..testtools import get_credential_sets
class ClientValidationContextFact... | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Test validation of keys generated by flocker-ca.
"""
from twisted.trial.unittest import SynchronousTestCase
from .. import amp_server_context_factory, rest_api_context_factory
from ..testtools import get_credential_sets
class ClientValidationContextFact... |
Check is object to avoid error on search express entities | <?php
namespace Concrete\Core\Express\Search\Column;
use Concrete\Core\Entity\Express\Association;
use Concrete\Core\Search\Column\Column;
use Concrete\Core\Search\Result\Result;
class AssociationColumn extends Column
{
protected $association = false;
protected $associationID;
public function __construct... | <?php
namespace Concrete\Core\Express\Search\Column;
use Concrete\Core\Entity\Express\Association;
use Concrete\Core\Search\Column\Column;
use Concrete\Core\Search\Result\Result;
class AssociationColumn extends Column
{
protected $association = false;
protected $associationID;
public function __construct... |
Fix ancestor next sibling test for DOMIterator. | <?php
namespace ComplexPie;
class DOMIterator implements \Iterator
{
private $root;
private $node;
private $position = 0;
public function __construct(\DOMNode $root)
{
$this->root = $root;
$this->rewind();
}
public function rewind()
{
$this->position = ... | <?php
namespace ComplexPie;
class DOMIterator implements \Iterator
{
private $root;
private $node;
private $position = 0;
public function __construct(\DOMNode $root)
{
$this->root = $root;
$this->rewind();
}
public function rewind()
{
$this->position = ... |
Fix the example that seemed to simply not work.. | <?php
namespace spec\MageTest\MagentoExtension\Context\Initializer;
use PHPSpec2\Specification;
class MagentoAwareInitializer implements Specification
{
function described_with($bootstrap, $app, $config, $cache, $factory)
{
$bootstrap->isAMockOf('MageTest\MagentoExtension\Service\Bootstrap');
... | <?php
namespace spec\MageTest\MagentoExtension\Context\Initializer;
use PHPSpec2\Specification;
class MagentoAwareInitializer implements Specification
{
function described_with($bootstrap, $app, $config, $cache, $factory)
{
$bootstrap->isAMockOf('MageTest\MagentoExtension\Service\Bootstrap');
... |
Use from django.conf import settings | from django.http import HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
def one_or_zero(arg):
"""Typecast to 1 or 0"""
if arg == '1':
return 1
elif arg == '0':
return 0
raise ValueError("not one or zero... | from django.http import HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from incubator.settings import STATUS_SECRETS
def one_or_zero(arg):
"""Typecast to 1 or 0"""
if arg == '1':
return 1
elif arg == '0':
return 0
raise ValueError("no... |
Enable integration test of citation-matching module | package pl.edu.icm.coansys.citations.coansys;
import java.io.File;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.testng.annotations.Test;
import pl.edu.icm.coansys.commons.hadoop.LocalSequenceFileUtils;
impor... | package pl.edu.icm.coansys.citations.coansys;
import java.io.File;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.testng.annotations.Test;
import pl.edu.icm.coansys.commons.hadoop.LocalSequenceFileUtils;
impor... |
[Capabilities] Fix doc formatting; wasn't expecting <pre> | # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol... | # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol... |
Add third, fourth and fifth test to the benchmark. | "use strict";
module.exports = function (grunt) {
grunt.initConfig({
eslint: {
src: [
"Gruntfile.js",
"index.js",
"lib/**/*.js",
"test/**/*.js"
]
},
vows: {
all: {
... | "use strict";
module.exports = function (grunt) {
grunt.initConfig({
eslint: {
src: [
"Gruntfile.js",
"index.js",
"lib/**/*.js",
"test/**/*.js"
]
},
vows: {
all: {
... |
Make it possible to register the locators via the constructor | package org.realityforge.replicant.client;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* A basic EntityLocator implementation that allows explicit per-type registration
*/
public class A... | package org.realityforge.replicant.client;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;
/**
* A basic EntityLocator implementation that allows explicit per-type registration
*/
public class A... |
Move tests to the top | package uk.co.benjiweber.expressions;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static uk.co.benjiweber.expressions.Using.using;
public class UsingTest {
@Test public void should_return_value() {
String result = using(Foo::new, foo -> {
return fo... | package uk.co.benjiweber.expressions;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import static uk.co.benjiweber.expressions.Using.using;
public class UsingTest {
static class Foo implements AutoCloseable {
public String result() {
return "result";
... |
Change history limit to 100 when viewing on single page | <?php
namespace Page;
class User
{
public function index()
{
$this->router->redirect('user/profile');
}
public function profile()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->l... | <?php
namespace Page;
class User
{
public function index()
{
$this->router->redirect('user/profile');
}
public function profile()
{
$this->load->model('Manga');
$this->load->library('Manga', 'MangaLib');
$this->load->l... |
Send proper response time even if non-200 | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_t... | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_t... |
Use assign instead of merge | 'use strict'
import * as types from '../constants/action-types'
import { REQUEST_PAGE_START_FROM } from '../constants/author-page'
import get from 'lodash/get'
import isArray from 'lodash/isArray'
import uniq from 'lodash/uniq'
const _ = {
get,
isArray,
uniq
}
const initialStates = {
isFetching: false
}
ex... | 'use strict'
import * as types from '../constants/action-types'
import { REQUEST_PAGE_START_FROM } from '../constants/author-page'
import get from 'lodash/get'
import isArray from 'lodash/isArray'
import merge from 'lodash/merge'
import uniq from 'lodash/uniq'
const _ = {
get,
isArray,
merge,
uniq
}
const i... |
Add state column to user create api | import uuid
from ckan import model
from ckan.lib import dictization
from ckan.plugins import toolkit
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base
import logging
log = logging.getLogger(__name__)
Base = declarative_base()
def make_uuid():
return unicode(uuid.uuid4(... | import uuid
from ckan import model
from ckan.lib import dictization
from ckan.plugins import toolkit
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base
import logging
log = logging.getLogger(__name__)
Base = declarative_base()
def make_uuid():
return unicode(uuid.uuid4(... |
Add baseUrl to require config | require.config({
baseUrl: "/js",
paths: {
'jquery': 'lib/jquery',
'underscore': 'lib/underscore',
'backbone': 'lib/backbone',
'doTCompiler': "lib/doTCompiler",
'text': 'lib/text',
'doT': 'lib/doT'
},
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ["u... | require.config({
paths: {
'jquery': 'lib/jquery',
'underscore': 'lib/underscore',
'backbone': 'lib/backbone',
'doTCompiler': "lib/doTCompiler",
'text': 'lib/text',
'doT': 'lib/doT'
},
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ["underscore", "jquer... |
Make the question more clear (for composition)
When the generator is being composed, people using the other generator might not be aware of its presence, so it's unclear what "Choose your style of DSL" refers to.
Ref. yeoman/generator-webapp#545.
Ref. yeoman/generator-webapp#538. | 'use strict';
var generators = require('yeoman-generator');
module.exports = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
this.option('ui', {
desc: 'Choose your style of test DSL for Mocha (bdd, tdd)',
type: String
});
this.option('rjs', {
... | 'use strict';
var generators = require('yeoman-generator');
module.exports = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
this.option('ui', {
desc: 'Choose your style of DSL (bdd, tdd)',
type: String
});
this.option('rjs', {
desc: 'Ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.