text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add method to retrieve dynamic attributes | <?php
namespace PhpAbac\Manager;
use PhpAbac\Repository\AttributeRepository;
use PhpAbac\Model\AbstractAttribute;
use PhpAbac\Model\Attribute;
class AttributeManager {
/** @var AttributeRepository **/
protected $repository;
public function __construct() {
$this->repository = new AttributeRe... | <?php
namespace PhpAbac\Manager;
use PhpAbac\Repository\AttributeRepository;
use PhpAbac\Model\AbstractAttribute;
use PhpAbac\Model\Attribute;
use PhpAbac\Model\EnvironmentAttribute;
class AttributeManager {
/** @var AttributeRepository **/
protected $repository;
public function __construct() {
... |
Fix cancellable streams on Windows clients + HTTPS transport
Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com> | import socket
try:
import requests.packages.urllib3 as urllib3
except ImportError:
import urllib3
class CancellableStream(object):
"""
Stream wrapper for real-time events, logs, etc. from the server.
Example:
>>> events = client.events()
>>> for event in events:
... pri... | import socket
try:
import requests.packages.urllib3 as urllib3
except ImportError:
import urllib3
class CancellableStream(object):
"""
Stream wrapper for real-time events, logs, etc. from the server.
Example:
>>> events = client.events()
>>> for event in events:
... pri... |
Apply phpqa using PSR2 standards | <?php
/**
* @file
* Contains Drupal\AppConsole\Test\Generator\PluginBlockGeneratorTest.
*/
namespace Drupal\AppConsole\Test\Generator;
use Drupal\AppConsole\Generator\PluginBlockGenerator;
use Drupal\AppConsole\Test\DataProvider\PluginBlockDataProviderTrait;
class PluginBlockGeneratorTest extends GeneratorTest
{... | <?php
/**
* @file
* Contains Drupal\AppConsole\Test\Generator\PluginBlockGeneratorTest.
*/
namespace Drupal\AppConsole\Test\Generator;
use Drupal\AppConsole\Generator\PluginBlockGenerator;
use Drupal\AppConsole\Test\DataProvider\PluginBlockDataProviderTrait;
class PluginBlockGeneratorTest extends GeneratorTest
{... |
Allow for higher versions of werkzeug
Install fails when a version of `werkzeug` greater than `0.10` is already present in the environment (current version is `0.10.4`) | from setuptools import setup, find_packages
setup(name='googleanalytics',
description='A wrapper for the Google Analytics API.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='stijn@debrouwere.org',
url='https://github.com/debrouwere/google-analytics/',
dow... | from setuptools import setup, find_packages
setup(name='googleanalytics',
description='A wrapper for the Google Analytics API.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='stijn@debrouwere.org',
url='https://github.com/debrouwere/google-analytics/',
dow... |
Revert "Revert "api key deleted from the list of required parameters"" | package org.atlasapi.application.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.http.HttpServletRequest;
import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;
import com.google.c... | package org.atlasapi.application.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.http.HttpServletRequest;
import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;
import com.google.c... |
Fix open call for LICENSE.txt
Closes #76 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytube import __version__
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('LICENSE.txt') as readme_file:
license = readme_file.read()... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytube import __version__
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('LICENSE') as readme_file:
license = readme_file.read()
se... |
Change empy Subsystem wrapper to old style class. | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, bas... | #!/usr/bin/env python
"""Provide the empy templating engine."""
from __future__ import print_function
import os.path
import em
from . import Engine
class SubsystemWrapper(em.Subsystem):
"""Wrap EmPy's Subsystem class.
Allows to open files relative to a base directory.
"""
def __init__(self, bas... |
Add function to get stats | <?php
namespace OrgManager\ApiClient;
use GuzzleHttp\Client;
class OrgManager
{
/** @var \GuzzleHttp\Client */
protected $client;
/** @var string */
protected $baseUrl;
/**
* @param \GuzzleHttp\Client $client
* @param string $apiToken
* @param string $root... | <?php
namespace OrgManager\ApiClient;
use GuzzleHttp\Client;
class OrgManager
{
/** @var \GuzzleHttp\Client */
protected $client;
/** @var string */
protected $baseUrl;
/**
* @param \GuzzleHttp\Client $client
* @param string $apiToken
* @param string $root... |
BUG: Fix typo in variable name. | """Aligner for texts and their segmentations.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
__all__ = ['AlignmentFailed', 'Aligner']
class AlignmentFailed(Exception): pass
class Aligner(object):
"""Align a text with its tokenization.
... | """Aligner for texts and their segmentations.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
__all__ = ['AlignmentFailed', 'Aligner']
class AlignmentFailed(Exception): pass
class Aligner(object):
"""Align a text with its tokenization.
... |
Add email to OrganizationInvitation query | import Relay from 'react-relay';
import OrganizationMemberRoleConstants from '../constants/OrganizationMemberRoleConstants';
export default class OrganizationInvitationCreate extends Relay.Mutation {
static fragments = {
organization: () => Relay.QL`
fragment on Organization {
id
}
`
}... | import Relay from 'react-relay';
import OrganizationMemberRoleConstants from '../constants/OrganizationMemberRoleConstants';
export default class OrganizationInvitationCreate extends Relay.Mutation {
static fragments = {
organization: () => Relay.QL`
fragment on Organization {
id
}
`
}... |
Rename vars in get_all_exits to make it more clear | #!/usr/bin/python3
class Puzzle:
def get_all_exits(self, graph):
exits = []
for root_node, connected_nodes in graph.items():
for node in connected_nodes:
if 'Exit' in node:
exits += node
return exits
def find_all_paths(self, graph, start... | #!/usr/bin/python3
class Puzzle:
def get_all_exits(self, graph):
exits = []
for key, value in graph.items():
for item in value:
if 'Exit' in item:
exits += item
return exits
def find_all_paths(self, graph, start, end, path=None):
... |
Change name back to dredd_hooks | # -*- coding: utf-8 -*-
from setuptools import find_packages, setup
long_desc = open('README.rst').read()
setup(
name='dredd_hooks',
version='0.1.3',
url='https://github.com/apiaryio/dredd-hooks-python/',
download_url='http://pypi.python.org/pypi/dredd_hooks',
license='MIT License',
author='V... | # -*- coding: utf-8 -*-
from setuptools import find_packages, setup
long_desc = open('README.rst').read()
setup(
name='dredd-hooks-python',
version='0.1.3',
url='https://github.com/apiaryio/dredd-hooks-python/',
download_url='http://pypi.python.org/pypi/dredd_hooks',
license='MIT License',
au... |
Add comments for tests of caching. | import unittest
import mock
import chainer
from chainer.functions.pooling import pooling_nd_kernel
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'ndim': [2, 3, 4],
}))
@attr.gpu
class TestPoolingNDKernelMemo(unittest.TestCase):
def setUp(self):
... | import unittest
import mock
import chainer
from chainer.functions.pooling import pooling_nd_kernel
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'ndim': [2, 3, 4],
}))
@attr.gpu
class TestPoolingNDKernelMemo(unittest.TestCase):
def setUp(self):
... |
Fix support for multiple tests in the same directory | import test from "ava";
import {runKaba} from "./lib/runner";
/**
* @typedef {{
* status: number,
* dir?: string,
* args?: string[],
* match?: RegExp,
* noMatch?: RegExp,
* }} FixtureConfig
*/
/* eslint-disable camelcase */
/** @var {Object<string,FixtureConfig>} fixtureTests */
let ... | import test from "ava";
import {runKaba} from "./lib/runner";
/**
* @typedef {{
* status: number,
* args?: string[],
* match?: RegExp,
* noMatch?: RegExp,
* }} FixtureConfig
*/
/* eslint-disable camelcase */
/** @var {Object<string,FixtureConfig>} fixtureTests */
let fixtureTests = {
j... |
Set jshint configuration option 'latedef' to false | module.exports = function (grunt) {
"use strict";
// load all grunt tasks
require('load-grunt-tasks')(grunt);
// Default task.
grunt.registerTask('default', ['jshint', 'karma']);
// uglify
grunt.registerTask('minify', ['uglify']);
var testConfig = function(configFile, customOptions) {
... | module.exports = function (grunt) {
"use strict";
// load all grunt tasks
require('load-grunt-tasks')(grunt);
// Default task.
grunt.registerTask('default', ['jshint', 'karma']);
// uglify
grunt.registerTask('minify', ['uglify']);
var testConfig = function(configFile, customOptions) {
... |
Revert "BUG: fms_v5 | ep importer -> the titles are compared using the same htmlspecialchars encoding"
This reverts commit 7d55ab33101d4ce18e99c14034d6f758f519b315. | <?php
/*"******************************************************************************************************
* (c) 2004-2006 by MulchProductions, www.mulchprod.de *
* (c) 2007-2014 by Kajona, www.kajona.de ... | <?php
/*"******************************************************************************************************
* (c) 2004-2006 by MulchProductions, www.mulchprod.de *
* (c) 2007-2014 by Kajona, www.kajona.de ... |
Fix naming issues in dictionary test | <?php
namespace Shadowhand\Test\Destrukt;
use Shadowhand\Destrukt\Dictionary;
class DictionaryTest extends StructTest
{
public function setUp()
{
$this->struct = new Dictionary([
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
]);
}
... | <?php
namespace Shadowhand\Test\Destrukt;
use Shadowhand\Destrukt\Dictionary;
class HashTest extends StructTest
{
public function setUp()
{
$this->struct = new Dictionary([
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
]);
}
p... |
Change function-based generic view to class-based.
As per their deprecation policy, Django 1.5 removed function-based
generic views. | # encoding: utf-8
"""
URL conf for django-sphinxdoc.
"""
from django.conf.urls.defaults import patterns, url
from django.views.generic.list import ListView
from sphinxdoc import models
from sphinxdoc.views import ProjectSearchView
urlpatterns = patterns('sphinxdoc.views',
url(
r'^$',
ListView.as... | # encoding: utf-8
"""
URL conf for django-sphinxdoc.
"""
from django.conf.urls.defaults import patterns, url
from django.views.generic import list_detail
from sphinxdoc import models
from sphinxdoc.views import ProjectSearchView
project_info = {
'queryset': models.Project.objects.all().order_by('name'),
'te... |
Fix for new builder of laravel | <?php
namespace Nbj\Cockroach\Builder;
use Illuminate\Database\Schema\Builder;
class CockroachBuilder extends Builder
{
/**
* Determine if the given table exists.
*
* @param string $table
* @return bool
*/
public function hasTable($table)
{
if (is_array($schema = $this-... | <?php
namespace Nbj\Cockroach\Builder;
use Illuminate\Database\Schema\Builder;
class CockroachBuilder extends Builder
{
/**
* Determine if the given table exists.
*
* @param string $table
* @return bool
*/
public function hasTable($table)
{
if (is_array($schema = $this-... |
Tag {{tmpl}} should not change nesting value | <?php
class jQueryTmpl_Tag_Tmpl implements jQueryTmpl_Tag
{
public function getTokenType()
{
return 'Tmpl';
}
public function getRegex()
{
return '/{{tmpl.*?}}/is';
}
public function getNestingValue()
{
return array(0,0);
}
public function parseTag($ra... | <?php
class jQueryTmpl_Tag_Tmpl implements jQueryTmpl_Tag
{
public function getTokenType()
{
return 'Tmpl';
}
public function getRegex()
{
return '/{{tmpl.*?}}/is';
}
public function getNestingValue()
{
return array(0,1);
}
public function parseTag($ra... |
Use new PROJECTIONCHANGE event properties | TC.control = TC.control || {};
if (!TC.Control) {
TC.syncLoadJS(TC.apiLocation + 'TC/Control');
}
TC.control.NavBarHome = function () {
TC.Control.apply(this, arguments);
};
TC.inherit(TC.control.NavBarHome, TC.Control);
(function () {
var ctlProto = TC.control.NavBarHome.prototype;
ctlProto.CLASS... | TC.control = TC.control || {};
if (!TC.Control) {
TC.syncLoadJS(TC.apiLocation + 'TC/Control');
}
TC.control.NavBarHome = function () {
TC.Control.apply(this, arguments);
};
TC.inherit(TC.control.NavBarHome, TC.Control);
(function () {
var ctlProto = TC.control.NavBarHome.prototype;
ctlProto.CLASS... |
Fix relative import to be absolute | import d3 from 'd3';
import fcRebind from 'd3fc-rebind';
import {getStockFluxData} from 'stockflux-core/src/services/StockFluxService';
export default function() {
var historicFeed = getStockFluxData(),
granularity,
candles;
var allowedPeriods = d3.map();
allowedPeriods.set(60 * 60 * 24, '... | import d3 from 'd3';
import fcRebind from 'd3fc-rebind';
import {getStockFluxData} from '../../../../../../node_modules/stockflux-core/src/services/StockFluxService';
export default function() {
var historicFeed = getStockFluxData(),
granularity,
candles;
var allowedPeriods = d3.map();
all... |
Use inline-block instead of float for iframes to prevent text from
wrapping around them. | <?php
class IncludeSteepGadgets {
static function HookParser($parser) {
$parser->setHook("process-model", "IncludeSteepGadgets::ProcessModelRender");
$parser->setHook("data-map", "IncludeSteepGadgets::MapRender");
return true;
}
static function ProcessModelRender($input, $args, $pa... | <?php
class IncludeSteepGadgets {
static function HookParser($parser) {
$parser->setHook("process-model", "IncludeSteepGadgets::ProcessModelRender");
$parser->setHook("data-map", "IncludeSteepGadgets::MapRender");
return true;
}
static function ProcessModelRender($input, $args, $pa... |
Append 站 to train station name | package cn.sunner.sms2calendar;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Sunner on 6/29/16.
*/
public class N12306Parser extends SMSParser {
public N12306Parser(String text) {
super(text);
}
... | package cn.sunner.sms2calendar;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Sunner on 6/29/16.
*/
public class N12306Parser extends SMSParser {
public N12306Parser(String text) {
super(text);
}
... |
Use get_prep_value instead of the database related one. Closes gh-42 | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value... | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value... |
Revert "Updating md5 for fixed file" because this was fixed properly in unstable (but will break SnpEff if put into Stable).
This reverts commit 6b4182c6ab3e214da4c73bc6f3687ac6d1c0b72c. | package org.broadinstitute.sting.gatk.walkers.CNV;
import org.broadinstitute.sting.WalkerTest;
import org.testng.annotations.Test;
import java.util.Arrays;
public class SymbolicAllelesIntegrationTest extends WalkerTest {
public static String baseTestString(String reference, String VCF) {
return "-T Comb... | package org.broadinstitute.sting.gatk.walkers.CNV;
import org.broadinstitute.sting.WalkerTest;
import org.testng.annotations.Test;
import java.util.Arrays;
public class SymbolicAllelesIntegrationTest extends WalkerTest {
public static String baseTestString(String reference, String VCF) {
return "-T Comb... |
Introduce set_of (similar to list_of validator) | # Licenced under the txaws licence available at /LICENSE in the txaws source.
"""
attrs validators for internal use.
"""
import attr
from attr import validators
def list_of(validator):
"""
Require a value which is a list containing elements which the
given validator accepts.
"""
return _Containe... | # Licenced under the txaws licence available at /LICENSE in the txaws source.
"""
attrs validators for internal use.
"""
import attr
from attr import validators
def list_of(validator):
"""
Require a value which is a list containing elements which the
given validator accepts.
"""
return _ListOf(v... |
Add type check when exchanging an array | <?php
namespace RDM\Generics;
class TypedArrayObject extends \ArrayObject
{
private $type;
/**
* {@inheritDoc}
*
* @param string $type The type of elements the array can contain.
* Can be any of the primitive types or a class name.
*/
public function __cons... | <?php
namespace RDM\Generics;
class TypedArrayObject extends \ArrayObject
{
private $type;
/**
* {@inheritDoc}
*
* @param string $type The type of elements the array can contain.
* Can be any of the primitive types or a class name.
*/
public function __cons... |
Test (absolute basics): Change margins to absolute coordinates | /**
* Basics
*/
describe('Basics', () => {
beforeEach(beforeEachHook);
afterEach(afterEachHook);
/**
* Absolute tracking
*/
it('absolute tracking', async () => {
let times = 0;
let poolCopy;
const targetOne = createTarget({ left: '-30px' });
const targetTwo = createTarget({ top: '30px' ... | /**
* Basics
*/
describe('Basics', () => {
beforeEach(beforeEachHook);
afterEach(afterEachHook);
/**
* Absolute tracking
*/
it('absolute tracking', async () => {
let times = 0;
let poolCopy;
const targetOne = createTarget({ marginLeft: '-30px' });
const targetTwo = createTarget({ margin... |
Change String array constructor to varargs | package me.rbrickis.mojo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Arguments {
private List<String> arguments;
public Arguments() {
this.arguments = new ArrayList<>();
}
public Arguments(String... arguments) {
this.arguments = Arrays.a... | package me.rbrickis.mojo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Arguments {
private List<String> arguments;
public Arguments() {
this.arguments = new ArrayList<>();
}
public Arguments(String[] arguments) {
this.arguments = Arrays.as... |
Print "Gesamtproduktgüte" on any key press. | package rogue.creature;
import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;
public class Player extends Creature implements C... | package rogue.creature;
import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;
public class Player extends Creature implements C... |
Remove synchronization, it leads to deadlocks
Example:
Thread A gets the lock in acquire(), does not hold the monitor anymore..
Thread B calls acquire() and waits for the lock (while holding the monitor)
Thead A wants to call release(), but cannot do that because thread B is
holding the monitor. Deadlock until timeout... | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.tenant;
import com.yahoo.path.Path;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.rec... | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.tenant;
import com.yahoo.path.Path;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.rec... |
Use new structure for 2.0 | (function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway... | (function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway... |
Fix roam param for compatibility. | import * as zrUtil from 'zrender/src/core/util';
function dataToCoordSize(dataSize, dataItem) {
dataItem = dataItem || [0, 0];
return zrUtil.map([0, 1], function (dimIdx) {
var val = dataItem[dimIdx];
var halfSize = dataSize[dimIdx] / 2;
var p1 = [];
var p2 = [];
p1[dimI... | import * as zrUtil from 'zrender/src/core/util';
function dataToCoordSize(dataSize, dataItem) {
dataItem = dataItem || [0, 0];
return zrUtil.map([0, 1], function (dimIdx) {
var val = dataItem[dimIdx];
var halfSize = dataSize[dimIdx] / 2;
var p1 = [];
var p2 = [];
p1[dimI... |
Update service worker to use cache and update strategy | var CACHE_NAME = 'static';
function _addToCache(method, resource, url) {
if (method === 'addAll') {
return caches.open(CACHE_NAME).then(cache => {
cache[method](resource);
});
} else if (method === 'put') {
return caches.open(CACHE_NAME).then(cache => {
cache[met... | var CACHE_NAME = 'static';
function _addToCache(method, resource, url) {
if (method === 'addAll') {
return caches.open(CACHE_NAME).then(cache => {
cache[method](resource);
});
} else if (method === 'put') {
return caches.open(CACHE_NAME).then(cache => {
cache[met... |
Fix refresh button highlighted after click | import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import ContainerFluid from '../ContainerFluid'
import VmUserMessages from '../VmUserMessages'
import UserMenu from './UserMenu'
import { getAllVms } from '../../actions/vm'
/**
* Main application header on top of the page
*/
const VmsPa... | import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import ContainerFluid from '../ContainerFluid'
import VmUserMessages from '../VmUserMessages'
import UserMenu from './UserMenu'
import { getAllVms } from '../../actions/vm'
/**
* Main application header on top of the page
*/
const VmsPa... |
Print client-POSTed data, more verbose error handling
And less fiddling with the returned header. For the time being,
I don't care about correcting the bugs in that part of the code. | # Adapted from http://stackoverflow.com/questions/10017859/how-to-build-a-simple-http-post-server
# Thank you!
import sys
import BaseHTTPServer
import cgi
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
... | # Adapted from http://stackoverflow.com/questions/10017859/how-to-build-a-simple-http-post-server
# Thank you!
import sys
import BaseHTTPServer
import cgi
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
... |
Add import error message to example | import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!... | from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
... |
Update to version 0.2 and some trove classifiers | #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.execut... | #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.execut... |
Add artificial limit of 500 records in lieu of pagination | (function () {
'use strict';
define(
[
'lodash',
'jquery'
],
function (_, $) {
return function (baseUrl, ajaxOptions, noCache) {
var queryString;
queryString = function (parameters) {
return _.map(p... | (function () {
'use strict';
define(
[
'lodash',
'jquery'
],
function (_, $) {
return function (baseUrl, ajaxOptions, noCache) {
var queryString;
queryString = function (parameters) {
return _.map(p... |
Update js to set also time (not just date) | function getDatePicker() {
var languageUA = {
days: ['Неділя','Понеділок','Вівторок','Середа','Четвер','Пятниця','Субота'],
daysShort: ['Нед','Пон','Вів','Сер','Чет','Пят','Суб'],
daysMin: ['Нд','Пн','Вт','Ср','Чт','Пт','Сб'],
months: ['Січень','Лютий','Березень','Квітень','Травень',... | function getDatePicker() {
var languageUA = {
days: ['Неділя','Понеділок','Вівторок','Середа','Четвер','Пятниця','Субота'],
daysShort: ['Нед','Пон','Вів','Сер','Чет','Пят','Суб'],
daysMin: ['Нд','Пн','Вт','Ср','Чт','Пт','Сб'],
months: ['Січень','Лютий','Березень','Квітень','Травень',... |
Add petition start date and running time back in for ended petitions | import React from 'react';
import styles from './petition-sidebar.scss';
import Countdown from 'components/Countdown';
import PetitionResponseStatus from 'containers/PetitionResponseStatus';
import ButtonIcon from 'components/ButtonIcon';
import FakeButton from 'components/FakeButton';
import SupportButton from 'contai... | import React from 'react';
import styles from './petition-sidebar.scss';
import Countdown from 'components/Countdown';
import PetitionResponseStatus from 'containers/PetitionResponseStatus';
import ButtonIcon from 'components/ButtonIcon';
import FakeButton from 'components/FakeButton';
import SupportButton from 'contai... |
Remove certain meddlesome ActBlue filing from a skip list | var async = require('async'),
fs = require('fs'),
filingQueue = require('./import'),
yauzl = require('yauzl');
var filings_dir = __dirname + '/../../data/fec/filings';
function unzipFile(file,cb) {
yauzl.open(file, {
autoClose: false
}, function(err, zipfile) {
if (err) thr... | var async = require('async'),
fs = require('fs'),
filingQueue = require('./import'),
yauzl = require('yauzl');
var filings_dir = __dirname + '/../../data/fec/filings';
function unzipFile(file,cb) {
yauzl.open(file, {
autoClose: false
}, function(err, zipfile) {
if (err) thr... |
Add source to project build index query | from __future__ import absolute_import, division, unicode_literals
from flask import Response, request
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Project, Build
class ProjectBuildIndexAPIView(APIView):
def _get_project(self, project_id):
project... | from __future__ import absolute_import, division, unicode_literals
from flask import Response, request
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Project, Build
class ProjectBuildIndexAPIView(APIView):
def _get_project(self, project_id):
project... |
redis_commands: Use a synopsis for usage examples | #!/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'):
... |
Make xmvn-resolve print resolved artifact files | /*-
* Copyright (c) 2012 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | /*-
* Copyright (c) 2012 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
Align award to tree sort | import { inject as service } from '@ember/service';
import { not, sort, filterBy } from '@ember/object/computed';
import { task } from 'ember-concurrency';
import Component from '@ember/component';
export default Component.extend({
store: service(),
flashMessages: service(),
isDisabled: not(
'model.permissio... | import { inject as service } from '@ember/service';
import { not, sort, filterBy } from '@ember/object/computed';
import { task } from 'ember-concurrency';
import Component from '@ember/component';
export default Component.extend({
store: service(),
flashMessages: service(),
isDisabled: not(
'model.permissio... |
Fix seller user group level security
After refactoring Admin* components to Seller* components we forgot to update the seller
user group security controller to use "sellerusergroupid" $stateParam instead of the old
"adminusergroupid". | angular.module('orderCloud')
.controller('SecurityCtrl', SecurityController)
;
function SecurityController($exceptionHandler, $stateParams, toastr, Assignments, AvailableProfiles, OrderCloudSDK) {
var vm = this;
vm.assignments = Assignments;
vm.profiles = AvailableProfiles;
vm.buyerid = $stateParam... | angular.module('orderCloud')
.controller('SecurityCtrl', SecurityController)
;
function SecurityController($exceptionHandler, $stateParams, toastr, Assignments, AvailableProfiles, OrderCloudSDK) {
var vm = this;
vm.assignments = Assignments;
vm.profiles = AvailableProfiles;
vm.buyerid = $stateParam... |
system: Load specific L10n providers in factory | <?php
/**
* Factory class for providing Localization implementations
* @author M2Mobi, Heinz Wiesinger
*/
class L10nFactory
{
/**
* Instance of the L10nProvider
* @var array
*/
private static $lprovider;
/**
* Constructor
*/
public function __construct()
{
}
... | <?php
/**
* Factory class for providing Localization implementations
* @author M2Mobi, Heinz Wiesinger
*/
class L10nFactory
{
/**
* Instance of the L10nProvider
* @var array
*/
private static $lprovider;
/**
* Constructor
*/
public function __construct()
{
}
... |
Undone: Set local worker as default for SyftTensor owner | import random
from syft.frameworks.torch.tensors import PointerTensor
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = None
def create_pointer(
se... | import random
from syft.frameworks.torch.tensors import PointerTensor
import syft
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = syft.local_worker
def ... |
Fix the error when there's no thumbnail available
In case the API returns null for the thumbnail, a dummy image is set as
the thumbnail prop | var React = require('react');
var Character = React.createClass({
getThumbnail: function() {
var image = 'http://placehold.it/250x250';
if(this.props.character.thumbnail) {
image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension;
}
return (
<img classNa... | var React = require('react');
var Character = React.createClass({
getThumbnail: function() {
var image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension;
return (
<img className="character-image" src={image}/>
)
},
getName: function() {
return (
<spa... |
Change units in weather api to imperial |
//Geolocation Function is listed below.
function geoLocation() {
var output = document.getElementById("out");
/*$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
... |
//Geolocation Function is listed below.
function geoLocation() {
var output = document.getElementById("out");
/*$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
... |
Fix notifications to use the wordName rather than wordId | import Ember from 'ember';
import ENV from '../config/environment';
import { Bindings } from 'ember-pusher/bindings';
// used by the Application controller
export default Ember.Mixin.create(Bindings, {
logPusherEvents: (ENV.environment === "development"),
PUSHER_SUBSCRIPTIONS: {
activities: ["push"]
},
us... | import Ember from 'ember';
import ENV from '../config/environment';
import { Bindings } from 'ember-pusher/bindings';
// used by the Application controller
export default Ember.Mixin.create(Bindings, {
logPusherEvents: (ENV.environment === "development"),
PUSHER_SUBSCRIPTIONS: {
activities: ["push"]
},
us... |
Make min length of lastname =2 | <?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Business;
use App\Contact;
use Route;
class AlterContactRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return ... | <?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Business;
use App\Contact;
use Route;
class AlterContactRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return ... |
Check event name when constructing. Cannot be empty. | <?php
namespace Arch;
/**
* Class event
*/
class Event
{
/**
* The event name
* @var string
*/
protected $name;
/**
* The event callback
* @var mixed
*/
protected $callback;
/**
* An optional target
* @var mixed
*/
protected $target... | <?php
namespace Arch;
/**
* Class event
*/
class Event
{
/**
* The event name
* @var string
*/
protected $name;
/**
* The event callback
* @var mixed
*/
protected $callback;
/**
* An optional target
* @var mixed
*/
protected $target... |
Use existing `afterNodeCreate` signal to trigger NodeConfigurator | <?php
namespace M12\Foundation;
/* *
* This script belongs to the "M12.Foundation" package. *
* *
* It is free software; you can redistribute it and/or modi... | <?php
namespace M12\Foundation;
/* *
* This script belongs to the "M12.Foundation" package. *
* *
* It is free software; you can redistribute it and/or modi... |
Revert to using the base postgres driver in tests | package org.realityforge.jeo.geolatte.jpa.eclipselink;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class DatabaseTestUtil
{
static Properties initDatabaseProperties()
{
final Properties propert... | package org.realityforge.jeo.geolatte.jpa.eclipselink;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class DatabaseTestUtil
{
static Properties initDatabaseProperties()
{
final Properties propert... |
Add test for export declarations to findUsedIdentifiers
I recently added some test that changed how identifiers were visited,
and I just wanted to make sure I didn't break anything for the
findUsedIdentifiers module. | import findUsedIdentifiers from '../findUsedIdentifiers';
import parse from '../parse';
it('finds used variables', () => {
expect(
findUsedIdentifiers(
parse(
`
api.something();
const foo = 'foo';
foo();
bar();
`,
),
),
).toEqual(new Set(['api', 'foo', 'bar']));
});
i... | import findUsedIdentifiers from '../findUsedIdentifiers';
import parse from '../parse';
it('finds used variables', () => {
expect(
findUsedIdentifiers(
parse(
`
api.something();
const foo = 'foo';
foo();
bar();
`,
),
),
).toEqual(new Set(['api', 'foo', 'bar']));
});
i... |
Add PHP code highlighting within package descriptions, patch from Amir. | <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>Package :: <?php echo $context->name; ?></h2>
<p><em><?php echo $context->summary; ?></em></p>
<p>
<?php
... | <?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>
<div class="package">
<div class="grid_8 left">
<h2>Package :: <?php echo $context->name; ?></h2>
<p><em><?php echo $context->summary; ?></em></p>
<p>
<?php
... |
Change status from Beta to Production/Stable | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.6',
'botocore>=1.5.40,<2.0.0',
'typing==3.5.3.0',
'six>=1.10.0,<2.0.0',
'pip>=9,<10'
]
setup(
name='chalice',
version=... | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.6',
'botocore>=1.5.40,<2.0.0',
'typing==3.5.3.0',
'six>=1.10.0,<2.0.0',
'pip>=9,<10'
]
setup(
name='chalice',
version=... |
Fix upgrade script: Check for empty items | /** @namespace H5PUpgrades */
var H5PUpgrades = H5PUpgrades || {};
H5PUpgrades['H5P.Agamotto'] = (function ($) {
return {
1: {
3: function (parameters, finished) {
// Update image items
if (parameters.items) {
parameters.items = parameters.items.map( function (item) {
... | /** @namespace H5PUpgrades */
var H5PUpgrades = H5PUpgrades || {};
H5PUpgrades['H5P.Agamotto'] = (function ($) {
return {
1: {
3: function (parameters, finished) {
// Update image items
parameters.items = parameters.items.map( function (item) {
// Create new image structure
... |
Change getting key method (SAAS-612)
Change key text split by '==' to split by whitespace.
http://localhost:8001/#/keys/add/ | (function() {
angular.module('ncsaas')
.controller('KeyAddController', ['baseControllerAddClass', 'keysService', '$state', KeyAddController]);
function KeyAddController(baseControllerAddClass, keysService, $state) {
var controllerScope = this;
var Controller = baseControllerAddClass.extend({
init... | (function() {
angular.module('ncsaas')
.controller('KeyAddController', ['baseControllerAddClass', 'keysService', '$state', KeyAddController]);
function KeyAddController(baseControllerAddClass, keysService, $state) {
var controllerScope = this;
var Controller = baseControllerAddClass.extend({
init... |
PUBDEV-2984: Add pyunit test for model_performance(xval=True) | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
... | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_nfolds_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate[1] = prostate[1].asfactor()
... |
Update target browsers. IE 11 needs to be manually specified now becuase it's dropped below 1% in Australia, but is still supported by ABC. | // External
const mem = require('mem');
// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');
const PROJECT_TYPES_CONFIG = {
preact: {
plugins: [
[
require.resolve('@babel/plugin-transform-react-jsx'),
{
pragma: 'h'
}... | // External
const mem = require('mem');
// Ours
const { merge } = require('../utils/structures');
const { getProjectConfig } = require('./project');
const PROJECT_TYPES_CONFIG = {
preact: {
plugins: [
[
require.resolve('@babel/plugin-transform-react-jsx'),
{
pragma: 'h'
}... |
Fix: Add type to param annotation | <?php
namespace Joindin\Api\Model;
use Joindin\Api\Request;
/**
* Container for multiple EventCommentReportModel objects
*/
class PendingTalkClaimModelCollection extends BaseModelCollection
{
/** @var array|PendingTalkClaimModel[] */
protected $list;
protected $total;
/**
* Take arrays of da... | <?php
namespace Joindin\Api\Model;
use Joindin\Api\Request;
/**
* Container for multiple EventCommentReportModel objects
*/
class PendingTalkClaimModelCollection extends BaseModelCollection
{
/** @var array|PendingTalkClaimModel[] */
protected $list;
protected $total;
/**
* Take arrays of da... |
Fix warning from React component prop not being camelCased | const Job = ({ locations, deadline, companyImage, companyName, jobTitle, ingress, jobName }) => {
if (locations.length >= 2) {
locations = `${locations.slice(0, -1).join(', ')} and ${locations[locations.length - 1]}`;
} else if (locations.length === 0) {
locations = 'Ikke spesifisert';
}
return (
<... | const Job = ({ locations, deadline, companyImage, companyName, jobTitle, ingress, jobName }) => {
if (locations.length >= 2) {
locations = `${locations.slice(0, -1).join(', ')} and ${locations[locations.length - 1]}`;
} else if (locations.length === 0) {
locations = 'Ikke spesifisert';
}
return (
<... |
Change the VERSION to 1.1.0.pre | VERSION = (1, 1, 0, 'pre')
__version__ = '.'.join(map(str, VERSION))
import logging
logger = logging.getLogger('plata')
class LazySettings(object):
def _load_settings(self):
from plata import default_settings
from django.conf import settings as django_settings
for key in dir(default_set... | VERSION = (1, 0, 0)
__version__ = '.'.join(map(str, VERSION))
import logging
logger = logging.getLogger('plata')
class LazySettings(object):
def _load_settings(self):
from plata import default_settings
from django.conf import settings as django_settings
for key in dir(default_settings):... |
Use static method instead of classmethod | # -*- encoding: utf-8 -*-
import logging
import yaml
from collections import namedtuple
log = logging.getLogger(__name__)
def load(filename):
with open(filename) as fp:
config = yaml.safe_load(fp)
return CfnCliConfig.load(config)
class CfnCliConfig(namedtuple('CfnCliConfig', 'version blueprints e... | # -*- encoding: utf-8 -*-
import logging
import yaml
from collections import namedtuple
log = logging.getLogger(__name__)
def load(filename):
with open(filename) as fp:
config = yaml.safe_load(fp)
return CfnCliConfig.load(config)
class CfnCliConfig(namedtuple('CfnCliConfig', 'version blueprints e... |
Use list comp instead of unnecessary dict comp | from framework.tasks.handlers import enqueue_task
from framework.archiver.tasks import archive, send_success_message
from framework.archiver.utils import (
link_archive_provider,
)
from framework.archiver import (
ARCHIVER_SUCCESS,
ARCHIVER_FAILURE,
)
from framework.archiver.exceptions import ArchiverCopyEr... | from framework.tasks.handlers import enqueue_task
from framework.archiver.tasks import archive, send_success_message
from framework.archiver.utils import (
link_archive_provider,
)
from framework.archiver import (
ARCHIVER_SUCCESS,
ARCHIVER_FAILURE,
)
from framework.archiver.exceptions import ArchiverCopyEr... |
Remove attempt to populate file input | App.extend({
Components: {}
});
App.Components.Form = (function ($) {
var pub = {
name: 'app.Components.Form',
events: ['change'],
assignFormValue: function (element, value) {
var isJqueryObj = element instanceof jQuery;
if (!isJqueryObj) {
elem... | App.extend({
Components: {}
});
App.Components.Form = (function ($) {
var pub = {
name: 'app.Components.Form',
events: ['change'],
assignFormValue: function (element, value) {
var isJqueryObj = element instanceof jQuery;
if (!isJqueryObj) {
elem... |
Change pypi version to 1.6.14-1 | from setuptools import setup, find_packages
import client
VERSION = client.__version__
setup(
name='okpy',
version='1.6.14-1', # version=VERSION,
author='John Denero, Soumya Basu, Stephen Martinis, Sharad Vikram, Albert Wu',
# author_email='',
description=('ok.py supports programming projects by ... | from setuptools import setup, find_packages
import client
VERSION = client.__version__
setup(
name='okpy',
version=VERSION,
author='John Denero, Soumya Basu, Stephen Martinis, Sharad Vikram, Albert Wu',
# author_email='',
description=('ok.py supports programming projects by running tests, '
... |
Fix typo "ech" -> "each" | """
This plugin implements :func:`startTestRun`, setting a test executor
(``event.executeTests``) that just collects tests without executing
them. To do so it calls result.startTest, result.addSuccess and
result.stopTest for each test, without calling the test itself.
"""
from nose2.events import Plugin
from nose2.comp... | """
This plugin implements :func:`startTestRun`, setting a test executor
(``event.executeTests``) that just collects tests without executing
them. To do so it calls result.startTest, result.addSuccess and
result.stopTest for ech test, without calling the test itself.
"""
from nose2.events import Plugin
from nose2.compa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.