text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Use BytecodeScanningDetector as base class | package edu.umd.cs.findbugs.detect;
import org.apache.bcel.classfile.CodeException;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
public class DontCatchNullPointerEx... | package edu.umd.cs.findbugs.detect;
import org.apache.bcel.classfile.CodeException;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
public class Don... |
Fix missing default values with autocomplete | import { inject, bindable, bindingMode } from 'aurelia-framework';
import { Config } from 'aurelia-api';
@inject(Element, Config)
export class UiAutocomplete {
@bindable({defaultBindingMode: bindingMode.twoWay}) value;
@bindable from;
@bindable placeholder;
@bindable searchParams = {};
@bindable di... | import { inject, bindable, bindingMode } from 'aurelia-framework';
import { Config } from 'aurelia-api';
@inject(Element, Config)
export class UiAutocomplete {
@bindable({defaultBindingMode: bindingMode.twoWay}) value;
@bindable from;
@bindable placeholder;
@bindable searchParams = {};
@bindable di... |
Implement rdatatype-aware and NoAnswer-aware DNS handling
This will work for CNAME entries because CNAMEs hit by A or AAAA lookups behave like `dig` does - they will trigger a second resultset for the CNAME entry in order to return the IP address.
This also is amended to handle a "NoAnswer" response - i.e. if there a... | import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call t... | import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call t... |
Move serializer into the class so it can be subclassed. | import cPickle as pickle
import logging
import time
class Serializer(object):
"""A pluggable Serializer class"""
name = "default"
def __init__(self, name='default'):
"""Constructor"""
self.ser = logging.getLogger('testserializer')
self.data = {}
self.name = name
def ... | import cPickle as pickle
import logging
import time
ser = logging.getLogger('testserializer')
class Serializer(object):
"""A pluggable Serializer class"""
name = "default"
def __init__(self, name='default'):
"""Constructor"""
self.data = {}
self.name = name
def save_request(... |
Remove unnecessary commented out lines | (function() {
describe('awesome-app.search module', function() {
var $controller,
$scope,
SearchService,
$rootScope,
controller;
beforeEach(function() {
module('awesome-app.search');
inject(function(_$controller_, _SearchServ... | (function() {
describe('awesome-app.search module', function() {
var $controller,
$scope,
SearchService,
$rootScope,
controller,
element;
beforeEach(function() {
module('awesome-app.search');
inject(function(_$con... |
Add logging to see who we can't get the info for | var moment = require('moment');
var userCache = {};
var cacheTimeInMilliseconds = 1000 * 60 * 15;
/**
* Every time a user posts a message, we update their slack profile so we can stay up to date on their profile
* @param {Object} bot
* @param {Object} message
* @param {Object} controller
*/
module.exports = fu... | var moment = require('moment');
var userCache = {};
var cacheTimeInMilliseconds = 1000 * 60 * 15;
/**
* Every time a user posts a message, we update their slack profile so we can stay up to date on their profile
* @param {Object} bot
* @param {Object} message
* @param {Object} controller
*/
module.exports = fu... |
Fix HtlmIFrameSrcDoc test, 27 failing [ci skip] | /*global describe, it*/
var expect = require('../unexpected-with-plugins'),
AssetGraph = require('../../lib/AssetGraph');
describe('relations/HtmlIFrameSrcDoc', function () {
it('should handle a test case with an existing <iframe srcdoc=...> element', function () {
return new AssetGraph({root: __dirnam... | /*global describe, it*/
var expect = require('../unexpected-with-plugins'),
AssetGraph = require('../../lib/AssetGraph');
describe('relations/HtmlIFrameSrcDoc', function () {
it('should handle a test case with an existing <iframe srcdoc=...> element', function () {
return new AssetGraph({root: __dirnam... |
Add client and channel models | '''
Created on Nov 9, 2014
@author: fechnert
'''
import yaml
import logging
import features
class Configuration(dict):
''' Read and provide the yaml config '''
def __init__(self, path):
''' Initialize the file '''
with open(path, 'r') as f:
self.update(yaml.load(f))
class Supe... | '''
Created on Nov 9, 2014
@author: fechnert
'''
import yaml
import logging
import features
class Configuration(dict):
''' Read and provide the yaml config '''
def __init__(self, path):
''' Initialize the file '''
with open(path, 'r') as f:
self.update(yaml.load(f))
class Supe... |
Extend MOP for RayTracer depth sorting. | package codechicken.lib.raytracer;
import net.minecraft.entity.Entity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
public class ExtendedMOP extends MovingObjectPosition implements Comparable<ExtendedMOP>
{
public Object data;
public double dist;
public ExtendedMOP(... | package codechicken.lib.raytracer;
import net.minecraft.entity.Entity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
public class ExtendedMOP extends MovingObjectPosition
{
public Object data;
public ExtendedMOP(Entity entity, Object data)
{
super(entity);
... |
Move some class references to imports. | package gx.realtime;
import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback;
import gx.realtime.RealtimeLoader.InitializeModelCallback;
import gx.realtime.RealtimeLoader.HandleErrorsCallback;
/**
* Options (key/value) for the RealtimeLoader.
*/
public class RealtimeOptions {
private String clientId;
... | package gx.realtime;
import gx.realtime.RealtimeLoader.InitializeModelCallback;
import gx.realtime.RealtimeLoader.HandleErrorsCallback;
/**
* Options (key/value) for the RealtimeLoader.
*/
public class RealtimeOptions {
// Attributes
private String clientId;
private String docId;
private Realt... |
Enable death listener to disable data-emitter | AFRAME.registerComponent('death-listener', {
schema: {
characterId: {default: undefined}
},
init: function () {
const el = this.el;
const data = this.data;
window.addEventListener('characterDestroyed', function (e) {
if(data.characterId === e.detail.characterId) {
if(el.components.s... | AFRAME.registerComponent('death-listener', {
schema: {
characterId: {default: undefined}
},
init: function () {
const el = this.el;
const data = this.data;
window.addEventListener('characterDestroyed', function (e) {
if(data.characterId === e.detail.characterId) {
if(el.components.sp... |
Add proxy settings to NetworkConfig | package netconf
type NetworkConfig struct {
PreCmds []string `yaml:"pre_cmds,omitempty"`
Dns DnsConfig `yaml:"dns,omitempty"`
Interfaces map[string]InterfaceConfig `yaml:"interfaces,omitempty"`
PostCmds []string `yaml:"post_cmds,omitempty"`
HttpProx... | package netconf
type NetworkConfig struct {
PreCmds []string `yaml:"pre_cmds,omitempty"`
Dns DnsConfig `yaml:"dns,omitempty"`
Interfaces map[string]InterfaceConfig `yaml:"interfaces,omitempty"`
PostCmds []string `yaml:"post_cmds,omitempty"`
}
type I... |
Add the asyncio wait_for back in | import asyncio
import json
from discode_server import db
from discode_server import fragments
connected = set()
notified = set()
async def feed(request, ws):
global connected
connected.add(ws)
print("Open WebSockets: ", len(connected))
try:
while True:
if not ws.open:
... | import json
from discode_server import db
from discode_server import fragments
connected = set()
notified = set()
async def feed(request, ws):
global connected
connected.add(ws)
print("Open WebSockets: ", len(connected))
try:
while True:
if not ws.open:
return
... |
Update container to use mock array rather than wrappers | <?php
namespace Michaeljennings\Carpenter\Nexus;
use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;
class Container implements ArrayAccess, IteratorAggregate
{
/**
* The items in the container.
*
* @var array
*/
protected $items = [];
public function __construct(array $items,... | <?php
namespace Michaeljennings\Carpenter\Nexus;
use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;
class Container implements ArrayAccess, IteratorAggregate
{
/**
* @var array
*/
protected $items = [];
public function __construct(array $items, array $config, $wrapper)
{
fo... |
Clear parameters before editing/adding. Before it was been unpossible to call two functions in sequence. | import json
import api
class WWWDomain(api.API):
def __init__(self, auth_handler):
self.url = auth_handler.url
self.sessid = auth_handler.sessid
self.func = 'wwwdomain.edit'
self.out = 'json'
self._clear_params()
def _clear_params(self):
try:
self.p... | import json
import api
class WWWDomain(api.API):
def __init__(self, auth_handler):
self.url = auth_handler.url
self.sessid = auth_handler.sessid
self.func = 'wwwdomain.edit'
self.out = 'json'
self.params = {
'auth' : self.sessid,
'out' : self.out,
... |
[Build] Test for CSS file in webpack.prod | const { resolve } = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = require('config');
const PORT = config.get('server.port');
module.exports = {
entry: '../src/index.jsx',
... | const { resolve } = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = require('config');
const PORT = config.get('server.port');
module.exports = {
entry: '../src/index.jsx',
... |
Add sort order to query results
* Hard coded the sort order for now. | 'use strict';
var _ = require('lodash'),
Promise = require('bluebird');
module.exports = ['data', function (data) {
var filters = function (query) {
var where = data.utils.rangeFilter('Year', query.start, query.end);
return _.assign(where, data.utils.inFilter('Make', query.makes));
};
return {
'... | 'use strict';
var _ = require('lodash'),
Promise = require('bluebird');
module.exports = ['data', function (data) {
var filters = function (query) {
var where = data.utils.rangeFilter('Year', query.start, query.end);
return _.assign(where, data.utils.inFilter('Make', query.makes));
};
return {
'... |
Use dateutil to calculate age of container. | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
from dateutil import (
parser as date_parser,
tz,
)
def list_old_juju_containers(hours):
env = ... | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_out... |
Fix status handling in getRestaurants
The changes in #15 were meant to fix a bug where we were looking at
an incorrect field for the status code of the fetch response.
However, these changes were not thoroughly tested and actually didn't
completely work as coded, because when the response is a success
it does not have... | ;(function () {
/* global fetch: false */
'use strict';
function getRestaurants(coords) {
var fetchUrl = '/restaurants?latitude=' + coords.latitude + '&longitude=' + coords.longitude;
return fetch(fetchUrl)
.then(function(response) {
// handle any errors
if (!response.ok) {
... | ;(function () {
/* global fetch: false */
'use strict';
function getRestaurants(coords) {
var fetchUrl = '/restaurants?latitude=' + coords.latitude + '&longitude=' + coords.longitude;
return fetch(fetchUrl)
.then(function(response) {
return response.json();
}).then(function(response) ... |
Comment out modules with broken tests. | #!/usr/bin/python
import unittest
import doctest
import sys
from optparse import OptionParser
from firmant.utils import get_module
# Import this now to avoid it throwing errors.
import pytz
if __name__ == '__main__':
suite = unittest.TestSuite()
modules = ['firmant.du',
'firmant.extensions',
... | #!/usr/bin/python
import unittest
import doctest
import sys
from optparse import OptionParser
from firmant.utils import get_module
# Import this now to avoid it throwing errors.
import pytz
if __name__ == '__main__':
suite = unittest.TestSuite()
modules = ['firmant.du',
'firmant.extensions',
... |
Remove unnecessary assert from view for Notice home. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.vie... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.vie... |
Allow user to change connection flags | <?php
namespace Ddeboer\Imap;
use Ddeboer\Imap\Exception\AuthenticationFailedException;
class Server
{
protected $hostname;
protected $port;
protected $connection;
protected $mailboxes;
/**
* Constructor
*
* @param string $hostname
* @param int $port
* @param string $... | <?php
namespace Ddeboer\Imap;
use Ddeboer\Imap\Exception\AuthenticationFailedException;
class Server
{
protected $hostname;
protected $port;
protected $connection;
protected $mailboxes;
public function __construct($hostname, $port = '993')
{
if ($port == 993) {
$cert = 's... |
Refresh page after user creation | function viewUsers(view) {
getUsers(
success = function (data) {
//console.log(data);
populateUsersTable(data);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateUsersTable(data) {
var usersHtml = templates.userList(data);
var isEditor = false;... | function viewUsers(view) {
getUsers(
success = function (data) {
//console.log(data);
populateUsersTable(data);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateUsersTable(data) {
var usersHtml = templates.userList(data);
var isEditor = false;... |
Update webpack externals to fix issue with React | import { resolve } from 'path';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
const config = {
entry: {
core: resolve('src', 'core', 'index.js'),
react: resolve('src', 'react'),
},
output: {
filename: '[name].js',
path: resolve('dist'),
library: 'Typewriter',
libraryTar... | import { resolve } from 'path';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
const config = {
entry: {
core: resolve('src', 'core', 'index.js'),
react: resolve('src', 'react'),
},
output: {
filename: '[name].js',
path: resolve('dist'),
library: 'Typewriter',
libraryTar... |
Use a tuple instead of a list for protocol membership test | # -*- coding: utf-8 -*-
import KISSmetrics
from KISSmetrics import request
from urllib3 import PoolManager
class Client:
def __init__(self, key, trk_host=KISSmetrics.TRACKING_HOSTNAME,
trk_proto=KISSmetrics.TRACKING_PROTOCOL):
self.key = key
if trk_proto not in ('http', 'https')... | # -*- coding: utf-8 -*-
import KISSmetrics
from KISSmetrics import request
from urllib3 import PoolManager
class Client:
def __init__(self, key, trk_host=KISSmetrics.TRACKING_HOSTNAME,
trk_proto=KISSmetrics.TRACKING_PROTOCOL):
self.key = key
if trk_proto not in ['http', 'https']... |
Add summary price own components --skip-ci | import React from 'react'
import Helper from '../../helpers'
import SingleComponentItemView from './SingleComponentItemView'
import './ItemView.css'
const ItemView = props => {
const {typeID, name, quantity, components, component_me, facility_me, prices} = props
let price = 0
let cmps = Helper.manufactureQty(co... | import React from 'react'
import Helper from '../../helpers'
import SingleComponentItemView from './SingleComponentItemView'
import './ItemView.css'
const ItemView = props => {
const {typeID, name, quantity, components, component_me, facility_me, prices} = props
const sum = Helper.price(props.price * quantity)
... |
Add long description (from README.md) | #!/usr/bin/env python
import os
from setuptools import setup
def get_long_description():
filename = os.path.join(os.path.dirname(__file__), 'README.md')
with open(filename) as f:
return f.read()
setup(name='pyannotate',
version='1.0.5',
description="PyAnnotate: Auto-generate PEP-484 annot... | #!/usr/bin/env python
from setuptools import setup
setup(name='pyannotate',
version='1.0.5',
description="PyAnnotate: Auto-generate PEP-484 annotations",
author='Dropbox',
author_email='guido@dropbox.com',
url='https://github.com/dropbox/pyannotate',
license='Apache 2.0',
pla... |
Return json, not just a string id | import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log =... | import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log =... |
Validate XLIFF files in tests using the XSD | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Tests\Resources;
use PHPUnit\Framework\TestCase;... | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Tests\Resources;
use PHPUnit\Framework\TestCase;... |
Make component name match file name | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import IconButton from './../molecules/IconButton';
class SocialMediaIcons extends Component {
shareOnFacebook() {
const url = window.location.href;
window.open(`https://www.facebook.com/sharer/sharer.php?... | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import IconButton from './../molecules/IconButton';
class SocialMediaSharing extends Component {
shareOnFacebook() {
const url = window.location.href;
window.open(`https://www.facebook.com/sharer/sharer.ph... |
Configure HTTP and Sockets API | 'use strict';
var _ = require('underscore'),
path = require('path'),
winston = module.parent.require('winston'),
meta = module.parent.require('./meta'),
routes = require('./app/routes'),
sockets = require('./app/sockets'),
emitter = module.parent.require('./emitter')... | 'use strict';
var _ = require('underscore'),
path = require('path'),
winston = module.parent.require('winston'),
meta = module.parent.require('./meta'),
routes = require('./app/routes'),
emitter = module.parent.require('./emitter'),
settings = null,
namespace = '... |
Add default values to get field values | /*
* Copyright 2011 Splunk, 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 agreed to... | /*
* Copyright 2011 Splunk, 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 agreed to... |
Remove old comment, and unessary if logic | import React from "react";
import ReactDOM from "react-dom";
import $ from "jquery";
import Backbone from "backbone";
export default React.createClass({
displayName: "Tag",
propTypes: {
tag: React.PropTypes.instanceOf(Backbone.Model).isRequired,
renderLinks: React.PropTypes.bool
},
ge... | import React from "react";
import ReactDOM from "react-dom";
import $ from "jquery";
import Backbone from "backbone";
export default React.createClass({
displayName: "Tag",
propTypes: {
tag: React.PropTypes.instanceOf(Backbone.Model).isRequired,
renderLinks: React.PropTypes.bool
},
ge... |
Add in windows drive pattern match.
As title. | from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
from numba import cuda
from numba.core import config
class MyError(Exception):
pass
regex_pattern = (
r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+'
)
class TestUserExc(SerialMixin, unittest.TestCase):
de... | from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
from numba import cuda
from numba.core import config
class MyError(Exception):
pass
regex_pattern = (
r'In function [\'"]test_exc[\'"], file [\.\/\\\-a-zA-Z_0-9]+, line \d+'
)
class TestUserExc(SerialMixin, unittest.TestCase):
def ... |
Support of comparison null values in object properties | package lv.ctco.cukesrest.internal.matchers;
import org.hamcrest.*;
import java.math.*;
public class EqualToIgnoringTypeMatcher {
public static Matcher<String> equalToIgnoringType(final String value) {
return new BaseMatcher<String>() {
@Override
public void describeTo(Descripti... | package lv.ctco.cukesrest.internal.matchers;
import org.hamcrest.*;
import java.math.*;
public class EqualToIgnoringTypeMatcher {
public static Matcher<String> equalToIgnoringType(final String value) {
return new BaseMatcher<String>() {
@Override
public void describeTo(Descripti... |
Check if there are associated acts before querying for them | from artgraph.node import NodeTypes
from artgraph.plugins import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
@staticmethod
def get_target_node_type():
return NodeTypes.ARTIST
def get_nodes(self):
from artgraph.node import Node, N... | from artgraph.node import NodeTypes
from artgraph.plugins import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
@staticmethod
def get_target_node_type():
return NodeTypes.ARTIST
def get_nodes(self):
from artgraph.node import Node, N... |
[JUnit] Remove cucumber.api glue annotation check | package io.cucumber.junit;
import io.cucumber.core.exception.CucumberException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
final class Assertions {
private Assertions() {
}
static void assertNoCucumberAnnotatedMethods(Class clazz) {
for (Method method : clazz.getDec... | package io.cucumber.junit;
import io.cucumber.core.exception.CucumberException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
final class Assertions {
private Assertions() {
}
static void assertNoCucumberAnnotatedMethods(Class clazz) {
for (Method method : clazz.getDec... |
Check and makse sure we have no dispatcher object | <?php
namespace Conduit\Middleware;
use Phly\Conduit\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Aura\Router\Router;
use Aura\Dispatcher\Dispatcher;
use Aura\Di\Container;
class ApplicationMiddleware implements MiddlewareInterface
{
private $contai... | <?php
namespace Conduit\Middleware;
use Phly\Conduit\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Aura\Router\Router;
use Aura\Dispatcher\Dispatcher;
use Aura\Di\Container;
class ApplicationMiddleware implements MiddlewareInterface
{
private $contai... |
Set cov-core dependency to 1.9 | import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long... | import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long... |
Fix missing semi-colon bug in javascript file | import 'jquery-ui-dist/jquery-ui';
$(() => {
// Is there already one prefix section on this Phase?
//
// draggableSections - A jQuery object, the sortable element.
//
// Returns Boolean
function prefixSectionExists(draggableSections) {
return !!draggableSections
.has('[data-modifiable=true]:nth-c... | import 'jquery-ui-dist/jquery-ui';
$(() => {
// Is there already one prefix section on this Phase?
//
// draggableSections - A jQuery object, the sortable element.
//
// Returns Boolean
function prefixSectionExists(draggableSections) {
return !!draggableSections
.has('[data-modifiable=true]:nth-c... |
Fix typo in test name | package com.genymobile.scrcpy;
import junit.framework.Assert;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
public class StringUtilsTest {
@Test
@SuppressWarnings("checkstyle:MagicNumber")
public void testUtf8Truncate() {
String s = "aÉbÔc";
byte[] utf8 = s.getBytes(S... | package com.genymobile.scrcpy;
import junit.framework.Assert;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
public class StringUtilsTest {
@Test
@SuppressWarnings("checkstyle:MagicNumber")
public void testUtf8Trucate() {
String s = "aÉbÔc";
byte[] utf8 = s.getBytes(St... |
Use github auth token for api.github.com | <?php
namespace PharIo\Phive;
class CurlConfigBuilder {
/**
* @var Environment
*/
private $environment;
/**
* @var PhiveVersion
*/
private $phiveVersion;
/**
* @param Environment $environment
* @param PhiveVersion $phiveVersion
*/
public function __construc... | <?php
namespace PharIo\Phive;
class CurlConfigBuilder {
/**
* @var Environment
*/
private $environment;
/**
* @var PhiveVersion
*/
private $phiveVersion;
/**
* @param Environment $environment
* @param PhiveVersion $phiveVersion
*/
public function __construc... |
Address review concerns: allow range requirements, specify requirments file path explicitly, ... | import os
import re
REQUIREMENT_RE = re.compile(r'^(([^=]+)[=<>]+[^#]+)(#.*)?$')
def update_pins(setup_args):
# Use requirements and constraints to set version pins
packages = set()
install_dir = os.path.dirname(__file__)
with open(os.path.join(install_dir, 'requirements.txt')) as requirements:
... | import os
import re
def update_pins(setup_args):
# Use requirements and constraints to set version pins
packages = set()
with open('./requirements.txt') as requirements:
for r in requirements:
if r.lower().strip() == 'dallinger':
continue
if not r.startswith... |
Add QA skip for import ordering | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
... | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
... |
Fix issue detected by scrutinizer | <?php
namespace Vision\Hydrator\Strategy;
use Vision\Annotation\Paragraph;
use Vision\Annotation\Symbol;
use Vision\Annotation\Word;
use Zend\Hydrator\Strategy\StrategyInterface;
class SymbolsStrategy implements StrategyInterface
{
/**
* @var TextPropertyStrategy
*/
protected $textPropertyStrategy;... | <?php
namespace Vision\Hydrator\Strategy;
use Vision\Annotation\Paragraph;
use Vision\Annotation\Symbol;
use Vision\Annotation\Word;
use Zend\Hydrator\Strategy\StrategyInterface;
class SymbolsStrategy implements StrategyInterface
{
/**
* @var TextPropertyStrategy
*/
protected $textPropertyStrategy;... |
Use new create() factory function | 'use strict';
/* eslint-env node */
module.exports = {
name: 'ember-cli-eslint',
// TODO: Disable this (or set it to return false) before committing
isDevelopingAddon: function() {
return false;
},
// instructs ember-cli-qunit and ember-cli-mocha to
// disable their lintTree implementations (which u... | 'use strict';
/* eslint-env node */
module.exports = {
name: 'ember-cli-eslint',
// TODO: Disable this (or set it to return false) before committing
isDevelopingAddon: function() {
return false;
},
// instructs ember-cli-qunit and ember-cli-mocha to
// disable their lintTree implementations (which u... |
Fix error in delta_minutes, use timedelta.total_seconds()/60 instead of timedelta.seconds/60. | from __future__ import unicode_literals
from config import settings
import os
import re
import string
import pytz
def clear_screen():
# Clear screen
os.system(['clear', 'cls'][os.name == 'nt'])
def print_obj(obj):
for attr, val in obj.__dict__.iteritems():
print "{0}: {1}".format(attr, val)
d... | from __future__ import unicode_literals
from config import settings
import os
import re
import string
import pytz
def clear_screen():
# Clear screen
os.system(['clear', 'cls'][os.name == 'nt'])
def print_obj(obj):
for attr, val in obj.__dict__.iteritems():
print "{0}: {1}".format(attr, val)
d... |
Fix employee test to check for returned result keys | import { expect } from 'chai';
import util from './util';
describe('Employees API', () => {
describe('fetch', () => {
it('should get employee list', (done) => {
const fsapi = util.getFullSlate();
fsapi.employees()
.then((employees) => {
expect(employees).to.be.an('array');
... | import { expect } from 'chai';
import util from './util';
describe('Employees API', () => {
describe('fetch', () => {
it('should get employee list', (done) => {
const fsapi = util.getFullSlate();
fsapi.employees()
.then((employees) => {
expect(employees).to.be.an('array');
... |
Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached` | # coding: utf-8
from django.conf import settings
DEFAULTS = {
"SPEEDINFO_TESTS": False,
"SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached",
"SPEEDINFO_STORAGE": None,
"SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
"SPEEDINFO_PROFILING_CONDITIONS": [],
"SPEEDINFO_EXCLUDE_URLS": [],
"SPE... | # coding: utf-8
from django.conf import settings
DEFAULTS = {
"SPEEDINFO_TESTS": False,
"SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached",
"SPEEDINFO_STORAGE": None,
"SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
"SPEEDINFO_PROFILING_CONDITIONS": [],
"SPEEDINFO_EXCLUDE_URLS": [],
"SPEE... |
Update List View Item View with live urls. Waiting for API to get more data. | app.views.PlanListView = Backbone.View.extend({
tagName:'ul',
className:'table-view',
initialize:function () {
var self = this;
this.model.on("reset", this.render, this);
this.model.on("add", function (plan) {
self.$el.append(new app.views.PlanListItemView({model:plan}).r... | app.views.PlanListView = Backbone.View.extend({
tagName:'ul',
className:'table-view',
initialize:function () {
var self = this;
this.model.on("reset", this.render, this);
this.model.on("add", function (plan) {
self.$el.append(new app.views.PlanListItemView({model:plan}).r... |
Add done flag to experiment. | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: ... | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: ... |
Use https for artworks on BOS | //
// FRAMES
//
// Rename plugins to extensions
db.Frame.update({}, { $rename: { 'plugins': 'extensions'}}, {multi: 1});
// Replace embedded current artwork with a relationship
db.Frame.find().snapshot().forEach(
function (elem) {
if (elem._current_artwork) {
db.Frame.update(
{... | //
// FRAMES
//
// Rename plugins to extensions
db.Frame.update({}, { $rename: { 'plugins': 'extensions'}}, {multi: 1});
// Replace embedded current artwork with a relationship
db.Frame.find().snapshot().forEach(
function (elem) {
if (elem._current_artwork) {
db.Frame.update(
{... |
Set development status to stable
Thanks Uri Rodberg for the suggestion. | from setuptools import setup, find_packages
setup(
name='sorl-thumbnail',
use_scm_version=True,
description='Thumbnails for Django',
long_description=open('README.rst').read(),
author="Mikko Hellsing",
author_email='mikko@aino.se',
maintainer="Jazzband",
maintainer_email="roadies@jazzba... | from setuptools import setup, find_packages
setup(
name='sorl-thumbnail',
use_scm_version=True,
description='Thumbnails for Django',
long_description=open('README.rst').read(),
author="Mikko Hellsing",
author_email='mikko@aino.se',
maintainer="Jazzband",
maintainer_email="roadies@jazzba... |
Trim both expected and actual content in assertion
In order to prevent silly errors that may be caused by the presence or absence of a newline character at the end of fixtures and/or HTTP responses, we trim both the expected and the actuel content before passing them to the PHPUnit assertion. | <?php
namespace Tests;
use PHPUnit\Framework\Assert as PHPUnit;
use Illuminate\Foundation\Testing\TestResponse;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
function setUp()
{
parent::setUp();
// Defin... | <?php
namespace Tests;
use PHPUnit\Framework\Assert as PHPUnit;
use Illuminate\Foundation\Testing\TestResponse;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
function setUp()
{
parent::setUp();
// Defin... |
Add content type for proper PyPI rendering | # -*- coding: utf-8 -*-
import codecs
import re
import sys
from setuptools import setup
def get_version():
return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version')
setup(name = "aiodns",
version = get_ve... | # -*- coding: utf-8 -*-
import codecs
import re
import sys
from setuptools import setup
def get_version():
return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version')
setup(name = "aiodns",
version = get_ve... |
Change the wording of the text in the box on the /equality page. | define([], function() {
return ["$timeout", "$rootScope", "api", function($timeout, $rootScope, api) {
return {
scope: {
state: "=",
questionDoc: "=",
editorMode: "=",
},
restrict: "A",
templateUrl: "/partials/... | define([], function() {
return ["$timeout", "$rootScope", "api", function($timeout, $rootScope, api) {
return {
scope: {
state: "=",
questionDoc: "=",
editorMode: "=",
},
restrict: "A",
templateUrl: "/partials/... |
Create basic password reset form | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[... | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[... |
Add term-missing to coverage call | from setuptools import setup, find_packages, Command
version = __import__('eemeter').get_version()
long_description = "Standard methods for calculating energy efficiency savings."
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass... | from setuptools import setup, find_packages, Command
version = __import__('eemeter').get_version()
long_description = "Standard methods for calculating energy efficiency savings."
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass... |
Create archive folder if it does not exist. | from imaplib import IMAP4, IMAP4_SSL
from .base import EmailTransport, MessageParseError
class ImapTransport(EmailTransport):
def __init__(self, hostname, port=None, ssl=False, archive=''):
self.hostname = hostname
self.port = port
self.archive = archive
if ssl:
self.t... | from imaplib import IMAP4, IMAP4_SSL
from .base import EmailTransport, MessageParseError
class ImapTransport(EmailTransport):
def __init__(self, hostname, port=None, ssl=False, archive=''):
self.hostname = hostname
self.port = port
self.archive = archive
if ssl:
self.t... |
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later. | # mode: run
# tag: generator
import cython
import sys
def test_generator_frame_cycle():
"""
>>> test_generator_frame_cycle()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g ... | # mode: run
# tag: generator
import cython
import sys
def test_generator_frame_cycle():
"""
>>> test_generator_frame_cycle()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g ... |
Remove icon from plain email link shortcode. | <?php
namespace Carawebs\Contact\Shortcodes;
use Carawebs\Contact\Traits\CssClasses;
/**
* Hook function for Email Button shortcode
*/
class EmailLink extends ContactAction {
use CssClasses;
public function __construct()
{
parent::__construct();
$this->setDefaultContactStrings([
... | <?php
namespace Carawebs\Contact\Shortcodes;
use Carawebs\Contact\Traits\CssClasses;
/**
* Hook function for Email Button shortcode
*/
class EmailLink extends ContactAction {
use CssClasses;
public function __construct()
{
parent::__construct();
$this->setDefaultContactStrings([
... |
Update Request, only return response time
Request: remove status_code and get_response_time() and only return the
response time on do() function | import requests
from time import time
class Client:
def __init__(self, host, requests, do_requests_counter):
self.host = host
self.requests = requests
self.counter = do_requests_counter
class Request:
GET = 'get'
POST = 'post'
def __init__(self, url, type=GET, data=None):
... | import requests
from time import time
class Client:
def __init__(self, host, requests, do_requests_counter):
self.host = host
self.requests = requests
self.counter = do_requests_counter
class Request:
GET = 'get'
POST = 'post'
def __init__(self, url, type=GET, data=None):
... |
Fix search indexing populating thread wordcount | <?php
class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread
{
protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null)
{
$wordcount = 0;
if (!empty($data['threadmark_count'... | <?php
class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread
{
protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null)
{
$wordcount = 0;
if (!empty($data['threadmark_count'... |
Use a lodash filter instead
- Map doesn't work the way I expected. | /* global define */
(function() {
'use strict';
define(['lodash', 'moment'], function(_, moment) {
var ToolController = function($q, $timeout, $location, $scope, ClusterService, ToolService) {
if (ClusterService.clusterId === null) {
$location.path('/first');
... | /* global define */
(function() {
'use strict';
define(['lodash', 'moment'], function(_, moment) {
var ToolController = function($q, $timeout, $location, $scope, ClusterService, ToolService) {
if (ClusterService.clusterId === null) {
$location.path('/first');
... |
Fix channel definition in add method | # Module: node
# Date: ...
# Author: ...
"""Node
...
"""
from .client import Client
from .server import Server
from circuits import handler, BaseComponent
class Node(BaseComponent):
"""Node
...
"""
channel = "node"
def __init__(self, bind=None, channel=channel, **kwargs):
su... | # Module: node
# Date: ...
# Author: ...
"""Node
...
"""
from .client import Client
from .server import Server
from circuits import handler, BaseComponent
class Node(BaseComponent):
"""Node
...
"""
channel = "node"
def __init__(self, bind=None, channel=channel, **kwargs):
su... |
Create Tasks on a tasklist | <?php namespace Rossedman\Teamwork;
use Rossedman\Teamwork\Traits\RestfulTrait;
class Tasklist extends AbstractObject {
protected $wrapper = 'todo-list';
protected $endpoint = 'tasklists';
/**
* GET /tasklists/{$id}.json
* @return mixed
*/
public function find()
{
retur... | <?php namespace Rossedman\Teamwork;
use Rossedman\Teamwork\Traits\RestfulTrait;
class Tasklist extends AbstractObject {
protected $wrapper = 'todo-list';
protected $endpoint = 'tasklists';
/**
* GET /tasklists/{$id}.json
* @return mixed
*/
public function find()
{
retur... |
Store cleanet phone number for use in SQL extracts | # -*- coding: utf-8 -*-
from openerp import models, fields, api
import string
class ResPartner(models.Model):
_inherit = ['res.partner']
mobile_clean = fields.Char(compute='_compute_mobile_clean', store=True)
@api.multi
@api.depends('mobile','phone')
def _compute_mobile_clean(self):
allo... | # -*- coding: utf-8 -*-
from openerp import models, fields, api
import string
class ResPartner(models.Model):
_inherit = ['res.partner']
mobile_clean = fields.Char(compute='_compute_mobile_clean')
@api.multi
@api.depends('mobile')
def _compute_mobile_clean(self):
allowed_chars = '+012345... |
FIx issue with oneway methods | import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.Client(ip, int(port))
else:
statsd_client = None
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine... | import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.Client(ip, int(port))
else:
statsd_client = None
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine... |
Add js static analysis as recognised test option | <?php
namespace SimplyTestable\WebClientBundle\Model;
class TestOptions {
private $testTypes = array();
private $testTypeMap = array(
'html-validation' => 'HTML validation',
'css-validation' => 'CSS validation',
'js-static-analysis' => 'JS static analysis'
);
... | <?php
namespace SimplyTestable\WebClientBundle\Model;
class TestOptions {
private $testTypes = array();
private $testTypeMap = array(
'html-validation' => 'HTML validation',
'css-validation' => 'CSS validation'
);
/**
*
* @param string $testType... |
Change to support name change | package com.boundary.camel.component.url;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Ignore;
imp... | package com.boundary.camel.component.http;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Ignore;
im... |
Use MutationObserver for expanded stories and jQuery for collapsed ones | var storyListener = function (modal) {
var observer = new MutationObserver(function (mutations) {
mutations.forEach(handleMutationEvents);
});
var handleMutationEvents = function handleMutationEvents(mutation) {
Array.prototype.forEach.call(mutation.addedNodes, addListenersInNode);
... | var storyListener = function (modal) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
var observer = new MutationObserver(function (mutations) {
mutations.forEach(handleMutatio... |
Update shoppingcart setup to use updated tax calculation | <?php
class CustomisableProductShoppingCart extends Extension {
/**
* Augment setup to get item price
*
*/
public function augmentSetup() {
foreach($this->owner->Items as $item) {
if($item->Customisations && is_array($item->Customisations)) {
$base_price = $... | <?php
class CustomisableProductShoppingCart extends Extension {
/**
* Augment setup to get item price
*
*/
public function augmentSetup() {
foreach($this->owner->Items as $item) {
if($item->Customisations && is_array($item->Customisations)) {
$base_price = $... |
Fix ReferenceError in saveAs polyfill | var save = (function() {
"use strict";
// saveAs from https://gist.github.com/MrSwitch/3552985
var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) {
return window.navigator.msSaveBlob(b, n);
} : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function (... | var save = (function() {
"use strict";
// saveAs from https://gist.github.com/MrSwitch/3552985
var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) {
return window.navigator.msSaveBlob(b, n);
} : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function (... |
Introduce scope_types in pause server policy
oslo.policy introduced the scope_type feature which can
control the access level at system-level and project-level.
- https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope
- http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens/sy... | # Copyright 2016 Cloudbase Solutions Srl
# 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 r... | # Copyright 2016 Cloudbase Solutions Srl
# 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 r... |
Change symbols generation and checks | var LOCK = false;
function print(text, nextAction) {
if (text) {
LOCK = true;
var display = document.getElementById("display");
display.innerHTML = display.innerHTML + text.substr(0, 1);
display.scrollTop = display.scrollHeight;
var newText = text.substring(1, text.length);
... | var LOCK = false;
function print(text, nextAction) {
if (text) {
LOCK = true;
var display = document.getElementById("display");
display.innerHTML = display.innerHTML + text.substr(0, 1);
display.scrollTop = display.scrollHeight;
var newText = text.substring(1, text.length);
... |
Fix unicode error in series | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to ma... | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to ma... |
Add entry point for readme | #!/usr/bin/env node
import yargs from 'yargs';
import { head, pipe, cond, equals, prop } from 'ramda';
import { reject } from 'bluebird';
import build from './build';
import run from './run';
import init from './init';
import publish from './publish';
import boilerplate from './boilerplate';
import readme from './read... | #!/usr/bin/env node
import yargs from 'yargs';
import { head, pipe, cond, equals, prop } from 'ramda';
import { reject } from 'bluebird';
import build from './build';
import run from './run';
import init from './init';
import publish from './publish';
import boilerplate from './boilerplate';
const commandEquals = val... |
Fix AMD define syntax (I hope). | /*globals define, module, window */
// This module contains functions for converting milliseconds
// to and from CSS time strings.
(function () {
'use strict';
var regex = /^([\-\+]?[0-9]+(\.[0-9]+)?)(m?s)$/,
functions = {
from: from,
to: to
};
exportFunctions();
// Public ... | /*globals define, module, window */
// This module contains functions for converting milliseconds
// to and from CSS time strings.
(function () {
'use strict';
var regex = /^([\-\+]?[0-9]+(\.[0-9]+)?)(m?s)$/,
functions = {
from: from,
to: to
};
exportFunctions();
// Public ... |
command: Fix comparaison of command (== 0x11) for half lx
I assume author @circuitdb wanted this in:
https://github.com/miroRucka/bh1750/pull/3
Change-Id: Ic8666c0b735a970f0ff82fedc4e654969a1a0076
Origin: https://github.com/miroRucka/bh1750/pull/12
Signed-off-by: Philippe Coval <e55eb7f5ae8caa4c9c0d2fc7cb5c13ca6c4cd... | var i2c = require('i2c');
var _ = require('lodash');
var utils = require('./utils');
var BH1750 = function (opts) {
this.options = _.extend({}, {
address: 0x23,
device: '/dev/i2c-1',
command: 0x10,
length: 2
}, opts);
this.verbose = this.options.verbose || false;
this.wi... | var i2c = require('i2c');
var _ = require('lodash');
var utils = require('./utils');
var BH1750 = function (opts) {
this.options = _.extend({}, {
address: 0x23,
device: '/dev/i2c-1',
command: 0x10,
length: 2
}, opts);
this.verbose = this.options.verbose || false;
this.wi... |
Fix filters in storeConfig: they where shared across multiple stores
Problem was that storeConfig is an object and thus modified by reference | Ext.define('Densa.overrides.HasMany', {
override: 'Ext.data.association.HasMany',
/**
* Allow filters in storeConfig
*
* Original overrides filters with filter
*/
createStore: function() {
var that = this,
associatedModel = that.associatedModel,
... | Ext.define('Densa.overrides.HasMany', {
override: 'Ext.data.association.HasMany',
/**
* Allow filters in storeConfig
*
* Original overrides filters with filter
*/
createStore: function() {
var that = this,
associatedModel = that.associatedModel,
... |
Revert "revert part of 27cd680"
c491bbc2302ac7c95c180d31845c643804fa30d3 | import copy
import os
from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired
# This env stuff is to catch glibc errors, because
# it apparently prints to /dev/tty instead of stderr.
# (see http://stackoverflow.com/a/27797579)
ENV = copy.copy(os.environ)
ENV["LIBC_FATAL_STDERR_"] = "1"
def ru... | import shlex
import copy
import os
from subprocess import STDOUT, run as _run, CalledProcessError, TimeoutExpired
# This env stuff is to catch glibc errors, because
# it apparently prints to /dev/tty instead of stderr.
# (see http://stackoverflow.com/a/27797579)
ENV = copy.copy(os.environ)
ENV["LIBC_FATAL_STDERR_"] =... |
Comment out logger until resolved properly | # -*- coding: utf-8 -*-
import logging
from django.core.exceptions import PermissionDenied
from tastypie.resources import ModelResource, ALL
from tastypie.authorization import Authorization
from apps.authentication.models import OnlineUser as User
from apps.api.rfid.auth import RfidAuthentication
class UserResourc... | # -*- coding: utf-8 -*-
import logging
from django.core.exceptions import PermissionDenied
from tastypie.resources import ModelResource, ALL
from tastypie.authorization import Authorization
from apps.authentication.models import OnlineUser as User
from apps.api.rfid.auth import RfidAuthentication
class UserResourc... |
Handle empty fastq_screen files properly. | import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().... | import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().... |
Add the 401 Unauthorized when no username is detected, thus no user
is logged in. This is the most basic form of permissions, where any
user can log in and do anything. | from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.meth... | from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.meth... |
Remove extraneous logging and bad param | import requests
import urllib
import urlparse
from st2actions.runners.pythonrunner import Action
class ActiveCampaignAction(Action):
def run(self, **kwargs):
if kwargs['api_key'] is None:
kwargs['api_key'] = self.config['api_key']
return self._get_request(kwargs)
def _get_r... | import requests
import urllib
import urlparse
from st2actions.runners.pythonrunner import Action
class ActiveCampaignAction(Action):
def run(self, **kwargs):
if kwargs['api_key'] is None:
kwargs['api_key'] = self.config['api_key']
return self._get_request(kwargs)
def _get_r... |
Remove old code that was never documented or used. | <?php
namespace Illuminate\Foundation\Testing;
use Mockery;
use PHPUnit_Framework_TestCase;
abstract class TestCase extends PHPUnit_Framework_TestCase
{
use ApplicationTrait, AssertionsTrait, CrawlerTrait;
/**
* The callbacks that should be run before the application is destroyed.
*
* @var ar... | <?php
namespace Illuminate\Foundation\Testing;
use Mockery;
use PHPUnit_Framework_TestCase;
abstract class TestCase extends PHPUnit_Framework_TestCase
{
use ApplicationTrait, AssertionsTrait, CrawlerTrait;
/**
* The Eloquent factory instance.
*
* @var \Illuminate\Database\Eloquent\Factory
... |
Comment out isomorphic fetch because of error message | const submitAjaxFormRequest = function(formObjectName) {
return {
type: 'SUBMIT_AJAX_FORM_REQUEST',
formObjectName
}
}
const submitAjaxFormFailure = function(error, formObjectName) {
return {
type: 'SUBMIT_AJAX_FORM_FAILURE',
error,
formObjectName
}
}
const submitAjaxFormSuccess = function(r... | const submitAjaxFormRequest = function(formObjectName) {
return {
type: 'SUBMIT_AJAX_FORM_REQUEST',
formObjectName
}
}
const submitAjaxFormFailure = function(error, formObjectName) {
return {
type: 'SUBMIT_AJAX_FORM_FAILURE',
error,
formObjectName
}
}
const submitAjaxFormSuccess = function(r... |
Drop the should in spec names | <?php
namespace spec\Raekke\Utils;
use PHPSpec2\ObjectBehavior;
class Collection extends ObjectBehavior
{
function it_behaves_like_an_array()
{
$this->shouldHaveType('Countable');
$this->shouldHaveType('IteratorAggregate');
}
function it_returns_default_value_if_key_isnt_set()
{
... | <?php
namespace spec\Raekke\Utils;
use PHPSpec2\ObjectBehavior;
class Collection extends ObjectBehavior
{
function it_should_behave_like_an_array()
{
$this->shouldHaveType('Countable');
$this->shouldHaveType('IteratorAggregate');
}
function it_returns_default_value_if_key_isnt_set()
... |
Fix error in cachebuster for workspace show sidebar | chorus.views.WorkspaceShowSidebar = chorus.views.Sidebar.extend({
constructorName: "WorkspaceShowSidebarView",
className:"workspace_show_sidebar",
subviews: {
".workspace_member_list": "workspaceMemberList"
},
setup:function () {
this.bindings.add(this.model, "image:change", this.r... | chorus.views.WorkspaceShowSidebar = chorus.views.Sidebar.extend({
constructorName: "WorkspaceShowSidebarView",
className:"workspace_show_sidebar",
subviews: {
".workspace_member_list": "workspaceMemberList"
},
setup:function () {
this.bindings.add(this.model, "image:change", this.r... |
Fix silly close error, wrong connection | #! /usr/bin/env python
from pika import BlockingConnection, ConnectionParameters
from psycopg2 import connect
RABBIT_MQ_HOST = '54.76.183.35'
RABBIT_MQ_PORT = 5672
POSTGRES_HOST = 'microservices.cc9uedlzx2lk.eu-west-1.rds.amazonaws.com'
POSTGRES_DATABASE = 'micro'
POSTGRES_USER = 'microservices'
POSTGRES_PASSWORD = ... | #! /usr/bin/env python
from pika import BlockingConnection, ConnectionParameters
from psycopg2 import connect
RABBIT_MQ_HOST = '54.76.183.35'
RABBIT_MQ_PORT = 5672
POSTGRES_HOST = 'microservices.cc9uedlzx2lk.eu-west-1.rds.amazonaws.com'
POSTGRES_DATABASE = 'micro'
POSTGRES_USER = 'microservices'
POSTGRES_PASSWORD = ... |
Fix display mode for block formulas | var katex = require("katex");
module.exports = {
book: {
assets: "./static",
js: [],
css: [
"katex.min.css"
]
},
ebook: {
assets: "./static",
css: [
"katex.min.css"
]
},
blocks: {
math: {
shortcuts: ... | var katex = require("katex");
module.exports = {
book: {
assets: "./static",
js: [],
css: [
"katex.min.css"
]
},
ebook: {
assets: "./static",
css: [
"katex.min.css"
]
},
blocks: {
math: {
shortcuts: ... |
Add more characters to escaping | <?php
/*
* This file is part of Alom Graphviz.
* (c) Alexandre Salomé <alexandre.salome@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alom\Graphviz;
/**
* Base class for Graphviz instructions.
*
* @author... | <?php
/*
* This file is part of Alom Graphviz.
* (c) Alexandre Salomé <alexandre.salome@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alom\Graphviz;
/**
* Base class for Graphviz instructions.
*
* @author... |
Add request parameter to backend.authenticate
Without this, the signature of our custom backend does not
match that of the function call. This signature is tested
in django.contrib.auth.authenticate here: https://github.com/django/django/blob/fdf209eab8949ddc345aa0212b349c79fc6fdebb/django/contrib/auth/__init__.py#L69... | # -*- coding: utf-8 -*-
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.models import User
from apps.user.models import ItsiUser, ConcordUser
class SSOAuthenticationBackend(BaseBackend):
"""
A custom authentication back-end f... | # -*- coding: utf-8 -*-
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.models import User
from apps.user.models import ItsiUser, ConcordUser
class SSOAuthenticationBackend(BaseBackend):
"""
A custom authentication back-end f... |
Update for compat w/ djangorestframework 3.2
Change request.QUERY_PARAMS to request.query_params | """
Provides JSONP rendering support.
"""
from __future__ import unicode_literals
from rest_framework.renderers import JSONRenderer
class JSONPRenderer(JSONRenderer):
"""
Renderer which serializes to json,
wrapping the json output in a callback function.
"""
media_type = 'application/javascript'... | """
Provides JSONP rendering support.
"""
from __future__ import unicode_literals
from rest_framework.renderers import JSONRenderer
class JSONPRenderer(JSONRenderer):
"""
Renderer which serializes to json,
wrapping the json output in a callback function.
"""
media_type = 'application/javascript'... |
Update tail command tests to check for backslashes | <?php
namespace Spatie\Tail\Tests;
class TailCommandTest extends TestCase
{
/** @test */
public function it_will_throw_an_exception_if_the_given_environment_is_not_configured()
{
$this->expectExceptionMessageMatches('/^No configuration set/');
$this->artisan('tail', [
'environ... | <?php
namespace Spatie\Tail\Tests;
class TailCommandTest extends TestCase
{
/** @test */
public function it_will_throw_an_exception_if_the_given_environment_is_not_configured()
{
$this->expectExceptionMessageMatches('/^No configuration set/');
$this->artisan('tail', [
'environ... |
Add support for boolean type
git-svn-id: 7e8def7d4256e953abb468098d8cb9b4faff0c63@5739 12255794-1b5b-4525-b599-b0510597569d | package com.arondor.common.reflection.reflect.instantiator;
import java.util.HashMap;
import java.util.Map;
public class FastPrimitiveConverter
{
private interface PrimitiveConverter
{
Object convert(String value);
}
private final Map<String, PrimitiveConverter> primitiveConverterMap = new Ha... | package com.arondor.common.reflection.reflect.instantiator;
import java.util.HashMap;
import java.util.Map;
public class FastPrimitiveConverter
{
private interface PrimitiveConverter
{
Object convert(String value);
}
private final Map<String, PrimitiveConverter> primitiveConverterMap = new Ha... |
Set Sequencer's HighWaterMark to 0 | package bench.pubsub;
import org.zeromq.ZMQ;
/**
* This sequencer simply reads from a PULL socket and forwards the
* message to the PUB socket.
*/
public class ZeroMQSequencer {
public static void main(String[] args) throws Exception {
new Thread(new Sequencer()).start();
}
public static cla... | package bench.pubsub;
import org.zeromq.ZMQ;
/**
* This sequencer simply reads from a PULL socket and forwards the
* message to the PUB socket.
*/
public class ZeroMQSequencer {
public static void main (String[] args) throws Exception {
new Thread(new Sequencer()).start();
}
public stati... |
Fix name of macosx backend. | #! /usr/bin/env python
# Last Change: Mon Dec 08 03:00 PM 2008 J
from os.path import join
import os
import warnings
from setuphelp import info_factory, NotFoundError
def configuration(parent_package='', top_path=None, package_name='soundio'):
from numpy.distutils.misc_util import Configuration
config = Confi... | #! /usr/bin/env python
# Last Change: Mon Dec 08 03:00 PM 2008 J
from os.path import join
import os
import warnings
from setuphelp import info_factory, NotFoundError
def configuration(parent_package='', top_path=None, package_name='soundio'):
from numpy.distutils.misc_util import Configuration
config = Confi... |
Update path to work on all SOs | 'use strict'
const path = require('path')
const webpack = require('webpack')
const validate = require('webpack-validator')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = validate({
entry: path.join('.', 'src', 'index.js'),
output: {
path: 'dist',
filename: '<%= camelNa... | 'use strict'
const path = require('path')
const webpack = require('webpack')
const validate = require('webpack-validator')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = validate({
entry: './src/index.js',
output: {
path: 'dist',
filename: '<%= camelName %>.js',
li... |
Remove effect classes after animations complete so they can be added again if needed | (function ($) {
$.fn.animateCSS = function (effect, delay, callback) {
// Return this to maintain chainability
return this.each(function () {
// Cache $(this) for speed
var $this = $(this);
// Check if delay exists or if it's a callback
if (!delay ... | (function ($) {
$.fn.animateCSS = function (effect, delay, callback) {
// Return this to maintain chainability
return this.each(function () {
// Cache $(this) for speed
var $this = $(this);
// Check if delay exists or if it's a callback
if (!delay ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.