text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
test: Use fixture name to name test | <?php
namespace nochso\Phormat\Test;
/**
* FixtureIterator provides test data from files.
*
* For files named `*.in.php` will try to use a matching `*.out.php` file for expected output.
* If not output file is found, the input is re-used for expected output.
*/
class FixtureIterator implements \Iterator{
/**
*... | <?php
namespace nochso\Phormat\Test;
/**
* FixtureIterator provides test data from files.
*
* For files named `*.in.php` will try to use a matching `*.out.php` file for expected output.
* If not output file is found, the input is re-used for expected output.
*/
class FixtureIterator implements \Iterator{
/**
*... |
Update PyDelphin interface to recent version | from delphin.interfaces import ace
from delphin.mrs import simplemrs, dmrx
from pydmrs.core import ListDmrs
from pydmrs.utils import load_config, get_config_option
DEFAULT_CONFIG_FILE = 'default_interface.conf'
config = load_config(DEFAULT_CONFIG_FILE)
DEFAULT_ERG_FILE = get_config_option(config, 'Grammar', 'ERG')
... | from delphin.interfaces import ace
from delphin.mrs import simplemrs, dmrx
from pydmrs.core import ListDmrs
from pydmrs.utils import load_config, get_config_option
DEFAULT_CONFIG_FILE = 'default_interface.conf'
config = load_config(DEFAULT_CONFIG_FILE)
DEFAULT_ERG_FILE = get_config_option(config, 'Grammar', 'ERG')
... |
Update: Create worker methods at prototype level
This approach is slightly faster since the code is executed only once.
Rather constructor code is executed every time a new instance is created.
Serious advantage of prototype over constructor is that the former is compatible with class inheritance. | export default class Worker {
constructor() {
// EventTarget
var delegate = document.createDocumentFragment();
[
'addEventListener',
'dispatchEvent',
'removeEventListener'
].forEach(f => /*this[f]*/ Worker.prototype[f] = (...xs) => delegate[f](...xs))
}
postMessage(aMessage, tran... | export default class Worker {
constructor() {
// EventTarget
var delegate = document.createDocumentFragment();
[
'addEventListener',
'dispatchEvent',
'removeEventListener'
].forEach(f =>
this[f] = (...xs) => delegate[f](...xs)
)
}
postMessage(aMessage, transferList)... |
Save app preset in config | 'use strict';
var BaseGenerator = require('yeoman-generator').Base;
module.exports = BaseGenerator.extend({
constructor: function () {
BaseGenerator.apply(this, arguments);
this.option('preset', {desc: 'App preset: dust | example | handlebars | jade', alias: 'p', defaults: 'handlebars'});
this.argument... | 'use strict';
var BaseGenerator = require('yeoman-generator').Base;
module.exports = BaseGenerator.extend({
constructor: function () {
BaseGenerator.apply(this, arguments);
this.option('preset', {desc: 'App preset: dust | example | handlebars | jade', alias: 'p', defaults: 'handlebars'});
this.argument... |
Change 500 Internal Server Error to 400 Bad Request | package main
import (
"io/ioutil"
"strconv"
"github.com/gin-gonic/gin"
"github.com/mdeheij/gitlegram/gitlab"
log "github.com/mdeheij/logwrap"
)
func main() {
c := NewConfig()
//gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.POST("/", func(c *gin.Context) {
body, ioerr := ioutil.ReadAll(c.Request.Body)... | package main
import (
"io/ioutil"
"strconv"
"github.com/gin-gonic/gin"
"github.com/mdeheij/gitlegram/gitlab"
log "github.com/mdeheij/logwrap"
)
func main() {
c := NewConfig()
//gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.POST("/", func(c *gin.Context) {
body, ioerr := ioutil.ReadAll(c.Request.Body)... |
Add wait time to ebay pageset
Bug: skia:11898
Change-Id: I0bb58f1d8e9c6ad48148d50b840f152fc158f071
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/400538
Reviewed-by: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.... | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... |
Add temporary accessor to make the helloworld application work again with @Visible
This accessor will be removed when MVEL processing of @Visible will be
fixed. | package info.sitebricks.example.web;
import com.google.sitebricks.At;
import com.google.sitebricks.Visible;
import com.google.sitebricks.http.Get;
/**
* The home page that our users will see at the top level URI "/".
* <p>
* This page is created once per request and has "no scope" in Guice
* terminology. See the ... | package info.sitebricks.example.web;
import com.google.sitebricks.At;
import com.google.sitebricks.Visible;
import com.google.sitebricks.http.Get;
/**
* The home page that our users will see at the top level URI "/".
* <p>
* This page is created once per request and has "no scope" in Guice
* terminology. See the ... |
Fix FCM URL for stage | /**
* @description
* This module sets all configuration
*
* policyCompassConfig is exposed as a global variable in order to use it in
* the main app.js file. If there's a way to do the same with dependency
* injection, this should be fixed.
*/
// Configuration for remote services
var policyCompassConfig = {
... | /**
* @description
* This module sets all configuration
*
* policyCompassConfig is exposed as a global variable in order to use it in
* the main app.js file. If there's a way to do the same with dependency
* injection, this should be fixed.
*/
// Configuration for remote services
var policyCompassConfig = {
... |
Work around `AttributeError: 'module' object has no attribute 'BufferedIOBase'` on Python 2.7+, Windows | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))
from version import version as __version__
def _setup_test():
import gzip
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--e... | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))
from version import version as __version__
def _setup_test():
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--exe', '-w', '%s' ... |
Allow override of backend urls from env variables | from flask import Flask
from flask import redirect
from flask import url_for
from kqueen_ui.blueprints.ui.views import ui
from werkzeug.contrib.cache import SimpleCache
import logging
import os
logger = logging.getLogger(__name__)
cache = SimpleCache()
config_file = os.environ.get('KQUEEN_CONFIG_FILE', 'config/dev.... | from flask import Flask
from flask import redirect
from flask import url_for
from kqueen_ui.blueprints.ui.views import ui
from werkzeug.contrib.cache import SimpleCache
import logging
import os
logger = logging.getLogger(__name__)
cache = SimpleCache()
config_file = os.environ.get('KQUEEN_CONFIG_FILE', 'config/dev.... |
Make stable builder pull from 1.10
R=kasperl@google.com
BUG=
Review URL: https://codereview.chromium.org/1107673002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@294974 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... |
Rename the used variable everywhere, and not just in its definition... | define(['jquery'], function ($) {
var colors = {
log: '#000000',
warn: '#cc9900',
error: '#cc0000'
};
var log = $('#log');
if (!console) {
console = {};
}
for (var name in colors) {
console[name] = (function (original, color) {
return... | define(['jquery'], function ($) {
var colors = {
log: '#000000',
warn: '#cc9900',
error: '#cc0000'
};
var log = $('#log');
if (!console) {
console = {};
}
for (var name in colors) {
console[name] = (function (original, color) {
return... |
Include license file in resulting tar.gz
I am going to package this module for Fedora. And it is better for Fedora if tar.gz file contains the file with the license (it is better for auditing). Can you please include it with next version? | from setuptools import setup
setup(
name="ordered-set",
version = '1.3.1',
maintainer='Luminoso Technologies, Inc.',
maintainer_email='rob@luminoso.com',
license = "MIT-LICENSE",
url = 'http://github.com/LuminosoInsight/ordered-set',
platforms = ["any"],
description = "A MutableSet that... | from setuptools import setup
setup(
name="ordered-set",
version = '1.3.1',
maintainer='Luminoso Technologies, Inc.',
maintainer_email='rob@luminoso.com',
license = "MIT-LICENSE",
url = 'http://github.com/LuminosoInsight/ordered-set',
platforms = ["any"],
description = "A MutableSet that... |
Address when args passed to cli are in quotes
puts entire string as first element in []string, so must grab this
element and split it on spaces | package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
const aURL = "http://artii.herokuapp.com"
func main() {
args := os.Args[1:]
if len(args) == 0 {
fmt.Printf("Usage:\n")
return
}
switch args[0] {
case "fonts":
fmt.Printf("%v", fontList())
return
}
fmt.Println(draw(args)... | package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
const aURL = "http://artii.herokuapp.com"
func main() {
args := os.Args[1:]
if len(args) == 0 {
fmt.Printf("Usage:\n")
return
}
switch args[0] {
case "fonts":
fmt.Printf("%v", fontList())
}
fmt.Println(draw(args[0]))
}
func fontLis... |
Add newline to format imports properly. | import os
from distutils.core import setup
from shortwave import VERSION
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-shortwave',
version=VERSION,
description='Shortwave command file management for Django apps.',
url='https://github.com... | import os
from distutils.core import setup
from shortwave import VERSION
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-shortwave',
version=VERSION,
description='Shortwave command file management for Django apps.',
url='https://github.com/... |
Add on.('close') to clear node status on Deploy | module.exports = function (RED) {
var alasql = require('alasql');
function AlasqlNodeIn(config) {
RED.nodes.createNode(this, config);
var node = this;
node.query = config.query;
node.on("input", function (msg) {
var sql = this.query || 'SELECT * FROM ?';
... | module.exports = function (RED) {
var alasql = require('alasql');
function AlasqlNodeIn(config) {
RED.nodes.createNode(this, config);
var node = this;
node.query = config.query;
node.on("input", function (msg) {
var sql = this.query || 'SELECT * FROM ?';
... |
Add params to topic partial | package net.ontopia.presto.jaxb;
import java.util.Collection;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@XmlRootElement
@JsonSerialize(include = JsonSerialize.In... | package net.ontopia.presto.jaxb;
import java.util.Collection;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@XmlRootElement
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@Jso... |
Add win32 to platform information | """
Return information about the given platform.
"""
import sys
class Platform(object):
@staticmethod
def is_darwin(name=None):
name = name or sys.platform
return 'darwin' in name
@staticmethod
def is_freebsd(name=None):
name = name or sys.platform
return name.start... | """
Return information about the given platform.
"""
import sys
class Platform(object):
@staticmethod
def is_darwin(name=None):
name = name or sys.platform
return 'darwin' in name
@staticmethod
def is_freebsd(name=None):
name = name or sys.platform
return name.start... |
Fix default log level in logging | const winston = require('winston');
module.exports = ({
filename,
level,
transports: transports = [{ type: 'Console', options: { level: 'debug' } }],
}) => {
if (filename) {
transports.push({
type: 'File',
options: { filename, level: 'debug' },
});
}
if (level) {
for (const transpor... | const winston = require('winston');
module.exports = ({
filename,
level,
transports: transports = [{ level: 'debug', type: 'Console' }],
}) => {
if (filename) {
transports.push({
type: 'File',
options: { filename, level: 'debug' },
});
}
if (level) {
for (const transport of transpor... |
Fix display of coverage report | var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
gulp.task('test', function(done) {
return runSequence('test-unit', 'test-coverage', 'test-complexity', done);
});
gulp.task('test-complexity', function() {
return gulp.src(['lib/**/*.js'])
.pipe(pl... | var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
gulp.task('test', function(done) {
return runSequence('test-unit', 'test-complexity', 'test-coverage', done);
});
gulp.task('test-complexity', function() {
return gulp.src(['lib/**/*.js'])
.pipe(pl... |
Remove "validation" from RejectionException docstring | #!/usr/bin/env python3
"""Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolErro... | #!/usr/bin/env python3
"""Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolErro... |
Throw Error instead of string | import VulcanEmail from 'meteor/vulcan:email';
import Handlebars from 'handlebars';
import moment from 'moment';
const postsQuery = `
query PostsSingleQuery($documentId: String){
PostsSingle(documentId: $documentId){
title
url
pageUrl
linkUrl
postedAt
htmlBody
thumbnailU... | import VulcanEmail from 'meteor/vulcan:email';
import Handlebars from 'handlebars';
import moment from 'moment';
const postsQuery = `
query PostsSingleQuery($documentId: String){
PostsSingle(documentId: $documentId){
title
url
pageUrl
linkUrl
postedAt
htmlBody
thumbnailU... |
jQuery: Fix code style, remove JSHint comment. | /**
* <%= name %>
*
* Makes bla bla.
*
* @version 0.0.0
* @requires jQuery
* @author <%= authorName %>
* @copyright <%= (new Date).getFullYear() %> <%= authorName %>, <%= authorUrl %>
* @license MIT
*/
/*global define:false*/
;(function(factory) { // Try to register as an anonymous AMD module
if (typeof de... | /**
* <%= name %>
*
* Makes bla bla.
*
* @version 0.0.0
* @requires jQuery
* @author <%= authorName %>
* @copyright <%= (new Date).getFullYear() %> <%= authorName %>, <%= authorUrl %>
* @license MIT
*/
/*jshint browser:true, jquery:true, white:false, smarttabs:true, eqeqeq:true,
immed:true, latedef:... |
Update example for update to isSameDay() | import React from "react";
import DayPicker from "react-day-picker";
import { dateUtils } from "react-day-picker/utils";
import "react-day-picker/lib/style.css";
export default class SelectableDay extends React.Component {
state = {
selectedDay: null
}
handleDayClick(e, day, modifiers) {
if (modifiers... | import React from "react";
import DayPicker from "react-day-picker";
import { dateUtils } from "react-day-picker/utils";
import "react-day-picker/lib/style.css";
export default class SelectableDay extends React.Component {
state = {
selectedDay: null
}
handleDayClick(e, day, modifiers) {
if (modifiers... |
Add cache key in HTML source | from django.core.cache import cache
def cache_get_key(*args, **kwargs):
"""Get the cache key for storage"""
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.appen... | from django.core.cache import cache
def cache_get_key(*args, **kwargs):
"""Get the cache key for storage"""
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.appen... |
Fix FileNotFoundError on missing local_settings.py
This has been broken for a long time... When running LBB without a
local_settings.py and without an LBB_ENV environment variable, importing
local_settings.py was resulting in a FileNotFoundError. | import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` f... | import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` f... |
Fix codegen template typo for app dll generation | <?php
require_once($argv[1]); // type.php
require_once($argv[2]); // program.php
$file_prefix = $argv[3];
$idl_type = $argv[4];
?>
// apps
# include "<?=$file_prefix?>.app.example.h"
void dsn_app_registration_<?=$_PROG->name?>()
{
// register all possible service apps
dsn::register_app< <?=$_PROG->get_cpp_name... | <?php
require_once($argv[1]); // type.php
require_once($argv[2]); // program.php
$file_prefix = $argv[3];
$idl_type = $argv[4];
?>
// apps
# include "<?=$file_prefix?>.app.example.h"
void dsn_app_registration_<?=$_PROG->name?>()
{
// register all possible service apps
dsn::register_app< <?=$_PROG->get_cpp_name... |
Update plugin to latest YggdrasilCore | package ru.linachan.pushbullet;
import ru.linachan.yggdrasil.component.YggdrasilPlugin;
import ru.linachan.yggdrasil.notification.YggdrasilNotificationManager;
public class PushBulletPlugin extends YggdrasilPlugin {
private PushBulletClient client;
@Override
protected void setUpDependencies() {
}
... | package ru.linachan.pushbullet;
import ru.linachan.yggdrasil.component.YggdrasilPlugin;
public class PushBulletPlugin extends YggdrasilPlugin {
private PushBulletClient client;
@Override
protected void setUpDependencies() {
}
@Override
protected void onInit() {
String apiKey = core... |
Use `RuntimeException` instead of `UnexpectedValueException` when zip extension is not enabled | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Packag... | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Packag... |
Remove another “trick babel” hack in analytics
Test plan
* with or without the “Drop IE 11” commit applied
* bin/rspec ./gems/plugins/analytics/spec_canvas/selenium/analytics_spec.rb:250
Should pass
Or to test manually:
* apply the “drop ie11” commit in canvas-lms
* check out this commit in gems/plugins/analytics
*... | import ComboBox from 'compiled/widget/ComboBox'
import StudentInCourseRouter from '../StudentInCourse/StudentInCourseRouter'
// #
// A combobox representing the possible filters for the department view.
export default class StudentComboBox extends ComboBox {
constructor(model) {
// construct combobox
super(m... | import ComboBox from 'compiled/widget/ComboBox'
import StudentInCourseRouter from '../StudentInCourse/StudentInCourseRouter'
// #
// A combobox representing the possible filters for the department view.
export default class StudentComboBox extends ComboBox {
constructor(model) {
{
// Hack: trick Babel/Type... |
Add kwargs to this to make Jenkins shut up about it | from utils.command_system import command
from utils import confirm
import discord
class SuperUser:
def __init__(self, amethyst):
self.amethyst = amethyst
@command()
@confirm.instance_owner()
async def coreswap(self, ctx, *, path1, path2):
"""Command to swap your core module.
... | from utils.command_system import command
from utils import confirm
import discord
class SuperUser:
def __init__(self, amethyst):
self.amethyst = amethyst
@command(usage='<path1> <path2>')
@confirm.instance_owner()
async def coreswap(self, ctx):
"""Command to swap your core module.
... |
Rename tests so that they run. | import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def test_noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def test_launches_node(self):
pass
class TestFailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('th... | import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def launches_node(self):
pass
class FailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_proj... |
Fix trello micro service url | export const dbURI = (() => {
if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') {
return 'mongodb://localhost/trelloService';
} else {
return 'mongodb://trellodb:27017/trelloService';
}
})();
export const dbTestURI = (() => {
if (process.env.NODE_ENV === 'docker-test') {
return... | export const dbURI = (() => {
if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') {
return 'mongodb://localhost/trelloService';
} else {
return 'mongodb://trellodb:27017/trelloService';
}
})();
export const dbTestURI = (() => {
if (process.env.NODE_ENV === 'docker-test') {
return... |
Add css and img files to bdist | #!/usr/bin/env python
# vim: set sts=4 sw=4 et:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = "0.0.4"
setup (name = "tupelo",
description = "Random code around a card game called Tuppi",
version = VERSION,
author = "Jari Tenhunen",
author_e... | #!/usr/bin/env python
# vim: set sts=4 sw=4 et:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = "0.0.4"
setup (name = "tupelo",
description = "Random code around a card game called Tuppi",
version = VERSION,
author = "Jari Tenhunen",
author_e... |
Update auth details on reauthorization | from tapiriik.services import *
from tapiriik.database import db
class Service:
def FromID(id):
if id=="runkeeper":
return RunKeeper
elif id=="strava":
return Strava
raise ValueError
def List():
return [RunKeeper, Strava]
def WebInit():
glob... | from tapiriik.services import *
from tapiriik.database import db
class Service:
def FromID(id):
if id=="runkeeper":
return RunKeeper
elif id=="strava":
return Strava
raise ValueError
def List():
return [RunKeeper, Strava]
def WebInit():
glob... |
Revert "sample data structure for multithread working"
This reverts commit 33a475b883c311666078b91ed1dab5870c6d583d. | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.peta2kuba.sample_data;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spr... | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.peta2kuba.sample_data;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spr... |
Disable duplicate celery log messages | from scoring_engine.celery_app import celery_app
from billiard.exceptions import SoftTimeLimitExceeded
import subprocess
from scoring_engine.logger import logger
@celery_app.task(name='execute_command', soft_time_limit=30)
def execute_command(job):
output = ""
# Disable duplicate celery log messages
if l... | from scoring_engine.celery_app import celery_app
from billiard.exceptions import SoftTimeLimitExceeded
import subprocess
from scoring_engine.logger import logger
@celery_app.task(name='execute_command', soft_time_limit=30)
def execute_command(job):
output = ""
logger.info("Running cmd for " + str(job))
t... |
fix(TripSummary): Remove green bar outside of batch itinerary results. | import coreUtils from '@opentripplanner/core-utils'
import { ClassicLegIcon } from '@opentripplanner/icons'
import React from 'react'
import ItinerarySummary from '../../narrative/default/itinerary-summary'
const { formatDuration, formatTime } = coreUtils.time
const TripSummary = ({ monitoredTrip }) => {
const { i... | import coreUtils from '@opentripplanner/core-utils'
import { ClassicLegIcon } from '@opentripplanner/icons'
import React from 'react'
import ItinerarySummary from '../../narrative/default/itinerary-summary'
const { formatDuration, formatTime } = coreUtils.time
const TripSummary = ({ monitoredTrip }) => {
const { i... |
Fix mistaken document about token pos |
class Token:
"""
Individual word with lemma, part-of-speech and location in text.
:ivar word: Unprocessed word
:ivar lemma: Lemmatized word
:ivar partofspeech: Part-of-speech of word
:ivar startPos: Start position of token in document text (note: not the sentence text)
:ivar endPos: End position of token in d... |
class Token:
"""
Individual word with lemma, part-of-speech and location in text.
:ivar word: Unprocessed word
:ivar lemma: Lemmatized word
:ivar partofspeech: Part-of-speech of word
:ivar startPos: Start position of token in sentence
:ivar endPos: End position of token in sentence
"""
def __init__(self,w... |
Set content-length in bytes instead of characters |
module.exports = function (options) {
options = options || {}
options.property = options.property || 'body'
options.stringify = options.stringify || JSON.stringify
return function (req, res, next) {
req.removeAllListeners('data')
req.removeAllListeners('end')
if(req.headers['content-length'] !== u... |
module.exports = function (options) {
options = options || {}
options.property = options.property || 'body'
options.stringify = options.stringify || JSON.stringify
return function (req, res, next) {
req.removeAllListeners('data')
req.removeAllListeners('end')
if(req.headers['content-length'] !== u... |
Fix redirection rule inside post comment route. | var path = require('path');
var posts = require('data-post');
var express = require('express');
var app = module.exports = express();
app.set('view engine', 'jade');
app.set('views', path.join(__dirname, 'views'));
app.param('slug', function _slug(req, res, next, val) {
var regex = /^[\w\-]+$/;
var captures;
if... | var path = require('path');
var posts = require('data-post');
var express = require('express');
var app = module.exports = express();
app.set('view engine', 'jade');
app.set('views', path.join(__dirname, 'views'));
app.param('slug', function _slug(req, res, next, val) {
var regex = /^[\w\-]+$/;
var captures;
if... |
Add friendly name to email-address | import AWS from 'aws-sdk'
import InputValidator from './InputValidator'
import EmailFormatter from './EmailFormatter'
AWS.config.region = 'us-east-1'
exports.handler = function(event, context) {
// Validate Inputs
let errors = InputValidator.validate(event)
if (errors) {
context.fail(errors)
return
}... | import AWS from 'aws-sdk'
import InputValidator from './InputValidator'
import EmailFormatter from './EmailFormatter'
AWS.config.region = 'us-east-1'
exports.handler = function(event, context) {
// Validate Inputs
let errors = InputValidator.validate(event)
if (errors) {
context.fail(errors)
return
}... |
Update git url, formatting nits | Package.describe({
summary: "Ravelry OAuth flow",
name: "amschrader:ravelry",
git: "https://github.com/amschrader/meteor-ravelry.git",
version: "0.1.2"
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('amschrader:ravelry');
api.addFiles('ravelry-tests.js');
});
Package.onUse(function(api)... | Package.describe({
summary: "Ravelry OAuth flow",
name: "amschrader:ravelry",
git: "git@github.com:amschrader/meteor-ravelry.git",
version: "0.1.0"
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('amschrader:ravelry');
api.addFiles('ravelry-tests.js');
});
Package.on_use(function(api) {
... |
Use read stream to ensure file is greater than 0 bytes | #! /usr/bin/env node
"use strict";
var argv = require("optimist").argv;
var pjson = require("../package.json");
var defaultConfig = require("./default-config");
var cliUtils = require("./cli").utils;
var cliInfo = require("./cli-info").info;
/**
* Handle Command-line usage
*/
if (require.main === module) {
if (... | #! /usr/bin/env node
"use strict";
var argv = require("optimist").argv;
var pjson = require("../package.json");
var defaultConfig = require("./default-config");
var cliUtils = require("./cli").utils;
var cliInfo = require("./cli-info").info;
/**
* Handle Command-line usage
*/
if (require.main === module) {
if (... |
[gulp] Make Gulp wait on the Promise returned from `del`
This fixes the `lib` build step; running `gulp build` now creates `lib` as expected. | var babel = require('gulp-babel');
var del = require('del');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var runSequence = require('run-sequence');
var babelOpts = require('./scripts/babel/default-options');
var paths = {
src: [
'src/**/*.js',
'!src/**/__tests__/**/*.js',
'!src/**... | var babel = require('gulp-babel');
var del = require('del');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var runSequence = require('run-sequence');
var babelOpts = require('./scripts/babel/default-options');
var paths = {
src: [
'src/**/*.js',
'!src/**/__tests__/**/*.js',
'!src/**... |
Add Python 3 to supported languages | #!/usr/bin/env python
from setuptools import setup
setup(
name='Simon',
version='0.7.0',
description='Simple MongoDB Models',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/Simon',
packages=['simon'... | #!/usr/bin/env python
from setuptools import setup
setup(
name='Simon',
version='0.7.0',
description='Simple MongoDB Models',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/Simon',
packages=['simon'... |
Fix indentation which causes error on restore
Fixes error message, that document with a specific number already exists, even if it doesn't. | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe import _
class DeletedDocument(Document):
pass
@frappe.whitelist()
d... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe import _
class DeletedDocument(Document):
pass
@frappe.whitelist()
d... |
Fix errrors on Firefox when dismiss toaster | /* global element, by */
'use strict';
var common = require('../common/common');
var navigation = require('../common/navigation');
var genericForm = require('../generic_form/generic_form');
var goToCloudImageList = function() {
navigation.go('main', 'admin');
navigation.go('admin', 'cloud-images');
};
module.expo... | /* global element, by */
'use strict';
var common = require('../common/common');
var navigation = require('../common/navigation');
var genericForm = require('../generic_form/generic_form');
var goToCloudImageList = function() {
navigation.go('main', 'admin');
navigation.go('admin', 'cloud-images');
};
module.expo... |
Make it compatible with older node.js | module.exports = function (protocol) {
protocol = protocol || 'http';
var url = 'http://vicopo.selfbuild.fr/search/';
switch (protocol) {
case 'https':
url = 'https://www.selfbuild.fr/vicopo/search/';
break;
case 'http':
break;
default:
throw new Error(protocol + ' protocol not supported');
}
var... | module.exports = function (protocol) {
protocol = protocol || 'http';
var url = 'http://vicopo.selfbuild.fr/search/';
switch (protocol) {
case 'https':
url = 'https://www.selfbuild.fr/vicopo/search/';
break;
case 'http':
break;
default:
throw new Error(protocol + ' protocol not supported');
}
var... |
Change ID to String (easier for comparisons) | /*
* Copyright 2013 That Amazing Web Ltd.
*
* 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 ... | /*
* Copyright 2013 That Amazing Web Ltd.
*
* 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 ... |
Return a cloned model.attributes by default | Minionette.ModelView = Minionette.View.extend({
// Listen to the default events
modelEvents: {
'change': 'render',
'destroy': 'remove'
},
// The data that is sent into the template function.
// Override this to provide custom data.
serializeData: function() {
},
// A u... | Minionette.ModelView = Minionette.View.extend({
// Listen to the default events
modelEvents: {
'change': 'render',
'destroy': 'remove'
},
// The data that is sent into the template function.
// Override this to provide custom data.
serializeData: function() {
return thi... |
Set the Renderer in the View Helper Manager
This would have been done in the EngineFactory - however - that creates
a circular dependency. | <?php
namespace ZfcTwig\Service;
use ZfcTwig\View\Renderer;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver\TemplatePathStack;
class ViewRendererFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLo... | <?php
namespace ZfcTwig\Service;
use ZfcTwig\View\Renderer;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver\TemplatePathStack;
class ViewRendererFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLo... |
Add exception for streams forcefully reset | # -*- coding: utf-8 -*-
"""
hyper/http20/exceptions
~~~~~~~~~~~~~~~~~~~~~~~
This defines exceptions used in the HTTP/2 portion of hyper.
"""
class HTTP20Error(Exception):
"""
The base class for all of ``hyper``'s HTTP/2-related exceptions.
"""
pass
class HPACKEncodingError(HTTP20Error):
"""
... | # -*- coding: utf-8 -*-
"""
hyper/http20/exceptions
~~~~~~~~~~~~~~~~~~~~~~~
This defines exceptions used in the HTTP/2 portion of hyper.
"""
class HTTP20Error(Exception):
"""
The base class for all of ``hyper``'s HTTP/2-related exceptions.
"""
pass
class HPACKEncodingError(HTTP20Error):
"""
... |
Update gateways to use new sendData method | <?php
namespace Omnipay\Mollie\Message;
/**
* Mollie Abstract Request
*/
abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest
{
protected $endpoint = 'https://secure.mollie.nl/xml/ideal';
public function getPartnerId()
{
return $this->getParameter('partnerId');
}
... | <?php
namespace Omnipay\Mollie\Message;
/**
* Mollie Abstract Request
*/
abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest
{
protected $endpoint = 'https://secure.mollie.nl/xml/ideal';
public function getPartnerId()
{
return $this->getParameter('partnerId');
}
... |
Make instance private, reorder lambda | package io.teiler.api.endpoint;
import static spark.Spark.before;
import static spark.Spark.get;
import static spark.Spark.post;
import io.teiler.api.service.GroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework... | package io.teiler.api.endpoint;
import static spark.Spark.before;
import static spark.Spark.get;
import static spark.Spark.post;
import io.teiler.api.service.GroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework... |
Make sure the username is lower case when imported from ldap
Otherwise the meteor accounts package cannot find the user document which leads to errors when logging in with an username that has upper case letters | let _ = require('underscore');
module.exports = function (ldapSettings, userData) {
let searchDn = ldapSettings.searchDn || 'cn';
// userData.mail may be a string with one mail address or an array.
// Nevertheless we are only interested in the first mail address here - if there should be more...
let t... | let _ = require('underscore');
module.exports = function (ldapSettings, userData) {
let searchDn = ldapSettings.searchDn || 'cn';
// userData.mail may be a string with one mail address or an array.
// Nevertheless we are only interested in the first mail address here - if there should be more...
let t... |
Make accessKey a zoneData param. | <?php
class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract {
public function getHtml($zoneData, array $variables) {
$zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']);
$variables = $this->_variableKeysToUnderscore($variables);
$variables['key'] = $zoneData['accessKey... | <?php
class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract {
/**
* @return string
*/
private function _getAccessKey() {
return self::_getConfig()->accessKey;
}
public function getHtml($zoneData, array $variables) {
$zoneId = CM_Util::htmlspecialchars($zoneDa... |
Fix bug when transcriptions are empty | from flask import render_template, jsonify, request
from app import app
from app import evolver
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
def format_transcriptions(transcriptions):
'''Split the raw string of transcriptions into
the correct tuple rules.'''
... | from flask import render_template, jsonify, request
from app import app
from app import evolver
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
def format_transcriptions(transcriptions):
'''Split the raw string of transcriptions into
the correct tuple rules.'''
... |
Disable ens for rin and rop since they have a different implementation | import domainSale from '@/assets/images/icons/domain-sale.svg';
import domainSaleHov from '@/assets/images/icons/domain-sale-hov.svg';
import registerDomain from '@/assets/images/icons/domain.svg';
import registerDomainHov from '@/assets/images/icons/domain-hov.svg';
import secureTransaction from '@/assets/images/icons... | import domainSale from '@/assets/images/icons/domain-sale.svg';
import domainSaleHov from '@/assets/images/icons/domain-sale-hov.svg';
import registerDomain from '@/assets/images/icons/domain.svg';
import registerDomainHov from '@/assets/images/icons/domain-hov.svg';
import secureTransaction from '@/assets/images/icons... |
Fix the marker bouncing function. | function initMap() {
var map;
var $business_object;
var biz_loc_collection;
var i;
$business_object = $('#businesses').data('url');
biz_loc_collection = [];
for (i = 0; i < $business_object.length; ++i) {
biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}... | function initMap() {
var map;
var $business_object;
var biz_loc_collection;
var i;
$business_object = $('#businesses').data('url');
biz_loc_collection = [];
for (i = 0; i < $business_object.length; ++i) {
biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}... |
Use 'future_or_past' for the Meetup API scroll parameter.
Hopefully this will fix the issue of the blank Meetup section after the meetup begins. | (function($) {
"use strict"; // Start of use strict
var meetupEventsUrl = "https://api.meetup.com/Phoenix-Unreal-Engine-Developers/events?scroll=future_or_past&photo-host=public&page=1&sig_id=55074012&status=past%2Cupcoming&sig=b751e22a582e2309e5b03a0cd1a80466ef7e4fc3";
function populateMap(data) {
var API_... | (function($) {
"use strict"; // Start of use strict
var meetupEventsUrl = "https://api.meetup.com/Phoenix-Unreal-Engine-Developers/events?scroll=next_upcoming&photo-host=public&page=1&sig_id=198889890&status=past%2Cupcoming&sig=fba37148ddce35c43bfcbed2979dbaa5804a5d9f";
function populateMap(data) {
var API_... |
Make sure the demo project is in the pythonpath | #!/usr/bin/env python
import os
import sys
from pathlib import Path
if __name__ == "__main__":
# We add ourselves into the python path, so we can find
# the package later.
demo_root =os.path.dirname(os.path.abspath(__file__))
crud_install = os.path.dirname(os.path.dirname(demo_root))
sys.path.inse... | #!/usr/bin/env python
import os
import sys
from pathlib import Path
if __name__ == "__main__":
# We add ourselves into the python path, so we can find
# the package later.
demo_root =os.path.dirname(os.path.abspath(__file__))
crud_install = os.path.dirname(os.path.dirname(demo_root))
sys.path.inse... |
Add some methods to the container for migration | package info.u_team.u_team_test.init;
import info.u_team.u_team_core.containertype.UContainerType;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.*;
import net.minecraft.inventory.container.ContainerType;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.... | package info.u_team.u_team_test.init;
import info.u_team.u_team_core.containertype.UContainerType;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.*;
import net.minecraft.inventory.container.ContainerType;
import net.minecr... |
Add url callback on custom login | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from bottle.ext import auth
from utils import conf
try:
auth_import = conf('auth')['engine'].split('.')[-1]
auth_from = u".".join(conf('auth')['engine'].split('.')[:-1])
auth_engine = getattr(__import__(auth_from, fromlist=[auth_import]),
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from bottle.ext import auth
from utils import conf
try:
auth_import = conf('auth')['engine'].split('.')[-1]
auth_from = u".".join(conf('auth')['engine'].split('.')[:-1])
auth_engine = getattr(__import__(auth_from, fromlist=[auth_import]),
... |
Fix start/watch issues for server | 'use strict';
var argv = require('yargs').argv;
var path = require('path');
module.exports = function(gulp, plugins, config) {
return function() {
function getSources(root, filter) {
if (root instanceof Array) {
return root.map(function(item) {
return item + filter;
}... | 'use strict';
var argv = require('yargs').argv;
var path = require('path');
module.exports = function(gulp, plugins, config) {
return function() {
function getSources(root, filter) {
if (root instanceof Array) {
return root.map(function(item) {
return item + filter;
}... |
Add log and remove isProduction | // Description:
// for initialize
//
"use strict";
const config = require("config");
const Raven = require('raven'); // TODO wrapper
function sentryIsSet() {
return config.sentry !== null;
}
module.exports = function(robot) {
robot.logger.info(`node env: ${process.env.NODE_ENV}`);
robot.logger.info(`... | // Description:
// for initialize
//
"use strict";
const config = require("config");
const Raven = require('raven'); // TODO wrapper
function isProduction() {
return process.env.NODE_ENV === 'production';
}
function sentryIsSet() {
return config.sentry !== null;
}
module.exports = function(robot) {
... |
Remove unused github api instance | require('dotenv').config({silent: true});
const process = require('process');
const http = require('http');
const createHandler = require('github-webhook-handler');
const Configuration = require('./lib/configuration');
const Dispatcher = require('./lib/dispatcher');
const installations = require('./lib/installations')... | require('dotenv').config({silent: true});
const process = require('process');
const http = require('http');
const createHandler = require('github-webhook-handler');
const GitHubApi = require('github');
const Configuration = require('./lib/configuration');
const Dispatcher = require('./lib/dispatcher');
const installat... |
Allow other middleware by calling `cb()` | 'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} res
* @api public
*/
module.exports = function (opts) {
return function (res, file, cb) {
opts = opts || { info: 'cyan' };
... | 'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} res
* @api public
*/
module.exports = function (opts) {
return function (res, file) {
opts = opts || { info: 'cyan' };
... |
Fix typo on output name, add module concat plugin. | const path = require('path')
const webpack = require('webpack')
module.exports = {
context: __dirname,
entry: './src/index.js',
devtool: 'source-map',
output: {
library: 'es2015-starter',
libraryTarget: 'umd',
path: path.resolve('dist'),
filename: 'es2015-starter.js',
},
resolve: {
ex... | const path = require('path')
module.exports = {
context: __dirname,
entry: './src/index.js',
devtool: 'source-map',
output: {
library: 'es2016-starter',
libraryTarget: 'umd',
path: path.resolve('dist'),
filename: 'es2015-starter.js',
},
resolve: {
extensions: ['.js'],
modules: [
... |
Use the update function's time argument in the spinning example and cleanup code. | var Gesso = require('gesso');
var fillRotatedRect = require('./helpers').fillRotatedRect;
// Create the game object
var game = new Gesso();
// We'll use closures for game variables
var angle = 0;
// This gets called every frame.
// Update your game state here.
game.update(function (t) {
// Calculate one rotation p... | var Gesso = require('gesso');
var fillRotatedRect = require('./helpers').fillRotatedRect;
// Create the game object
var game = new Gesso();
// We'll use closures for game variables
var seconds = 0;
// This gets called every frame. Update your game state here.
game.update(function () {
// Calculate the time passed,... |
Remove "x-powered-by" header (for security) | /**
server
The backbone of the server module. In development, this runs proxied through
BrowserSync server.
@param {Object} options Options passed on to "globals"
@param {Function} next Called when server successfully initialized
**/
var reorg = require("reorg");
module.exports = reorg(function(options,... | /**
server
The backbone of the server module. In development, this runs proxied through
BrowserSync server.
@param {Object} options Options passed on to "globals"
@param {Function} next Called when server successfully initialized
**/
var reorg = require("reorg");
module.exports = reorg(function(options,... |
Remove markup-accepting signature of Document | 'use strict';
var util = require('util');
var Node = require('./node');
var Element = require('./nodes/element');
var makeElement = require('./nodes/make-element');
function Document(options) {
Node.call(this, {
tagName: 'html',
nodeType: 9,
parseOptions: options
});
this.documentElement = new Element({
t... | 'use strict';
var util = require('util');
var Node = require('./node');
var Element = require('./nodes/element');
var makeElement = require('./nodes/make-element');
function Document(markup, options) {
if (typeof markup !== 'string') {
options = markup;
markup = null;
}
Node.call(this, {
tagName: 'html',
... |
Add top offset to prevent top bar from cropping the top stack | 'use strict'
const fg = require('d3-fg')
const render = require('nanohtml')
const morphdom = require('morphdom')
const debounce = require('debounce')
const createActions = require('./actions')
const createState = require('./state')
const graph = require('./cmp/graph')(render)
const ui = require('./cmp/ui')(render)
mod... | 'use strict'
const fg = require('d3-fg')
const render = require('nanohtml')
const morphdom = require('morphdom')
const debounce = require('debounce')
const createActions = require('./actions')
const createState = require('./state')
const graph = require('./cmp/graph')(render)
const ui = require('./cmp/ui')(render)
mod... |
Undo accidental version bump caused by Makefile | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.1.7',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='kyle@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_pac... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.1.8',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='kyle@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_pac... |
Add correct syntax for environment variable | import csv
import re
import os
from elasticsearch import Elasticsearch
es = Elasticsearch({'host': os.environ['ELASTICSEARCH_URL']})
with open('data/ParcelCentroids.csv', 'r') as csvfile:
print "open file"
csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',')
curren... | import csv
import re
from elasticsearch import Elasticsearch
es = Elasticsearch({'host': ELASTICSEARCH_URL})
with open('data/ParcelCentroids.csv', 'r') as csvfile:
print "open file"
csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',')
current_row = 0
for row in c... |
Send button disabled as long as there is no message | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
... | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
... |
Remove duplicated slash in virus_scan | from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
from django.core.signing import TimestampSigner
class BaseEngine:
def __init__(self):
self.signer = TimestampSigner()
def get_webhook_url(self):
return "{}://{}{}?token={}".format(
"https",... | from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
from django.core.signing import TimestampSigner
class BaseEngine:
def __init__(self):
self.signer = TimestampSigner()
def get_webhook_url(self):
return "{}://{}/{}?token={}".format(
"https"... |
Check if participant exists when tracking pixel is requested | <?php
namespace Intracto\SecretSantaBundle\Controller;
use Intracto\SecretSantaBundle\Response\TransparentPixelResponse;
use Intracto\SecretSantaBundle\Entity\Participant;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpKe... | <?php
namespace Intracto\SecretSantaBundle\Controller;
use Intracto\SecretSantaBundle\Response\TransparentPixelResponse;
use Intracto\SecretSantaBundle\Entity\Participant;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpK... |
Revert "For removing the FlagShip section in the shipping settings tab, avoid hardcoding the FlagShip shipping method id."
This reverts commit 1ca4ad0917decb824fc7ea3dc7cb1d27b5612738. | <?php
namespace FS\Components\Event\Listener;
use FS\Injection\I;
use FS\Components\AbstractComponent;
use FS\Context\ApplicationListenerInterface;
use FS\Components\Event\NativeHookInterface;
use FS\Context\ConfigurableApplicationContextInterface as Context;
use FS\Context\ApplicationEventInterface as Event;
use FS\... | <?php
namespace FS\Components\Event\Listener;
use FS\Components\AbstractComponent;
use FS\Context\ApplicationListenerInterface;
use FS\Components\Event\NativeHookInterface;
use FS\Context\ConfigurableApplicationContextInterface as Context;
use FS\Context\ApplicationEventInterface as Event;
use FS\Components\Event\App... |
Move component actions to the bottom of the file | import Ember from 'ember';
const {
computed,
defineProperty
} = Ember;
export default Ember.Component.extend({
classNames: ['f-default__row'],
model: null,
type: 'text',
placeholder: '',
value: null,
valuePath: '',
validation: null,
isTyping: false,
notValidating: computed.not('validation.isVa... | import Ember from 'ember';
const {
computed,
defineProperty
} = Ember;
export default Ember.Component.extend({
classNames: ['f-default__row'],
model: null,
type: 'text',
placeholder: '',
value: null,
valuePath: '',
validation: null,
isTyping: false,
init() {
var valuePath = this.get('value... |
Add useful constructor to range filter | <?php
/**
* Range Filter
*
* @uses Elastica_Filter_Abstract
* @category Xodoa
* @package Elastica
* @author Nicolas Ruflin <spam@ruflin.com>
* @link http://www.elasticsearch.org/guide/reference/query-dsl/range-filter.html
*/
class Elastica_Filter_Range extends Elastica_Filter_Abstract
{
protected $_fields = ar... | <?php
/**
* Range Filter
*
* @uses Elastica_Filter_Abstract
* @category Xodoa
* @package Elastica
* @author Nicolas Ruflin <spam@ruflin.com>
* @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/range_query/
*/
class Elastica_Filter_Range extends Elastica_Filter_Abstract
{
protected $_fiel... |
Send "no such channel" message on NAMES with a nonexistent channel | from twisted.words.protocols import irc
from txircd.modbase import Command
class NamesCommand(Command):
def onUse(self, user, data):
for chan in data["targetchan"]:
user.report_names(chan)
def processParams(self, user, params):
if user.registered > 0:
user.sendMessage(irc.ERR_NOTREGISTERED, "NAMES", ":Yo... | from twisted.words.protocols import irc
from txircd.modbase import Command
class NamesCommand(Command):
def onUse(self, user, data):
for chan in data["targetchan"]:
user.report_names(chan)
def processParams(self, user, params):
if user.registered > 0:
user.sendMessage(irc.ERR_NOTREGISTERED, "NAMES", ":Yo... |
Fix migration 211 to handle lack of data. | """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wik... | """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wik... |
Update AWS::FMS::Policy per 2020-06-18 changes | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSProperty, AWSObject, Tags
from .validators import json_checker, boolean
class IEMap(AWSProperty):
props = {
'ACCOUNT': ([basestring], False),
'ORGUNIT': ([basestrin... | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSProperty, AWSObject, Tags
from .validators import json_checker, boolean
class IEMap(AWSProperty):
props = {
'ACCOUNT': ([basestring], False),
}
class Policy(AWSObject... |
Allow modify experiment status via REST API. | from django.contrib.auth.models import User, Group
from rest_framework import serializers
from damis.models import Dataset, Algorithm, Experiment
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSeria... | from django.contrib.auth.models import User, Group
from rest_framework import serializers
from damis.models import Dataset, Algorithm, Experiment
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSeria... |
Use STATIC_DRAW as default WebGL buffer usage | /**
* @module ol/webgl/Buffer
*/
import _ol_webgl_ from '../webgl.js';
/**
* @enum {number}
*/
const BufferUsage = {
STATIC_DRAW: _ol_webgl_.STATIC_DRAW,
STREAM_DRAW: _ol_webgl_.STREAM_DRAW,
DYNAMIC_DRAW: _ol_webgl_.DYNAMIC_DRAW
};
/**
* @constructor
* @param {Array.<number>=} opt_arr Array.
* @param {nu... | /**
* @module ol/webgl/Buffer
*/
import _ol_webgl_ from '../webgl.js';
/**
* @enum {number}
*/
const BufferUsage = {
STATIC_DRAW: _ol_webgl_.STATIC_DRAW,
STREAM_DRAW: _ol_webgl_.STREAM_DRAW,
DYNAMIC_DRAW: _ol_webgl_.DYNAMIC_DRAW
};
/**
* @constructor
* @param {Array.<number>=} opt_arr Array.
* @param {nu... |
Use split_up in both places | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(b... | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(b... |
Remove duplicate declaration of componentWillUnmount
Remove duplicate declaration of componentWillUnmount and move `this._isMounted = true` inside componentDidMount | /* @flow */
import React, {Component} from 'react';
import StyleKeeper from '../style-keeper';
export default class StyleSheet extends Component {
static contextTypes = {
_radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper)
};
constructor() {
super(...arguments);
this.state = this._getCSSS... | /* @flow */
import React, {Component} from 'react';
import StyleKeeper from '../style-keeper';
export default class StyleSheet extends Component {
static contextTypes = {
_radiumStyleKeeper: React.PropTypes.instanceOf(StyleKeeper)
};
constructor() {
super(...arguments);
this.state = this._getCSSS... |
Add suffixes to all gifs | import os
def remove_image_from_csvs(image):
for csv in os.listdir("."):
if csv[-4:] != ".csv":
continue
with open(csv, "r") as h:
lines = h.readlines()
modified = False
for x in range(len(lines)):
if image in lines[x]:
lines[x] = ... | import os
def remove_image_from_csvs(image):
for csv in os.listdir("."):
if csv[-4:] != ".csv":
continue
with open(csv, "r") as h:
lines = h.readlines()
modified = False
for x in range(len(lines)):
if image in lines[x]:
del lines[x... |
Use Laravel base controller in example | <?php
// Add the ServiceProvider
// Create the oauth-providers config file
// Create a route:
Route::get('login/{provider}', ['uses' => 'SocialController@login']);
// Create a controller:
use CodeZero\OAuth\Contracts\Authenticator;
use Illuminate\Routing\Controller;
class SocialController extends Controller
{
... | <?php
// Add the ServiceProvider
// Create the oauth-providers config file
// Create a route:
Route::get('login/{provider}', ['uses' => 'SocialController@login']);
// Create a controller:
use CodeZero\OAuth\Contracts\Authenticator;
class SocialController extends Controller
{
public function __construct()
... |
Update imports to use json extensions in fixtures. | /**
* Tag Manager datastore fixtures.
*
* Site Kit by Google, Copyright 2020 Google 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
*
* https://www.apache.org/licenses/LICENS... | /**
* Tag Manager datastore fixtures.
*
* Site Kit by Google, Copyright 2020 Google 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
*
* https://www.apache.org/licenses/LICENS... |
Fix exception with adding paths that don't exist. | <?php
namespace ZfcTwig\Service;
use Zend\ServiceManager\FactoryInterface;
use Twig_Loader_Filesystem;
use Zend\ServiceManager\ServiceLocatorInterface;
class TwigDefaultLoaderFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @retur... | <?php
namespace ZfcTwig\Service;
use Zend\ServiceManager\FactoryInterface;
use Twig_Loader_Filesystem;
use Zend\ServiceManager\ServiceLocatorInterface;
class TwigDefaultLoaderFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @retur... |
Resolve ONLY file:// deps relative to package root, everything else CWD | "use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")
module.exports = function (spec, where, cb) {
if (where instanceof Function) cb = where, where = null
if (where == null) where = "."
cb = dz(cb)
try {
var dep = npa(spec)
}
ca... | "use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")
module.exports = function (spec, where, cb) {
if (where instanceof Function) cb = where, where = null
if (where == null) where = "."
cb = dz(cb)
try {
var dep = npa(spec)
}
ca... |
Add Subscriber dependency to droninit | package org.inaetics.dronessimulator.drone.droneinit;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.inaetics.dronessimulator.discovery.api.Discoverer;
import org.inaetics.dronessimulator.pubsub.api.subscriber.Subscriber;
import org.osgi.framework.BundleCon... | package org.inaetics.dronessimulator.drone.droneinit;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.inaetics.dronessimulator.discovery.api.Discoverer;
import org.osgi.framework.BundleContext;
public class Activator extends DependencyActivatorBase {
@O... |
Use IOException instead of Throwable for not successful http status | package de.fau.amos.virtualledger.android.api.shared;
import android.util.Log;
import java.io.IOException;
import io.reactivex.subjects.PublishSubject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RetrofitCallback<T> implements Callback<T> {
private static final Str... | package de.fau.amos.virtualledger.android.api.shared;
import android.util.Log;
import io.reactivex.subjects.PublishSubject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RetrofitCallback<T> implements Callback<T> {
private static final String TAG = RetrofitCallback.cl... |
Add function method that gives the resource location of the registry
name. Can be used for sound events etc | package info.u_team.u_team_core.util.registry;
import java.util.*;
import java.util.function.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;
public class CommonDeferredRegister<R ext... | package info.u_team.u_team_core.util.registry;
import java.util.*;
import java.util.function.Supplier;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;
public class CommonDeferredRegister<R extends IForgeRegistryEntry<R>> implemen... |
Fix redis initialization in tests | # -*- coding: utf-8 -*-
from flask import Flask
from flask_split import split
from flask_split.core import _get_redis_connection
class TestCase(object):
def setup_method(self, method):
self.app = Flask(__name__)
self.app.debug = True
self.app.secret_key = 'very secret'
self.app.re... | # -*- coding: utf-8 -*-
from flask import Flask
from flask_split import split
from redis import Redis
class TestCase(object):
def setup_method(self, method):
self.redis = Redis()
self.redis.flushall()
self.app = Flask(__name__)
self.app.debug = True
self.app.secret_key = '... |
Unify component name and filename. | import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import InputContainer from '../Input/InputContainer';
import { inputChanged } from './PlatbyActions';
import {
formatValue,
inputOptions,
inputValid,
isInputEnabled,
isInputVisible
} from './platbyReducer';
const mapStateToProps = (st... | import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import InputContainer from '../Input/InputContainer';
import { inputChanged } from './PlatbyActions';
import {
formatValue,
inputOptions,
inputValid,
isInputEnabled,
isInputVisible
} from './platbyReducer';
const mapStateToProps = (st... |
Update json.loads line for python 3.5
Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'".
Fixed it by decoding downloaded json to utf-8 | #!/usr/bin/env python
"""
Snipped to download current IKEA ZLL OTA files into ~/otau
compatible with python 3.
"""
import os
import json
try:
from urllib.request import urlopen, urlretrieve
except ImportError:
from urllib2 import urlopen
from urllib import urlretrieve
f = urlopen("http://fw.ota.homesmart.ikea.net... | #!/usr/bin/env python
"""
Snipped to download current IKEA ZLL OTA files into ~/otau
compatible with python 3.
"""
import os
import json
try:
from urllib.request import urlopen, urlretrieve
except ImportError:
from urllib2 import urlopen
from urllib import urlretrieve
f = urlopen("http://fw.ota.homesmart.ikea.net... |
Fix tear down click handler problem in tests
It's not obvious what "the way" to teardown window event handlers is in
Ember. The datacenter-picker is permanently in the app during usage, but
in tests I'm assuming it gets added and removed lots.
So when you run the tests, as the tests aren't run in an isolated runner
t... | import Mixin from '@ember/object/mixin';
import { next } from '@ember/runloop';
import { get } from '@ember/object';
const isOutside = function(element, e) {
if (element) {
const isRemoved = !e.target || !document.contains(e.target);
const isInside = element === e.target || element.contains(e.target);
re... | import Mixin from '@ember/object/mixin';
import { next } from '@ember/runloop';
import { get } from '@ember/object';
const isOutside = function(element, e) {
const isRemoved = !e.target || !document.contains(e.target);
const isInside = element === e.target || element.contains(e.target);
return !isRemoved && !isI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.