text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Remove field which was never accessed | package uk.ac.ebi.atlas.profiles.baseline;
import com.google.common.base.Joiner;
import uk.ac.ebi.atlas.model.experiment.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.experiment.baseline.FactorGroup;
import uk.ac.ebi.atlas.profiles.ExpressionsRowRawDeserializer;
import java.util.List;
import java.util.Que... |
package uk.ac.ebi.atlas.profiles.baseline;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import uk.ac.ebi.atlas.model.experiment.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.experiment.baseline.FactorGroup;
import uk.ac.ebi.atlas.profiles.ExpressionsRowRawDeserializer;... |
Update LoginForm to match reality | import logging
from django import forms
from django.contrib.auth import forms as authforms
from ..models import UserProfile
logger = logging.getLogger(__name__)
class LoginForm(forms.Form):
nick = forms.CharField(label="Nick", max_length=25)
password = forms.CharField(
label="Heslo", max_length=100... | import logging
from django import forms
from django.contrib.auth import forms as authforms
from ..models import UserProfile
logger = logging.getLogger(__name__)
class LoginForm(forms.Form):
nick = forms.CharField(label="Nick", max_length=20)
password = forms.CharField(label="Heslo", max_length=50, widget=f... |
Add a proper Riak health check | /**
* Copyright 2016 Smoke Turner, LLC.
*
* 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... | /**
* Copyright 2016 Smoke Turner, LLC.
*
* 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... |
Use blank string instead of None as default origin
Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com> | import logging
from fnmatch import fnmatch
from tornado import web
from qotr.config import config
L = logging.getLogger(__name__)
ALLOWED_ORIGINS = [o.strip() for o in config.allowed_origin.split(',')]
def set_cors_headers(handler):
'''
Given a handler, set the CORS headers on it.
'''
origin = hand... | import logging
from fnmatch import fnmatch
from tornado import web
from qotr.config import config
L = logging.getLogger(__name__)
ALLOWED_ORIGINS = [o.strip() for o in config.allowed_origin.split(',')]
def set_cors_headers(handler):
'''
Given a handler, set the CORS headers on it.
'''
origin = hand... |
Fix a few more lint issues | package org.gbif.nameparser.utils;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Modified Executors DefaultThreadFactory to allow custom named thread pools.
* Otherwise, this factory yields the same semantics as the thread f... | package org.gbif.nameparser.utils;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Modified Executors DefaultThreadFactory to allow custom named thread pools.
* Otherwise, this factory yields the same semantics as the thread f... |
Improve comments and add breakpoint const | package wrap
import "strings"
const (
// breakpoints defines which characters should be able to break a line.
breakpoints = " "
)
// Line will wrap a single line of text at the given length.
// If limit is less than 1, the string remains unchanged.
//
// If a word is longer than the given limit, it will not be bro... | package wrap
import "strings"
// Line will wrap a single line of text at the given length.
// If limit is less than 1, the string remains unchanged.
//
// If a word is longer than the given limit, it will not be broken to fit.
// See the examples for this scenario.
func Line(s string, limit int) string {
if limit < ... |
Fix disappearing contact entries after being renamed by another client.
This actually modified a cached roster entry of another random user that
happened to have the same JID in their roster. | <?php
namespace Moxl\Xec\Payload;
use App\Roster as DBRoster;
use App\User as DBUser;
class Roster extends Payload
{
public function handle($stanza, $parent = false)
{
if ((string)$parent->attributes()->type == 'set') {
$jid = current(explode('/', (string)$stanza->item->attributes()->jid)... | <?php
namespace Moxl\Xec\Payload;
use App\Roster as DBRoster;
use App\User as DBUser;
class Roster extends Payload
{
public function handle($stanza, $parent = false)
{
if ((string)$parent->attributes()->type == 'set') {
$jid = current(explode('/', (string)$stanza->item->attributes()->jid)... |
Remove change set links from quick search as it will likely conflict with issues and builds too (on svn at least) | /*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any late... | /*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any late... |
Reformat code use golang standard format | package main
import (
"fmt"
"net"
"os"
"sync"
"time"
)
var (
host string // The host address to scan
)
func init() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
os.Exit(1)
}
host = os.Args[1]
}
func main() {
d := net.Dialer{Timeout: 10 * time.Second}
p := make(chan b... | package main
import (
"fmt"
"os"
"net"
"time"
"sync"
)
var (
host string // The host address to scan
)
func init() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
os.Exit(1)
}
host = os.Args[1]
}
func main() {
d := net.Dialer{Timeout: 10 * time.Second}
p... |
Use the correct host name | package com.example.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.... | package com.example.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.... |
Clean up page metadata keys | <?php
namespace Site\Page;
class MetadataList {
public $error;
public $count = 0;
public function find($parameters = array()) {
$bind_params = array();
$get_object_query = "
SELECT id
FROM page_metadata
WHERE id = id
";
if (!empty($parameters['page_id'])) {
$get_object_query .= "
... | <?php
namespace Site\Page;
class MetadataList {
public $error;
public $count = 0;
public function find($parameters = array()) {
$bind_params = array();
$get_object_query = "
SELECT id
FROM page_metadata
WHERE id = id
";
if (!empty($parameters['page_id'])) {
$get_object_query .= "
... |
Use print() for Python3. No global variables. Optimisations | from __future__ import print_function
import json
import optparse
def read_gene_info(gene_info):
transcript_species_dict = dict()
for gene_dict in gene_info.values():
for transcript in gene_dict['Transcript']:
transcript_species_dict[transcript['id']] = transcript['species'].replace("_", ... | import json
import optparse
transcript_species_dict = dict()
sequence_dict = dict()
def readgene(gene):
for transcript in gene['Transcript']:
transcript_species_dict[transcript['id']] = transcript['species'].replace("_", "")
def read_fasta(fp):
for line in fp:
line = line.rstrip()
... |
Update contact to function on click | jQuery(document).ready(function() {
var loginToken = window.localStorage.getItem("token");
setTimeout(function() {
keepAliveTwo(loginToken);
}, 500);
displayAllUsersForCoach();
function displayAllUsersForCoach() {
// Get a list of users under the logged in job coach
var us... | jQuery(document).ready(function() {
var loginToken = window.localStorage.getItem("token");
setTimeout(function() {
keepAliveTwo(loginToken);
}, 500);
displayAllUsersForCoach();
function displayAllUsersForCoach() {
// Get a list of users under the logged in job coach
var us... |
Handle when container is undefined. | (function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjus... | (function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjus... |
Bugfix: Structure keyword get accepted now | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structur... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structur... |
Revert "commented out clear for now"
This reverts commit 1a03b1fc61f9c32e26dd146801127306736a86c3. | package guitests;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ClearCommandTest extends ToDoListGuiTest {
@Test
public void clear() {
/*
//verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertCl... | package guitests;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ClearCommandTest extends ToDoListGuiTest {
/*
@Test
public void clear() {
/*
//verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assert... |
Store session cookies as a dictionary | #!/usr/bin/env python
'''PyLibChorus -- Python Chorus API Library'''
import logging
from pylibchorus.chorus_api import login
from pylibchorus.chorus_api import logout
from pylibchorus.chorus_api import check_login_status
from pylibchorus.chorus_api import create_workfile
from pylibchorus.chorus_api import update_workf... | #!/usr/bin/env python
'''PyLibChorus -- Python Chorus API Library'''
import logging
from pylibchorus.chorus_api import login
from pylibchorus.chorus_api import logout
from pylibchorus.chorus_api import check_login_status
from pylibchorus.chorus_api import create_workfile
from pylibchorus.chorus_api import update_workf... |
Add missing border to messages box | package es.ucm.fdi.tp.views.swing;
import javax.swing.border.TitledBorder;
public class MessagesBox extends ScrollableTextarea {
private static final long serialVersionUID = 768586332299945974L;
public MessagesBox() {
super();
}
public MessagesBox(String text) {
super(text);
}
public MessagesBox(int... | package es.ucm.fdi.tp.views.swing;
public class MessagesBox extends ScrollableTextarea {
private static final long serialVersionUID = 768586332299945974L;
public MessagesBox() {
super();
}
public MessagesBox(String text) {
super(text);
}
public MessagesBox(int rows, int cols) {
super(rows,cols);
}... |
Change navigation after add category to list categories | package vu.de.npolke.myexpenses.servlets;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRes... | package vu.de.npolke.myexpenses.servlets;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRes... |
Fix an issue in isEmulator | package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| ... | package com.smartdevicelink.test.util;
import android.os.Build;
public class DeviceUtil {
public static boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| ... |
Change custom stroke override method
Peeking into the fabric source, it looks like the `_stroke` method we're
overriding in the `highlighted_stroke` mixin has been renamed to
`_renderStroke`. Making sure we override the correct method, we start
seeing our customized stroke rendering. | module.exports = {
borderWidth: 5,
strokeWidth: 0.1,
// in percentage of borderWidth
outlineWidth: 0.2,
outlineStyle: "#FFF",
/**
* Provide a custom stroke function that draws a fat white line THEN a
* narrower colored line on top.
*/
_renderStroke: function (ctx) {
var myScale = this.scaleX... | module.exports = {
borderWidth: 5,
strokeWidth: 0.1,
// in percentage of borderWidth
outlineWidth: 0.2,
outlineStyle: "#FFF",
/**
* Provide a custom stroke function that draws a fat white line THEN a
* narrower colored line on top.
*/
_stroke: function (ctx) {
var myScale = this.scaleX;
... |
Add mutator generation to assemble command. | <?php
namespace R\Hive\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
class AssembleCommand extends Command
{
protected $name = 'hive:assemble';
protected $description = 'Create a new Hive resource collection for an instance.';
public function fire()
{
... | <?php
namespace R\Hive\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
class AssembleCommand extends Command
{
protected $name = 'hive:assemble';
protected $description = 'Create a new Hive resource collection for an instance.';
public function fire()
{
... |
Fix handling of non-error reponses from Graphite | var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.ENV_NAME || "unknown";
var timer = null;
var graphite = null;
var data = Measured.cre... | var Graphite = require('graphite');
var Measured = require('measured');
var reportInterval = 5000;
var graphiteHost = process.env.GRAPHITE_HOST || null;
var graphitePort = process.env.GRAPHITE_PORT || 2003;
var envName = process.env.ENV_NAME || "unknown";
var timer = null;
var graphite = null;
var data = Measured.cre... |
Complete search functionality for models
* Add button functionality to search bar | const mongoose = require('mongoose')
const shortId = require('shortid')
const Schema = mongoose.Schema
const assetSchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
tagId: String,
assignedTo: String
})
const specSchema = Schema({
_shortId: {type: String, unique: true, default... | const mongoose = require('mongoose')
const shortId = require('shortid')
const Schema = mongoose.Schema
const assetSchema = Schema({
_shortId: {type: String, unique: true, default: shortId.generate},
tagId: { type: String, text: true },
assignedTo: { type: String, text: true }
})
const specSchema = Schema({
_s... |
Update parse() to grab the business URL | 'use strict';
var Backbone = require('backbone');
var BusinessModel = Backbone.Model.extend({
idAttribute: 'id',
parse: function(data) {
var hash = {};
hash.name = data.name;
hash.id = data.id;
hash.address = data.location.display_address.join(' ');
hash.rating = data.rating;
... | 'use strict';
var Backbone = require('backbone');
var BusinessModel = Backbone.Model.extend({
idAttribute: 'id',
parse: function(data) {
var hash = {};
hash.name = data.name;
hash.id = data.id;
hash.address = data.location.display_address.join(' ');
hash.rating = data.rating;
... |
[Feature] Add BucketListApi resource to api. | """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResour... | """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResour... |
Use model injection for Pitch model | <?php
class PitchController extends BaseController {
protected $pitch;
function __construct(Pitch $pitch)
{
$this->pitch = $pitch;
}
/**
* Validator for pitches
*/
protected $rules = [
'email' => 'required|email',
'name' => 'required',
'blurb' => 'required'
];
public function getIndex()
{
re... | <?php
class PitchController extends BaseController {
/**
* Validator for pitches
*/
protected $rules = [
'email' => 'required|email',
'name' => 'required',
'blurb' => 'required'
];
public function getIndex()
{
$pitch = new Pitch();
return View::make('pitch')->with('pitch', $pitch);
}
public fun... |
Fix to use node path module to join path | var path = require('path');
var exec = require('child_process').exec;
var _ = require('lodash');
var Q = require('q');
function UrlToImage() {
var api = {};
api.render = function(url, file, opts) {
var def = Q.defer();
var args = [
path.join(__dirname, 'url-to-image.js'),
... | var exec = require('child_process').exec;
var _ = require('lodash');
var Q = require('q');
function UrlToImage() {
var api = {};
api.render = function(url, file, opts) {
var def = Q.defer();
var args = [
__dirname + 'url-to-image.js',
url,
file,
... |
Use plural names for resource types in URLs | from django.conf.urls.defaults import patterns, include, url
from boundaryservice.views import *
urlpatterns = patterns('',
url(r'^boundary-sets/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'),
url(r'^boundary-sets/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservic... | from django.conf.urls.defaults import patterns, include, url
from boundaryservice.views import *
urlpatterns = patterns('',
url(r'^boundary-set/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'),
url(r'^boundary-set/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservice_... |
Revert "Do not display quesitons in script."
This reverts commit 5c7286c1dc6348f2212266871876376df15592c0. | from demo7 import get_answer
import json
class TripleError(Exception):
"""
Raised when a triple contains connectors (e.g. AND, FIRST).
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
def string_of_triple(t,missing,separator):
if ... | from demo7 import get_answer
import json
class TripleError(Exception):
"""
Raised when a triple contains connectors (e.g. AND, FIRST).
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
def string_of_triple(t,missing,separator):
if ... |
Fix attribute error in vsphere controller
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com> | from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.get_datacenters():
if dc.name == app.provider.region:
self.datace... | from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.client.get_datacenters():
if dc.name == app.provider.region:
self... |
ExpandURL: Move to group 'base' and enable "More at ..." | (function(env){
env.ddg_spice_expand_url = function(api_response) {
"use strict";
// Get the orignal query.
var query = DDG.get_query().replace(/expand\s*/i, "");
// Check if there are any errors.
if (!api_response["long-url"] || api_response["long-url"] === query) {
... | (function(env){
env.ddg_spice_expand_url = function(api_response) {
"use strict";
// Get the orignal query.
var query = DDG.get_query().replace(/expand\s*/i, "");
// Check if there are any errors.
if (!api_response["long-url"] || api_response["long-url"] === query) {
... |
Return graph object after ploting | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distr... | # Internal modules #
from plumbing.graphs import Graph
from plumbing.autopaths import FilePath
# Third party modules #
from matplotlib import pyplot
# Constants #
__all__ = ['LengthDist']
################################################################################
class LengthDist(Graph):
"""The length distr... |
Fix format string for MessageFormat | package com.komanov.stringformat;
import org.slf4j.helpers.MessageFormatter;
import java.text.MessageFormat;
import java.util.Locale;
public class JavaFormats {
private static final MessageFormat messageFormatInstance = new MessageFormat("{0,number,#}a{1}b{2}{3}");
public static String concat(int value1, St... | package com.komanov.stringformat;
import org.slf4j.helpers.MessageFormatter;
import java.text.MessageFormat;
import java.util.Locale;
public class JavaFormats {
private static final MessageFormat messageFormatInstance = new MessageFormat("{0}a{1}b{2}{3}");
public static String concat(int value1, String valu... |
Bring US site shipping repo up-to-date
The repo internals had changed since the US site was born. | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')... | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')... |
Add support for scoped package | #!/usr/bin/env node
var program = require('commander'),
globalify = require('./globalify'),
packageJson = require('./package.json'),
fs = require('fs');
program
.version(packageJson.version)
.usage('<module> [options]')
.arguments('<module>')
.option('-o, --out <outputFileName>', 'the outpu... | #!/usr/bin/env node
var program = require('commander'),
globalify = require('./globalify'),
packageJson = require('./package.json'),
fs = require('fs');
program
.version(packageJson.version)
.usage('<module> [options]')
.arguments('<module>')
.option('-o, --out <outputFileName>', 'the outpu... |
Add more detail to module docstring | # -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certa... | # -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certa... |
Make argv arguments optional, fixes pip installed script | import yaml
from zonetruck.WorkManager import WorkManager
from zonetruck.ZoneUpdater import ZoneUpdater
from zonetruck.ZoneFilter import ZoneFilter
from zonetruck.zone_xfer import zone_xfer
import sys
def main(argv=None):
argv = argv or sys.argv
config = yaml.safe_load(open(argv[1], 'r'))
zone_filter = Zo... | import yaml
from zonetruck.WorkManager import WorkManager
from zonetruck.ZoneUpdater import ZoneUpdater
from zonetruck.ZoneFilter import ZoneFilter
from zonetruck.zone_xfer import zone_xfer
def main(argv):
config = yaml.safe_load(open(argv[1], 'r'))
zone_filter = ZoneFilter(config['filter_rules']).filter
... |
Add 'extraAllowedContent' to CKEditor config | (function(win, doc){
'use strict';
var
getRootPath = function(){
var parts = win.location.pathname.split('/');
parts.shift(); // remove first
parts.pop(); // remove last
parts.pop(); // yes, twice
var path = parts.join('/');
return '/' + path;
},
root_http = getRoo... | (function(win, doc){
'use strict';
var
getRootPath = function(){
var parts = win.location.pathname.split('/');
parts.shift(); // remove first
parts.pop(); // remove last
parts.pop(); // yes, twice
var path = parts.join('/');
return '/' + path;
},
root_http = getRoo... |
Add some more test coverage | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy... | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1)
sub = nnpy.Socket(nnpy.AF_SP, nnpy.S... |
Fix large Input file generator | <?php
declare(strict_types=1);
require_once __DIR__.'/../__CondorcetAutoload.php';
///
$number_of_votes = 100_000_000;
$number_of_candidates = 8;
///
$candidateName = 'A';
$candidates = [];
for ($i=0; $i < $number_of_candidates ; $i++) :
$candidates[] = $candidateName++;
endfor;
$file = fopen(__DIR__.... | <?php
declare(strict_types=1);
require_once __DIR__.'/../__CondorcetAutoload.php';
///
$number_of_votes = 100_000_000;
$number_of_candidates = 8;
///
$candidateName = 'A';
$candidates = [];
for ($i=0; $i < $number_of_candidates ; $i++) :
$candidates[] = $candidateName++;
endfor;
$file = fopen(__DIR__.... |
Add "AnyOf" to public API. | from .compiler import ParseResult
from .expressions import (
Alt,
And,
Any,
AnyOf,
Backtrack,
Bind,
End,
Expect,
Fail,
ForwardRef,
Left,
List,
Literal,
Not,
Opt,
Or,
Require,
Return,
Right,
Some,
Start,
Struct,
Term,
Transf... | from .compiler import ParseResult
from .expressions import (
Alt,
And,
Any,
Backtrack,
Bind,
End,
Expect,
Fail,
ForwardRef,
Left,
List,
Literal,
Not,
Opt,
Or,
Require,
Return,
Right,
Some,
Start,
Struct,
Term,
Transform,
Wh... |
Add function support to SVG as well | import { createElement } from './create-element.js';
import { parseArguments, isString, isNode } from './util.js';
const ns = 'http://www.w3.org/2000/svg';
const svgCache = {};
const memoizeSVG = query => svgCache[query] || (svgCache[query] = createElement(query, ns));
export const svg = (query, ...args) => {
let... | import { createElement } from './create-element.js';
import { parseArguments, isString, isNode } from './util.js';
const ns = 'http://www.w3.org/2000/svg';
const svgCache = {};
const memoizeSVG = query => svgCache[query] || (svgCache[query] = createElement(query, ns));
export const svg = (query, ...args) => {
let... |
Add volume adjustment to sound script. | // This will not make any noise if the file
// ~/.arlobot/status/bequiet
// exists
var beQuietFile = process.env.HOME + '/.arlobot/status/bequiet';
var fs = require('fs');
fs.open(beQuietFile, 'r', function(err) {
if (err) {
var exec = require('child_process').exec;
// Set volume at max
exe... | // This will not make any noise if the file
// ~/.arlobot/status/bequiet
// exists
var beQuietFile = process.env.HOME + '/.arlobot/status/bequiet';
var fs = require('fs');
fs.open(beQuietFile, 'r', function(err) {
if (err) {
var requestedSound = process.argv[2];
// This script can accept text to s... |
Reorder to match PHPTAL interface. | <?php defined('SYSPATH') or die('No direct script access.');
/**
* Allows PHPTAL to take advantage of the Kohana i18n tranlator.
*
* @package KOtal
* @category Base
* @author Hanson Wong
* @author johanlindblad
* @copyright (c) 2010 Hanson Wong
* @license http://github.com/Dismounted/KOtal/blob... | <?php defined('SYSPATH') or die('No direct script access.');
/**
* Allows PHPTAL to take advantage of the Kohana i18n tranlator.
*
* @package KOtal
* @category Base
* @author Hanson Wong
* @author johanlindblad
* @copyright (c) 2010 Hanson Wong
* @license http://github.com/Dismounted/KOtal/blob... |
Increase intake motor value to 1.0. | package org.usfirst.frc.team3335.robot.subsystems;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team3335.robot.RobotMap;
import com.ctre.CANTalon;
import edu.wpi.first.wpilibj.CANSpeedController;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.... | package org.usfirst.frc.team3335.robot.subsystems;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team3335.robot.RobotMap;
import com.ctre.CANTalon;
import edu.wpi.first.wpilibj.CANSpeedController;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.... |
Remove useless url from test urls | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.http.response import HttpResponse
admin.autodiscover()
def empty_view(request):
return HttpResponse()
urlpatterns = [
url(r'^home/', empty_view, name="home"),
url(r'^admin/', admin.site.urls)... | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.http.response import HttpResponse
admin.autodiscover()
def empty_view(request):
return HttpResponse()
urlpatterns = [
url(r'^home/', empty_view, name="home"),
url(r'^admin/', admin.site.urls)... |
Fix link to example pipelines | import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Cr... | import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Cr... |
Set automatic releases as 'prerelease'. | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps... | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps... |
Install CMake in system dirs | #!/usr/bin/env python
# Build the project with Biicode.
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz',... | #!/usr/bin/env python
# Build the project with Biicode.
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz',... |
Add tests for sending messages to "user" projects | from nose.tools import *
from lamson.testing import *
import os
from lamson import server
relay = relay(port=8823)
client = RouterConversation("queuetester@localhost", "requests_tests")
confirm_format = "testing-confirm-[0-9]+@"
noreply_format = "testing-noreply@"
host = "localhost"
def test_react_for_existing_proje... | from nose.tools import *
from lamson.testing import *
import os
from lamson import server
relay = relay(port=8823)
client = RouterConversation("queuetester@localhost", "requests_tests")
confirm_format = "testing-confirm-[0-9]+@"
noreply_format = "testing-noreply@"
host = "localhost"
def test_react_for_existing_proje... |
Remove superfluous parens; catch timeout | #!/usr/bin/env python
"""Collection of module netural utility functions"""
from sys import stderr
from ssl import SSLError
from socket import timeout
try:
from urllib.request import urlopen, HTTPError, URLError
except ImportError:
from urllib2 import urlopen, HTTPError, URLError
class HTMLGetError(Exception):... | #!/usr/bin/env python
"""Collection of module netural utility functions"""
from sys import stderr
from ssl import SSLError
try:
from urllib.request import urlopen, HTTPError, URLError
except ImportError:
from urllib2 import urlopen, HTTPError, URLError
class HTMLGetError(Exception):
pass
def get_html(url... |
Use terminal md5 for perf | #coding:utf-8
import os
import cStringIO
import gzip
import hashlib
import subprocess
from cactus.utils.helpers import checksum
class FakeTime:
"""
Monkey-patch gzip.time to avoid changing files every time we deploy them.
"""
def time(self):
return 1111111111.111
def compressString(s):
... | #coding:utf-8
import os
import cStringIO
import gzip
import hashlib
from cactus.utils.helpers import checksum
class FakeTime:
"""
Monkey-patch gzip.time to avoid changing files every time we deploy them.
"""
def time(self):
return 1111111111.111
def compressString(s):
"""Gzip a given st... |
Add Google Analytics to each angular page viewed | 'use strict';
/**
* Main module of the application.
*/
angular
.module('personalDataDashboardApp', [
'ui.router',
'ngAnimate',
'ngResource',
'ui.bootstrap'
])
.run(['$rootScope', '$state', '$stateParams', '$location', function ($rootScope, $state, $stateParams, $location) ... | 'use strict';
/**
* Main module of the application.
*/
angular
.module('personalDataDashboardApp', [
'ui.router',
'ngAnimate',
'ngResource',
'ui.bootstrap'
])
.run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) {
$rootScope.$st... |
Fix warning assertion in credentials test
This commit fixes a warning assertion in a credentials test now that we
are stricter about warning message assertions. | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this fi... | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this fi... |
Add working_dir and copy_steps options | from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
... | from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self):
WFGenerator.__init__(self, steps_dir=CWL_PATH)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Sav... |
Fix queries and path to templates | from app import app
from app.models import Post
from flask import render_template
@app.route('/')
@app.route('/page/<int:page>')
def blog(page=1):
"""View the blog."""
posts = Post.query.filter_by(visible=True) \
.order_by(Post.published.desc())
if posts:
pagination = posts.p... | from app import app
from app.models import Post
from flask import render_template
@app.route('/')
@app.route('/page/<int:page>')
def blog(page=1):
"""View the blog."""
posts = Post.query.filter_by_latest()
if posts:
pagination = posts.paginate(page=page, per_page=Post.PER_PAGE)
return render_t... |
Test whether Z3Java can be loaded in a simpler way. | /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2015 Dirk Beyer
* 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 ... | /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2015 Dirk Beyer
* 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 ... |
Set action rules kind to 'on_time' | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 HBEE (http://www.hbee.eu)
# @author: Paulius Sladkevičius <paulius@hbee.eu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 HBEE (http://www.hbee.eu)
# @author: Paulius Sladkevičius <paulius@hbee.eu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
Use ->write() instead of echo | <?php
namespace Bendihossan\Pinfo\Command;
use Console_Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Bendihossan\Pinfo\Command\PinfoCommand;
class ... | <?php
namespace Bendihossan\Pinfo\Command;
use Console_Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Bendihossan\Pinfo\Command\PinfoCommand;
class ... |
Remove @override on createJSModules for latest RN version | package com.devfd.RNGeocoder;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.V... | package com.devfd.RNGeocoder;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.V... |
Change type from text to UnicodeText | from sqlalchemy import ForeignKey, Column, UnicodeText
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Unicode, Integer
from sqlalchemy.orm import backref, relation
from tgext.pluggable import app_model, primary_key
Declara... | from sqlalchemy import ForeignKey, Column
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Unicode, Integer
from sqlalchemy.orm import backref, relation
from tgext.pluggable import app_model, primary_key
DeclarativeBase = de... |
Use option.text instead of option.label. | /**
* Patterns checkedflag - Add checked flag to checkbox labels
*
* Copyright 2013 Simplon B.V. - Wichert Akkerman
*/
define([
"jquery",
"../registry",
"../utils"
], function($, patterns, utils) {
var select_option = {
name: "select-option",
trigger: "label select",
init: f... | /**
* Patterns checkedflag - Add checked flag to checkbox labels
*
* Copyright 2013 Simplon B.V. - Wichert Akkerman
*/
define([
"jquery",
"../registry",
"../utils"
], function($, patterns, utils) {
var select_option = {
name: "select-option",
trigger: "label select",
init: f... |
Fix mutation not returning person | import { Likes } from '../collections';
import { swapiLoader, peopleUrl } from './swapi-loader';
import { pubsub } from './pubsub';
export const resolvers = {
Person: {
id: ({ url }) => url,
name: ({ name }) => name,
likes: ({ url }) => Likes.find({ personId: url }).count(),
films: ({ films }) => swa... | import { Likes } from '../collections';
import { swapiLoader, peopleUrl } from './swapi-loader';
import { pubsub } from './pubsub';
export const resolvers = {
Person: {
id: ({ url }) => url,
name: ({ name }) => name,
likes: ({ url }) => Likes.find({ personId: url }).count(),
films: ({ films }) => swa... |
Make event type more explicit in examples | package eventstore.j.examples;
import eventstore.EventData;
import eventstore.j.EventDataBuilder;
import java.util.UUID;
public class EventDataBuilderExample {
final EventData empty = new EventDataBuilder("eventType").build();
final EventData binary = new EventDataBuilder("eventType")
.eventId(... | package eventstore.j.examples;
import eventstore.EventData;
import eventstore.j.EventDataBuilder;
import java.util.UUID;
public class EventDataBuilderExample {
final EventData empty = new EventDataBuilder("empty").build();
final EventData binary = new EventDataBuilder("binary")
.eventId(UUID.ra... |
Add self instantiation, prevents possible reference conflicts | /**
* Module dependencies
*/
var assert = require('assert');
/**
* Expose 'foyer'
*/
module.exports = foyer;
/**
* Foyer
*
* @param {Function[]} tasks
* @param {Function} cb
* @api public
*/
function foyer(tasks, cb) {
if (!(this instanceof foyer)) return new foyer(tasks, cb);
assert('[object Array]'... | /**
* Module dependencies
*/
var assert = require('assert');
/**
* Expose 'foyer'
*/
module.exports = foyer;
/**
* Foyer
*
* @param {Function[]} tasks
* @param {Function} cb
* @api public
*/
function foyer(tasks, cb) {
assert('[object Array]' == Object.prototype.toString.call(tasks), 'Tasks must be an ... |
Change required privilege of DeleteJobAction (SERVER_OPERATION -> PROCESS_MANAGE) | <?php
class DeleteJobAction extends ApiActionBase
{
protected static $required_privileges = array(Auth::PROCESS_MANAGE);
protected static $rules = array(
'jobID' => array('type' => 'int', 'required' => true)
);
protected function execute($params)
{
$pdo = DBConnector::getConnection();
$pdo->b... | <?php
class DeleteJobAction extends ApiActionBase
{
protected static $required_privileges = array(Auth::SERVER_SETTINGS);
protected static $rules = array(
'jobID' => array('type' => 'int', 'required' => true)
);
protected function execute($params)
{
$pdo = DBConnector::getConnection();
$pdo->... |
Send default_currency in Client init on client test | import unittest
from bluesnap.client import Client
class ClientTestCase(unittest.TestCase):
DUMMY_CREDENTIALS = {
'username': 'username',
'password': 'password',
'default_store_id': '1',
'seller_id': '1',
'default_currency': 'GBP'
}
def setUp(self):
self.c... | import unittest
from bluesnap.client import Client
class ClientTestCase(unittest.TestCase):
DUMMY_CREDENTIALS = {
'username': 'username',
'password': 'password',
'default_store_id': '1',
'seller_id': '1',
}
def setUp(self):
self.client = Client(env='live', **self.... |
Revert "ACalc: Increased minimum and starting calculator size."
This reverts commit 1747c7b05b30630358a58603da0d1878cf9b2a57. | /**
* @license
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless requir... | /**
* @license
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless requir... |
Add comment describing url prefixes | import {has, type} from 'ramda';
/*
* requests_pathname_prefix is the new config parameter introduced in
* dash==0.18.0. The previous versions just had url_base_pathname
*/
export function urlBase(config) {
if (type(config) === "Null" ||
(type(config) === "Object") &&
!has('url_base_pathname', ... | import {has, type} from 'ramda';
export function urlBase(config) {
if (type(config) === "Null" ||
(type(config) === "Object") &&
!has('url_base_pathname', config) &&
!has('requests_pathname_prefix', config)) {
throw new Error(`
Trying to make an API request but "url_base... |
Add pytz as a dependency | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(
name='django-modelcluster',
version='0.5',
description="Django extension to allow working with 'clusters' of models as a single unit, independently of the database",
... | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(
name='django-modelcluster',
version='0.5',
description="Django extension to allow working with 'clusters' of models as a single unit, independently of the database",
... |
Mark table cell by data-line | Object.prototype._is_nil = function (name) {
const obj = this; // e.g document
if (obj && obj.$attr) {
return obj.$attr(name)['$nil?']();
}
return true;
};
asciidoctor.Extensions.register(function () {
this.treeProcessor(function () {
const self = this;
const selector = JSON... | Object.prototype._is_nil = function (name) {
const obj = this; // e.g document
if (obj && obj.$attr) {
return obj.$attr(name)['$nil?']();
}
return true;
};
asciidoctor.Extensions.register(function () {
this.treeProcessor(function () {
const self = this;
self.process(function... |
Raise an exception when request fails.
In general, I think that it is safer to raise an exception when an HTTP
request used to fetch a page fails. | import requests
class BasePage:
def __init__(self, data):
self.data = data
@classmethod
def from_file(cls, path):
with open(path) as f:
raw = f.read()
return cls(raw)
@classmethod
def from_url(cls, url):
res = requests.get(url)
res.raise_for_s... | import requests
class BasePage:
def __init__(self, data):
self.data = data
@classmethod
def from_file(cls, path):
with open(path) as f:
raw = f.read()
return cls(raw)
@classmethod
def from_url(cls, url):
res = requests.get(url)
return cls(res.... |
Append to log file instead of overwrite it | <?php
function debug_collectionInfoStart($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Collecting data\n";
}
}
function debug_collectionInfoEnd($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Finished collecting data\n";
}
}
function debug_collectionInterval($debug, $interval) {
if ... | <?php
function debug_collectionInfoStart($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Collecting data\n";
}
}
function debug_collectionInfoEnd($debug) {
if ($debug == TRUE) {
echo "[DEBUG] Finished collecting data\n";
}
}
function debug_collectionInterval($debug, $interval) {
if ... |
Add completion log message to the background task | from heltour.tournament.models import *
from heltour.tournament import lichessapi
from heltour.celery import app
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
# Disabled for now because of rate-limiting
lichess_teams = [] # ['lichess4545-league']
@app.task(bind=True)
def update_play... | from heltour.tournament.models import *
from heltour.tournament import lichessapi
from heltour.celery import app
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
# Disabled for now because of rate-limiting
lichess_teams = [] # ['lichess4545-league']
@app.task(bind=True)
def update_play... |
Add greedSpread to Run Model | 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var runSchema = new Schema({
time: Date,
participants: [ String ],
results: [{
season: Number,
fishStart: Number,
fishEnd: Number,
groupRestraint: Number,
... | 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var runSchema = new Schema({
time: Date,
participants: [ String ],
results: [{
season: Number,
fishStart: Number,
fishEnd: Number,
groupRestraint: Number,
... |
Add APL2 header and fix a typo. | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License")... | package groovy.lang;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation to hold the groovydoc for the annotated element at runtime, we can it "Runt... |
Set properties to be public | <?php
namespace OAuth2\Client\Provider;
class User implements \IteratorAggregate {
public $uid = null;
public $nickname = null;
public $name = null;
public $firstName = null;
public $lastName = null;
public $email = null;
public $location = null;
public $description = null;
public... | <?php
namespace OAuth2\Client\Provider;
class User implements \IteratorAggregate {
protected $uid = null;
protected $nickname = null;
protected $name = null;
protected $firstName = null;
protected $lastName = null;
protected $email = null;
protected $location = null;
protected $descri... |
Update point to fix equality problems. | package com.censoredsoftware.library.schematic;
import java.util.Objects;
public class Point {
private final int X, Y, Z;
private final World world;
public Point(int X, int Y, int Z, World world) {
this.X = X;
this.Y = Y;
this.Z = Z;
this.world = world;
}
public i... | package com.censoredsoftware.library.schematic;
public class Point {
private final int X, Y, Z;
private final World world;
public Point(int X, int Y, int Z, World world) {
this.X = X;
this.Y = Y;
this.Z = Z;
this.world = world;
}
public int getX() {
return ... |
Make minor improvements to comments and formatting | #!/usr/bin/env python
import turtle
def draw_initials():
"""Draw the initials BC"""
# Set up screen, etc.
window = turtle.Screen()
window.bgcolor('gray')
letter = turtle.Turtle()
letter.shape('turtle')
letter.color('white', 'gray')
letter.speed(8)
# Move pen into place
lette... | import turtle
def draw_initials():
#Set up screen, etc.
window = turtle.Screen()
window.bgcolor('gray')
###THE LETTER B###
letter = turtle.Turtle()
letter.shape('turtle')
letter.color('white', 'gray')
letter.speed(8)
#Move pen into place
letter.penup()
letter.left(180)... |
cliedit: Fix the completion test case. | package cliedit
import (
"testing"
"github.com/elves/elvish/cli/el/codearea"
"github.com/elves/elvish/edit/ui"
"github.com/elves/elvish/eval"
"github.com/elves/elvish/styled"
"github.com/elves/elvish/util"
)
func TestCompletion(t *testing.T) {
_, cleanupDir := eval.InTempHome()
util.ApplyDir(util.Dir{"a": ""... | package cliedit
import (
"testing"
"github.com/elves/elvish/cli/el/codearea"
"github.com/elves/elvish/edit/ui"
"github.com/elves/elvish/eval"
"github.com/elves/elvish/styled"
"github.com/elves/elvish/util"
)
func TestCompletion(t *testing.T) {
_, cleanupDir := eval.InTempHome()
util.ApplyDir(util.Dir{"a": ""... |
Make tab widgets look good on ElementaryOS.
Any other linux distribution will probably look bad because of this. In
the future a better solution must be found to styling the background of
a widget inside a scrollarea inside a tabwidget. | """
Style
Contains convenience functions for styling widgets.
:Authors:
Berend Klein Haneveld
"""
import sys
def styleWidgetForTab(widget):
"""
This function style a widget that can be used inside a QScrollArea that
is inside a QTabWidget. On OS X the background color inside a tab
widget is slightly darker tha... | """
Style
Contains convenience functions for styling widgets.
:Authors:
Berend Klein Haneveld
"""
import sys
def styleWidgetForTab(widget):
"""
This function style a widget that can be used inside a QScrollArea that
is inside a QTabWidget. On OS X the background color inside a tab
widget is slightly darker tha... |
Remove check for "availability" command because this case is treated separately. | package rabbit;
public class CommandCreator {
public String createCommand(String userCommand) {
String[] tokens = userCommand.split("\\s+");
switch(tokens[0]) {
case "security":
switch (tokens[1]) {
case "tls":
return "nmap ... | package rabbit;
public class CommandCreator {
public String createCommand(String userCommand) {
String[] tokens = userCommand.split("\\s+");
switch(tokens[0]) {
case "availability":
return "nmap -sV " + tokens[1];
case "security":
switch (t... |
Fix deprecated usage of Ember.observer.
[Fixes #81] | import RecordArray from "./record-array";
/**
@module ember-orbit
*/
var get = Ember.get;
/**
@class FilteredRecordArray
@namespace EO
@extends EO.RecordArray
*/
export default RecordArray.extend({
/**
@method filterFunction
@param {EO.Model} record
@return {Boolean} `true` if the record should be i... | import RecordArray from "./record-array";
/**
@module ember-orbit
*/
var get = Ember.get;
/**
@class FilteredRecordArray
@namespace EO
@extends EO.RecordArray
*/
var FilteredRecordArray = RecordArray.extend({
/**
@method filterFunction
@param {EO.Model} record
@return {Boolean} `true` if the record ... |
Add message if transformer_hash already exists | from django.core.management.base import BaseCommand
from optparse import make_option
from ...utils import transformer
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--sheet', action='store', dest='sheet', default=None,
help='Sheet name'),
ma... | from django.core.management.base import BaseCommand
from optparse import make_option
from ...utils import transformer
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--sheet', action='store', dest='sheet', default=None,
help='Sheet name'),
ma... |
Fix potential bug in parameter passing | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... |
Remove an unused method in FakeResourceTracker
Nothing calls _create and there is no _create in the super class for
this to be overriding.
Change-Id: Ic41f2d249b9aaffb2caaa18dd492924a4ceb3653 | # Copyright (c) 2012 OpenStack Foundation
# 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 ... | # Copyright (c) 2012 OpenStack Foundation
# 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 ... |
Fix copy-paste-o in exception message. | from functools import wraps
from django.http import HttpResponseForbidden
from google.appengine.api.users import is_current_user_admin
def task_queue_only(view_func):
""" View decorator that only allows requests which originate from the App Engine task queue.
"""
@wraps(view_func)
def new_view(reques... | from functools import wraps
from django.http import HttpResponseForbidden
from google.appengine.api.users import is_current_user_admin
def task_queue_only(view_func):
""" View decorator that only allows requests which originate from the App Engine task queue.
"""
@wraps(view_func)
def new_view(reques... |
Fix missing svg bug on chrome | var path = require('path');
// /////////////////////////////////////////////////////////////////////////////
// ------------------------ Available modules --------------------------------//
// ---------------------------------------------------------------------------//
module.exports.hello = require('./hello');
// /... | var path = require('path');
// /////////////////////////////////////////////////////////////////////////////
// ------------------------ Available modules --------------------------------//
// ---------------------------------------------------------------------------//
module.exports.hello = require('./hello');
// /... |
Use the Accept-Encoding header for the cache key | var SyncCache = require('active-cache/sync');
var filesizeParser = require('filesize-parser');
function key(req) {
return req.z+','+req.x+','+req.y+','+req.layer+','+req.filename+','+req.headers['accept-encoding'];
}
module.exports = function(opts) {
opts = opts || {};
var lruopts = {max: 6};
if (typeof opts.siz... | var SyncCache = require('active-cache/sync');
var filesizeParser = require('filesize-parser');
function key(req) {
return req.z+','+req.x+','+req.y+','+req.layer+','+req.filename;
}
module.exports = function(opts) {
opts = opts || {};
var lruopts = {max: 6};
if (typeof opts.size === 'string') {
lruopts.max = f... |
Terminate the request after sending. | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylorotwell@gmail.com>
*/
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|... | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylorotwell@gmail.com>
*/
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|... |
Use parentheses even when constructor take no params | <?php
namespace YUti\OpChecker;
class ValueRepository
{
private $repository;
private static function initialize(ValueRepository $instance)
{
$instance->repository = array_fill_keys(TypeUtil::types(), array());
}
public static function newInstance()
{
$instance = new ValueRepos... | <?php
namespace YUti\OpChecker;
class ValueRepository
{
private $repository;
private static function initialize(ValueRepository $instance)
{
$instance->repository = array_fill_keys(TypeUtil::types(), array());
}
public static function newInstance()
{
$instance = new ValueRepos... |
Fix deprecated disableClick prop on Dropzone
Ref: https://github.com/react-dropzone/react-dropzone/commit/1402362dd16a349761187a29cca356628b23b798 | import React from "react";
import Dropzone from "react-dropzone";
import "./DropHandler.css";
export default class DropHandler extends React.Component {
handleDrop = (files) => {
this.props.importSequenceFromFile(files[0]);
};
render() {
const { children, style, className, disabled } = this.props;
re... | import React from "react";
import Dropzone from "react-dropzone";
import "./DropHandler.css";
export default class DropHandler extends React.Component {
handleDrop = (files) => {
this.props.importSequenceFromFile(files[0]);
};
render() {
const { children, style, className, disabled } = this.props;
re... |
Fix bug with arguments handling in JSON API content decorator | from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
... | from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
... |
:recycle: Revert password route back to original broken state | <form class="keyboard-save" action="{{ url('auth/password') }}" method="POST" role="form" autocomplete="false" id="passwordUpdate">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="POST">
<br>
<div class="form-group">
<div class="fg-line">
... | <form class="keyboard-save" action="{!! route('canvas.auth.password') !!}" method="POST" role="form" autocomplete="false" id="passwordUpdate">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="POST">
<br>
<div class="form-group">
<div class="fg-lin... |
Set standard state of wizard to one (so first step automatically starts) | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty
class ToolbarProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._state = 1
self._use_wizard = False
stateChanged = pyqtSignal()
wizardStateChanged = pyqtSignal()
... | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty
class ToolbarProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._state = 0
self._use_wizard = False
stateChanged = pyqtSignal()
wizardStateChanged = pyqtSignal()
... |
Correct warning print to only happen if the socket is not available. | import { consola } from './utils';
import initWebSocket from './initWebSocket';
import closeWebSocket from './closeWebSocket';
import * as types from './types';
export * from './types';
const createMiddleware = () => {
let websocket;
return store => next => (action) => {
switch (action.type) {
case ty... | import { consola } from './utils';
import initWebSocket from './initWebSocket';
import closeWebSocket from './closeWebSocket';
import * as types from './types';
export * from './types';
const createMiddleware = () => {
let websocket;
return store => next => (action) => {
switch (action.type) {
case ty... |
Remove all flowtypes for now | 'use strict'
/* eslint-disable no-param-reassign */
// Replace absolute file paths with <PROJECT_ROOT>
const cwd = process.cwd()
module.exports = {
print (val, serialize) {
if (isPath(val)) {
val = val.split(cwd).join('<PROJECT_ROOT>')
}
else if (val instanceof Error) {
val.message = v... | 'use strict'
/* eslint-disable no-param-reassign */
// Replace absolute file paths with <PROJECT_ROOT>
const cwd = process.cwd()
/*::
type Val = string | Object
*/
module.exports = {
print (val/* : Val */, serialize/* : Function */) {
if (isPath(val)) {
val = val.split(cwd).join('<PROJECT_ROOT>')
... |
Replace exact equality assert with isclose in bands cli | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_ban... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_bands():
samples_d... |
Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3 | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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 agre... | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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 agre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.