text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change internal iface to eth0 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Meta extends REST_Controller {
public function index_get()
{
$response = array(
'id' => 'sw',
'name' => 'Scaleway',
'server_nick_name' => 'Server',
'default_region' => 'par1',... | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Meta extends REST_Controller {
public function index_get()
{
$response = array(
'id' => 'sw',
'name' => 'Scaleway',
'server_nick_name' => 'Server',
'default_region' => 'par1',... |
Delete unused webob conversion method | """Helpers for WebOb requests and responses."""
import webob
def webob_to_django_response(webob_response):
"""Returns a django response to the `webob_response`"""
from django.http import HttpResponse
django_response = HttpResponse(
webob_response.app_iter,
content_type=webob_response.cont... | """Helpers for WebOb requests and responses."""
import webob
def webob_to_django_response(webob_response):
"""Returns a django response to the `webob_response`"""
from django.http import HttpResponse
django_response = HttpResponse(
webob_response.app_iter,
content_type=webob_response.cont... |
Allow vscode install on windows | var fs = require('fs');
var getHomePath = require('home-path');
var logHelper = require('../util/log-helper');
var path = require('path');
var process = require('process');
var symlinkOrReplaceFilesInFolderSync = require('../util/symlink-or-replace-files-in-folder-sync');
function getVSCodeConfigDir() {
var baseDir ... | var fs = require('fs');
var getHomePath = require('home-path');
var logHelper = require('../util/log-helper');
var path = require('path');
var process = require('process');
var symlinkOrReplaceFilesInFolderSync = require('../util/symlink-or-replace-files-in-folder-sync');
function getVSCodeConfigDir() {
var baseDir ... |
Enable gcm and email module | import 'newrelic';
// Socket
import '../modules/socket/socket-server';
// Auth modules
import '../modules/facebook/facebook';
import '../modules/google/google';
import '../modules/session/session';
import '../modules/signin/signin';
import '../modules/signup/signup';
import '../modules/resource/resource';
/* ########... | import 'newrelic';
// Socket
import '../modules/socket/socket-server';
// Auth modules
import '../modules/facebook/facebook';
import '../modules/google/google';
import '../modules/session/session';
import '../modules/signin/signin';
import '../modules/signup/signup';
import '../modules/resource/resource';
/* ########... |
Add .mpg video extension to supported list | module.exports = {
isPlayable,
isVideo,
isAudio,
isPlayableTorrent
}
var path = require('path')
/**
* Determines whether a file in a torrent is audio/video we can play
*/
function isPlayable (file) {
return isVideo(file) || isAudio(file)
}
function isVideo (file) {
var ext = path.extname(file.name).toL... | module.exports = {
isPlayable,
isVideo,
isAudio,
isPlayableTorrent
}
var path = require('path')
/**
* Determines whether a file in a torrent is audio/video we can play
*/
function isPlayable (file) {
return isVideo(file) || isAudio(file)
}
function isVideo (file) {
var ext = path.extname(file.name).toL... |
Use addAssets to add font files.
Since v1.2, 2015-Sept-21:
Backwards-incompatible change for package authors: Static assets in
package.js files must now be explicitly declared by using addAssets
instead of addFiles. Previously, any file that didn't have a source
handler was automatically registered as a server... | Package.describe({
name: 'chriswessels:glyphicons-halflings',
version: '2.0.0',
summary: "This simple smart package adds the Glyphicon Halflings font-face to Meteor.",
git: 'https://github.com/chriswessels/meteor-glyphicons-halflings.git'
});
Package.onUse(function (api){
api.addAssets([
'lib/glyphicons-... | Package.describe({
name: 'chriswessels:glyphicons-halflings',
version: '2.0.0',
summary: "This simple smart package adds the Glyphicon Halflings font-face to Meteor.",
git: 'https://github.com/chriswessels/meteor-glyphicons-halflings.git'
});
Package.onUse(function (api){
api.addFiles('lib/glyphicons-halflin... |
Add more description to input example. | 'use strict';
/* eslint-disable indent */
module.exports = function(tx) {
var body = tx.get('body');
tx.create({
id: 'title',
type: 'heading',
level: 1,
content: 'Input Element'
});
body.show('title');
tx.create({
id: 'intro',
type: 'paragraph',
content: [
"You can use cus... | 'use strict';
/* eslint-disable indent */
module.exports = function(tx) {
var body = tx.get('body');
tx.create({
id: 'title',
type: 'heading',
level: 1,
content: 'Input Element'
});
body.show('title');
tx.create({
id: 'intro',
type: 'paragraph',
content: [
"You can use cus... |
Update old fixtures and add a method to filter site on deleted=false | <?php
namespace PHPOrchestra\ModelBundle\Repository;
use Doctrine\ODM\MongoDB\DocumentRepository;
use PHPOrchestra\ModelInterface\Model\SiteInterface;
use PHPOrchestra\ModelInterface\Repository\SiteRepositoryInterface;
/**
* Class SiteRepository
*/
class SiteRepository extends DocumentRepository implements SiteRep... | <?php
namespace PHPOrchestra\ModelBundle\Repository;
use Doctrine\ODM\MongoDB\DocumentRepository;
use PHPOrchestra\ModelInterface\Model\SiteInterface;
use PHPOrchestra\ModelInterface\Repository\SiteRepositoryInterface;
/**
* Class SiteRepository
*/
class SiteRepository extends DocumentRepository implements SiteRep... |
Remove the fully qualified module reference 'trombi.client'
If there happens to be more than one version of trombi on the system
(such as stable vs testing) the one in the PYTHONPATH that gets
encountered will be silently loaded when specifically loading the
module __init__ file for the other client. Now using the rel... | # Copyright (c) 2010 Inoi Oy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute,... | # Copyright (c) 2010 Inoi Oy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute,... |
Add the new contrail extension to neutron plugin config file
Change-Id: I2a1e90a2ca31314b7a214943b0f312471b11da9f | import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:... | import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:... |
Modify the interpnd cython generator to allow .NET output | #!/usr/bin/env python
import tempfile
import subprocess
import os
import sys
import re
import shutil
from mako.template import Template
dotnet = False
if len(sys.argv) > 1 and sys.argv[1] == '--dotnet':
dotnet = True
f = open('interpnd.pyx', 'r')
template = f.read()
f.close()
tmp_dir = tempfile.mkdtemp()
try:
... | #!/usr/bin/env python
import tempfile
import subprocess
import os
import sys
import re
import shutil
from mako.template import Template
f = open('interpnd.pyx', 'r')
template = f.read()
f.close()
tmp_dir = tempfile.mkdtemp()
try:
# Run templating engine
fn = os.path.join(tmp_dir, 'interpnd.pyx')
f = open... |
Add constant SUID and minor reformatting
svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=410556 | /* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
*
* 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/LIC... | /* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
*
* 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/LIC... |
Set ‘build’ as the default Grunt task | module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
cssmin: {
build: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<... | module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
cssmin: {
build: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<... |
Hide action buttons if the company is archived
This prevents bad data being added when a company
has been archived | const { getCompanyInvestmentProjects } = require('../../investment-projects/repos')
const { transformInvestmentProjectToListItem } = require('../../investment-projects/transformers')
const { transformApiResponseToCollection } = require('../../transformers')
async function renderInvestments (req, res, next) {
const t... | const { getCompanyInvestmentProjects } = require('../../investment-projects/repos')
const { transformInvestmentProjectToListItem } = require('../../investment-projects/transformers')
const { transformApiResponseToCollection } = require('../../transformers')
async function renderInvestments (req, res, next) {
const t... |
Return active thread count from the threadpool | /*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* 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
... | /*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* 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
... |
Use metaclasses to register node types. | import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
_nodeTypes = {}
class _NodeTypeRegistrar(type):
def __init__(self, name, bases, dict):
type.__init__(self, name, bases, dict)
_nodeTypes[self.nodeType] = self
class NodeType(object):
__metaclass__ = _NodeType... | import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
class NodeType(object):
nodeType = 'UNKNOWN'
def __init__(self):
pass
def freeze(self):
return (self.nodeType, self.__dict__)
@classmethod
def thaw(class_, d):
return class_(**d)
class Cli... |
Raise maxListeners so if you have 16 cores it doesn't complain | #!/usr/bin/env node
var log = require('./src/log.js'),
Parent = require('./src/parent.js'),
ctrl = require('daemonctrl'),
currentParent = new Parent(),
config, sender;
function onExit(error) {
currentParent.stop();
ctrl.end();
if (error) {
throw e;
}
process.exit();
}
//sinc... | #!/usr/bin/env node
var log = require('./src/log.js'),
Parent = require('./src/parent.js'),
ctrl = require('daemonctrl'),
currentParent = new Parent(),
config, sender;
function onExit(error) {
currentParent.stop();
ctrl.end();
if (error) {
throw e;
}
process.exit();
}
proces... |
Refactor MeanQ to use Array.reduce(). | /**
* checks if there are scores which can be combined
*/
function checkValidity (scores) {
if (scores == null) {
throw new Error('There must be a scores object parameter')
}
if (Object.keys(scores).length <= 0) {
throw new Error('At least one score must be passed')
}
}
/**
* Score canidate based on... | /**
* checks if there are scores which can be combined
*/
function checkValidity (scores) {
if (scores == null) {
throw new Error('There must be a scores object parameter')
}
if (Object.keys(scores).length <= 0) {
throw new Error('At least one score must be passed')
}
}
/**
* Score canidate based on... |
Allow users to read the name | package se.arbetsformedlingen.venice.probe;
import java.util.Objects;
public class Application {
private String application;
Application(String application) {
this.application = application;
}
String getApplicationName() {
return application;
}
@Override
public boolean e... | package se.arbetsformedlingen.venice.probe;
import java.util.Objects;
public class Application {
private String application;
Application(String application) {
this.application = application;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o =... |
Add ip on ip dev | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This chec... | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This chec... |
Refactor pairing internals into functions for readability | var uuid = require('uuid/v1')
var requests = new Set()
function getRequest () {
var reqs = Array.from(requests.values())
if (reqs.length > 0) {
var req = reqs[Math.floor(Math.random() * reqs.length)]
requests.delete(req)
return req
} else {
return null;
}
}
function newEvent (socket) {
if (... | var uuid = require('uuid/v1')
var requests = new Set()
function getRequest () {
var reqs = Array.from(requests.values())
if (reqs.length > 0) {
var req = reqs[Math.floor(Math.random() * reqs.length)]
requests.delete(req)
return req
} else {
return null;
}
}
function initialize (socket) {
so... |
Use python interpreter instead of sys.executable | """
Docs with Sphinx.
"""
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join... | """
Docs with Sphinx.
"""
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join... |
Add TODO for removing stubs | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus... | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus... |
style: Fix the misspell in docstring
Datatime -> Datetime | """Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"... | """Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"... |
MINOR: Advance system test ducktape dependency from 0.3.10 to 0.4.0
Previous version of ducktape was found to have a memory leak which caused occasional failures in nightly runs.
Author: Geoff Anderson <geoff@confluent.io>
Reviewers: Ewen Cheslack-Postava <ewen@confluent.io>
Closes #1165 from granders/minor-advance... | # 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"); you may not use ... | # 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"); you may not use ... |
Use Google Charts as like before
We don't have to do this upgrade right now. | import Component from '@ember/component';
function createEvent(name) {
let event = document.createEvent('Event');
event.initEvent(name, true, true);
return event;
}
export default Component.extend({
tagName: '',
didInsertElement() {
let script = document.createElement('script');
s... | /*global google*/
import Component from '@ember/component';
function createEvent(name) {
let event = document.createEvent('Event');
event.initEvent(name, true, true);
return event;
}
export default Component.extend({
tagName: '',
didInsertElement() {
let script = document.createElement('s... |
Refactor timeline method call to use kwargs | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['cr... | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['cr... |
Change conversation token to a pointer to allow it to be null in the json | package api
// RootResponse object which will be formatted to json and sent back to google and onto the user.
type RootResponse struct {
ConversationToken *string `json:"conversation_token"`
ExpectUserResponse bool `json:"expect_user_response"`
ExpectedInputs []ExpectedInput `json:"expected_... | package api
// RootResponse object which will be formatted to json and sent back to google and onto the user.
type RootResponse struct {
ConversationToken string `json:"conversation_token"`
ExpectUserResponse bool `json:"expect_user_response"`
ExpectedInputs []ExpectedInput `json:"expected_... |
Replace range prop to values | /**
* @copyright Copyright (c) 2020 Maxim Khorin <maksimovichu@gmail.com>
*/
'use strict';
const Base = require('./Validator');
module.exports = class RangeValidator extends Base {
constructor (config) {
super({
// values: []
not: false,
allowArray: false,
... | /**
* @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
*/
'use strict';
const Base = require('./Validator');
module.exports = class RangeValidator extends Base {
constructor (config) {
super({
range: null,
not: false,
allowArray: false,
... |
Update py2app script for Qt 5.11 | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... |
Add missing installed apps for tests | """
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'hrzeqwz0@nps2#ns3_qkqz*#5=)1bxcdwa*h__hta0f1bqr2e!'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = ("tests/templates", )
INSTALLED_APPS = (
'django_nose',
'django.contrib.contenttypes',
'django.... | """
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'hrzeqwz0@nps2#ns3_qkqz*#5=)1bxcdwa*h__hta0f1bqr2e!'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = ("tests/templates", )
INSTALLED_APPS = (
'django_nose',
)
for dir in os.listdir("tests/apps"):
if o... |
Introduce base party form, limit `archived` flag to update form | """
byceps.blueprints.admin.party.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import BooleanField, DateTimeField, IntegerField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ..... | """
byceps.blueprints.admin.party.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import BooleanField, DateTimeField, IntegerField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ..... |
Implement a test specifically for abbreviations | from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecut... | from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
... |
Use switches rather than switches.keys().
Minor cosmetic change, really. | #!/usr/bin/python
"Create a 64-node tree network, and test connectivity using ping."
from mininet.log import setLogLevel
from mininet.net import init, Mininet
from mininet.node import KernelSwitch, UserSwitch, OVSKernelSwitch
from mininet.topolib import TreeNet
def treePing64():
"Run ping test on 64-node tree ne... | #!/usr/bin/python
"Create a 64-node tree network, and test connectivity using ping."
from mininet.log import setLogLevel
from mininet.net import init, Mininet
from mininet.node import KernelSwitch, UserSwitch, OVSKernelSwitch
from mininet.topolib import TreeNet
def treePing64():
"Run ping test on 64-node tree ne... |
Add .js extension for require | /**
* Run test specs in node environment
* Usage:
* $ cd seajs
* $ node tests/runner-node.js
*/
require('../lib/sea.js')
define('./tests/node-runner', function(require) {
var test = require('./test')
var suites = require('./meta').map(function(suite) {
return './' + suite + '/meta'
})
require.a... | /**
* Run test specs in node environment
* Usage:
* $ cd seajs
* $ node tests/runner-node.js
*/
require('../lib/sea')
define('./tests/node-runner', function(require) {
var test = require('./test')
var suites = require('./meta').map(function(suite) {
return './' + suite + '/meta'
})
require.asyn... |
Allow dev server to be accessed from the network. | var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: './build',
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /src\/.+\.js$/,
loader: 'babel?prese... | var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: './build',
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /src\/.+\.js$/,
loader: 'babel?prese... |
Use PORT env var for Heroku | 'use strict';
let config = require('./config');
let express = require('express');
let app = express();
console.log('Starting.');
app.listen(process.env.PORT || 12345, () => {
console.log('Server started.');
});
// API parent route
let api = express.Router({ mergeParams: true });
app.use(config.API_R... | 'use strict';
let config = require('./config');
let express = require('express');
let app = express();
console.log('Starting.');
app.listen(12345, () => {
console.log('Server started.');
});
// API parent route
let api = express.Router({ mergeParams: true });
app.use(config.API_ROOT, api);
/**
... |
Remove start main activity task from handler if back button is pressed during loading process. | package com.tuenti.tuentitv.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import butterknife.InjectView;
import com.tuenti.tuentitv.R;
import java.util.LinkedList;
import java.util.List;
/**
* @author Pedro Vicente Gómez Sánchez.
... | package com.tuenti.tuentitv.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import butterknife.InjectView;
import com.tuenti.tuentitv.R;
import java.util.LinkedList;
import java.util.List;
/**
* @author Pedro Vicente Gómez Sánchez.
... |
Use score as well in annotations table | #!/usr/bin/env python
"""A script to sum the rpkm values for all genes for each annotation."""
import pandas as pd
import argparse
import sys
def main(args):
rpkm_table =pd.read_table(args.rpkm_table, index_col=0)
annotations = pd.read_table(args.annotation_table, header=None, names=["gene_id", "annotation", ... | #!/usr/bin/env python
"""A script to sum the rpkm values for all genes for each annotation."""
import pandas as pd
import argparse
import sys
def main(args):
rpkm_table =pd.read_table(args.rpkm_table, index_col=0)
annotations = pd.read_table(args.annotation_table, header=None, names=["gene_id", "annotation", ... |
Remove special case from StringIO. | from io import StringIO
try:
FileNotFoundError = FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdo... | try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
FileNotFoundError = FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanag... |
Remove extract magic string for DOT, use String.format for greater clarity | package seedu.todo.ui.components;
import javafx.fxml.FXML;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import seedu.todo.models.Task;
import seedu.todo.ui.UiPartLoader;
public class TaskListTaskItem extends MultiComponent {
private static final String FXML_PATH = "c... | package seedu.todo.ui.components;
import javafx.fxml.FXML;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import seedu.todo.models.Task;
import seedu.todo.ui.UiPartLoader;
public class TaskListTaskItem extends MultiComponent {
private static final String FXML_PATH = "c... |
Bump version for new build | from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup (
name = 'pyvault',
version = '1.4.4.3',
description = 'Python password manager',
long_description = lon... | from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup (
name = 'pyvault',
version = '1.4.4.2',
description = 'Python password manager',
long_description = lon... |
fix(switch): Switch component refactored to stateful. | import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
const styles = () => ({
switchBase: {
color: '#c7c8c9',
'&$checked': {
color: '#0072CE',
},
'&$checked + $track': {
backgroundColor: '#0072CE',
... | import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
const CustomSwitch = withStyles({
switchBase: {
color: '#c7c8c9',
'&$checked': {
color: '#0072CE',
},
'&$checked + $track': {
backgroundColor: '#0072CE',
... |
Use README.md as long description | #!/usr/bin/env python
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='hashmerge',
version='0.1',
url='https://github.com/lebauce/hashmerge',
author='Sylvain Baubeau',
author_email='bob@glumol.com',
description="Merges two arbitrari... | #!/usr/bin/env python
from setuptools import setup
setup(
name='hashmerge',
version='0.1',
url='https://github.com/lebauce/hashmerge',
author='Sylvain Baubeau',
author_email='bob@glumol.com',
description="Merges two arbitrarily deep hashes into a single hash.",
license='MIT',
include_p... |
Make epsilon smaller to be able to compare smaller scores | <?php
namespace lucidtaz\minimax\engine;
use Closure;
use lucidtaz\minimax\game\Decision;
class DecisionWithScore
{
const EPSILON = 0.00001;
/**
* @var Decision
*/
public $decision = null;
/**
* @var float
*/
public $score;
/**
* @var integer How deep in the execut... | <?php
namespace lucidtaz\minimax\engine;
use Closure;
use lucidtaz\minimax\game\Decision;
class DecisionWithScore
{
/**
* @var Decision
*/
public $decision = null;
/**
* @var float
*/
public $score;
/**
* @var integer How deep in the execution tree this result was found... |
Remove @Component for optional encoder
Instantiation is optional as to avoid introducing a hard dependency on spring-security. | package org.jasig.cas.authentication.handler;
import javax.validation.constraints.NotNull;
/**
* Pass the encode/decode responsibility to a delegated Spring Security
* password encoder.
*
* @author Joe McCall
* @since 4.3
*/
public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder {
... | package org.jasig.cas.authentication.handler;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
/**
* Pass the encode/decode responsibility to a delegated Spring Security
* password encoder.
*
* @author Joe McCall
* @since 4.3
*/
@Component("springSecurityDelegatingP... |
Introduce a new error class. | #
## PyMoira client library
##
## This file contains the Moira-related errors.
#
import moira_constants
class MoiraBaseError(Exception):
"""Any exception thrown by the library is inhereted from this"""
pass
class MoiraConnectionError(MoiraBaseError):
"""An error which prevents the client from having or continuin... | #
## PyMoira client library
##
## This file contains the Moira-related errors.
#
import moira_constants
class MoiraBaseError(Exception):
"""Any exception thrown by the library is inhereted from this"""
pass
class MoiraConnectionError(MoiraBaseError):
"""An error which prevents the client from having or continuin... |
Add support for debug mode | var AWS = require("aws-sdk");
var s3 = new AWS.S3({
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET
});
var elasticsearchUrl = process.env.ELASTICSEARCH_URL;
var s3Bucket = process.env.S3_BUCKET;
var debug = process.env.DEBUG;
var importer = require("./importer")(s3, {debug: debug});
if... | var AWS = require("aws-sdk");
var s3 = new AWS.S3({
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET
});
var importer = require("./importer")(s3);
if (!process.env.ELASTICSEARCH_URL) {
console.log("You must specify ELASTICSEARCH_URL");
process.exit(1);
}
if (process.env.S3_BUCKET) {... |
Add order to PerObjectSettings tool | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object... |
Add a `m.Fragment = "["` utility for JSX users. | "use strict"
var hyperscript = require("./hyperscript")
var request = require("./request")
var mountRedraw = require("./mount-redraw")
var m = function m() { return hyperscript.apply(this, arguments) }
m.m = hyperscript
m.trust = hyperscript.trust
m.fragment = hyperscript.fragment
m.Fragment = "["
m.mount = mountRedr... | "use strict"
var hyperscript = require("./hyperscript")
var request = require("./request")
var mountRedraw = require("./mount-redraw")
var m = function m() { return hyperscript.apply(this, arguments) }
m.m = hyperscript
m.trust = hyperscript.trust
m.fragment = hyperscript.fragment
m.mount = mountRedraw.mount
m.route ... |
[scripts] Use different way to determine 32/64-bit which returns mode of current binary, not of the system | import sim, syscall_strings, sys
if sys.maxsize == 2**31-1:
__syscall_strings = syscall_strings.syscall_strings_32
else:
__syscall_strings = syscall_strings.syscall_strings_64
def syscall_name(syscall_number):
return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_number)
class LogSyscall... | import sim, syscall_strings, platform
if platform.architecture()[0] == '64bit':
__syscall_strings = syscall_strings.syscall_strings_64
else:
__syscall_strings = syscall_strings.syscall_strings_32
def syscall_name(syscall_number):
return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_numbe... |
bugfix: Exclude results with matching inline configs when testing files | var _ = require('lodash');
module.exports = function(ast, filePath, plugins) {
var errors = [],
warnings = [];
_.each(plugins, function(plugin){
var results,
array;
if (plugin.severity === 2) {
array = errors;
} else if (plugin.severity === 1) {
array = warnings;
} els... | var _ = require('lodash');
module.exports = function(ast, filePath, plugins) {
var errors = [],
warnings = [];
_.each(plugins, function(plugin){
var results,
array;
if (plugin.severity === 2) {
array = errors;
} else if (plugin.severity === 1) {
array = warnings;
} ... |
Add optional path parameter to module_path helper | <?php
if (! function_exists('module_path')) {
function module_path($name, $path = '')
{
$module = app('modules')->find($name);
return $module->getPath().($path ? DIRECTORY_SEPARATOR.$path : $path);
}
}
if (! function_exists('config_path')) {
/**
* Get the configuration path.
... | <?php
if (! function_exists('module_path')) {
function module_path($name)
{
$module = app('modules')->find($name);
return $module->getPath();
}
}
if (! function_exists('config_path')) {
/**
* Get the configuration path.
*
* @param string $path
* @return string
... |
Add test suite to the distribution | from setuptools import setup
from tcxparser import __version__
setup(
name='python-tcxparser',
version=__version__,
author='Vinod Kurup',
author_email='vinod@kurup.com',
py_modules=['tcxparser', 'test_tcxparser'],
url='https://github.com/vkurup/python-tcxparser/',
license='BSD',
descrip... | from setuptools import setup
from tcxparser import __version__
setup(
name='python-tcxparser',
version=__version__,
author='Vinod Kurup',
author_email='vinod@kurup.com',
py_modules=['tcxparser', ],
url='https://github.com/vkurup/python-tcxparser/',
license='BSD',
description='Simple par... |
Bump the package version - 0.1.7
Change log:
- Updated documentation for better PyPI support
- Includes all the latest fixes until now | import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.7",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintainer = "Matthias Lee",
maintainer_e... | import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.6",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintainer = "Matthias Lee",
maintainer_e... |
Delete name nad email also | const initialState = {
readMore: false,
jwToken: null,
myEmail: null,
myName: null,
myFetch: null
}
export default function update (state = initialState, action) {
switch (action.type) {
case 'TOGGLE_READ_MORE':
return Object.assign({}, state, {
readMore: action.readMore
})
case... | const initialState = {
readMore: false,
jwToken: null,
myEmail: null,
myName: null,
myFetch: null
}
export default function update (state = initialState, action) {
switch (action.type) {
case 'TOGGLE_READ_MORE':
return Object.assign({}, state, {
readMore: action.readMore
})
case... |
Fix no-replace-server to accurately preview update
This override of OS::Nova::Server needs to reflect the fact
that it never replaces on update or the update --dry-run output
ends up being wrong.
Closes-Bug: 1561076
Change-Id: I9256872b877fbe7f91befb52995c62de006210ef | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
Remove rules which are now enabled by default
These template lint rules are now enabled in the 'recommended'
configuration so we don't need to override them in our config. | /* eslint-env node */
'use strict';
var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];
module.exports = {
extends: 'recommended',
rules: {
'bare-strings': ['?', '»', '—'].concat(defaultAllowedBase... | /* eslint-env node */
'use strict';
var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];
module.exports = {
extends: 'recommended',
rules: {
'bare-strings': ['?', '»', '—'].concat(defaultAllowedBase... |
Revert "Updated the boto requirement to 2.8.0"
This reverts commit add8a4a7d68b47ed5c24fefa5dde6e8e372804bf. | from setuptools import setup, find_packages
import dynamodb_sessions
long_description = open('README.rst').read()
major_ver, minor_ver = dynamodb_sessions.__version__
version_str = '%d.%d' % (major_ver, minor_ver)
setup(
name='django-dynamodb-sessions',
version=version_str,
packages=find_packages(),
... | from setuptools import setup, find_packages
import dynamodb_sessions
long_description = open('README.rst').read()
major_ver, minor_ver = dynamodb_sessions.__version__
version_str = '%d.%d' % (major_ver, minor_ver)
setup(
name='django-dynamodb-sessions',
version=version_str,
packages=find_packages(),
... |
Clean up control model tests | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for control model."""
from ggrc import db
from ggrc.models import Control
from integration.ggrc import TestCase
from integration.ggrc.models import factories
class TestControl(TestCase):
def tes... |
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc import db
from ggrc.models import Control
from integration.ggrc import TestCase
from .factories import ControlCategoryFactory, ControlFactory
from nose.plugins.skip import SkipTest
from nose.tools... |
Use actual byte string instead of hex2bin() on hex string | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(stric... | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(stric... |
Sort feed items by title first, then date. | package feedloggr2
import (
"github.com/jinzhu/gorm"
rss "github.com/jteeuwen/go-pkg-rss"
_ "github.com/mattn/go-sqlite3"
)
type Datastore interface {
GetItems(feed_url string) ([]*FeedItem, error)
ProcessChannels(feed *rss.Feed, channels []*rss.Channel)
ProcessItems(feed *rss.Feed, ch *rss.Channel, items []*r... | package feedloggr2
import (
"github.com/jinzhu/gorm"
rss "github.com/jteeuwen/go-pkg-rss"
_ "github.com/mattn/go-sqlite3"
)
type Datastore interface {
GetItems(feed_url string) ([]*FeedItem, error)
ProcessChannels(feed *rss.Feed, channels []*rss.Channel)
ProcessItems(feed *rss.Feed, ch *rss.Channel, items []*r... |
Remove extra whitespace from bug title
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk> | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# 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... | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# 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... |
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning. | # -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutori... | # -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutori... |
Fix decimal numbers limit to 2
while calculating the row total, javascript was called and on some quantity, a number with a big decimal part was appearing.In this PR it is fixed
Fixes https://github.com/opensuse/osem/issues/1709 | function update_price($this){
var id = $this.data('id');
// Calculate price for row
var value = $this.val();
var price = $('#price_' + id).text();
$('#total_row_' + id).text((value * price).toFixed(2));
// Calculate total price
var total = 0;
$('.total_row').each(function( index ) {
... | function update_price($this){
var id = $this.data('id');
// Calculate price for row
var value = $this.val();
var price = $('#price_' + id).text();
$('#total_row_' + id).text(value * price);
// Calculate total price
var total = 0;
$('.total_row').each(function( index ) {
total +... |
Use re instead of regex.
Don't rewrite the file in place.
(Reported by Andy Dustman.) | #!/usr/bin/env python
# Fix Python script(s) to reference the interpreter via /usr/bin/env python.
# Warning: this overwrites the file without making a backup.
import sys
import re
def main():
for file in sys.argv[1:]:
try:
f = open(file, 'r')
except IOError, msg:
print file, ': can\'t open :', msg
co... | #! /usr/bin/env python
# Fix Python script(s) to reference the interpreter via /usr/bin/env python.
import sys
import regex
import regsub
def main():
for file in sys.argv[1:]:
try:
f = open(file, 'r+')
except IOError:
print file, ': can\'t open for update'
continue
line = f.readline()
if regex.mat... |
Add comment explaining where runtime value comes from | "use strict";
var _ = require('lodash');
var defaultSettings = {
title: 'Model My Watershed',
itsi_embed: false,
itsi_enabled: true,
data_catalog_enabled: false,
base_layers: {},
stream_layers: {},
coverage_layers: {},
boundary_layers: {},
conus_perimeter: {},
draw_tools: [],
... | "use strict";
var _ = require('lodash');
var defaultSettings = {
title: 'Model My Watershed',
itsi_embed: false,
itsi_enabled: true,
data_catalog_enabled: false,
base_layers: {},
stream_layers: {},
coverage_layers: {},
boundary_layers: {},
conus_perimeter: {},
draw_tools: [],
... |
Fix null pointer exception when user has 0 devices associated with account | package com.google.sps.data;
import com.google.sps.data.ChromeOSDevice;
import java.util.ArrayList;
import java.util.List;
/*
* Class representing response to `list Chrome OS Devices` request.
* See https://developers.google.com/admin-sdk/directory/v1/reference/chromeosdevices/list
*/
public final class ListDevice... | package com.google.sps.data;
import com.google.sps.data.ChromeOSDevice;
import java.util.ArrayList;
import java.util.List;
/*
* Class representing response to `list Chrome OS Devices` request.
* See https://developers.google.com/admin-sdk/directory/v1/reference/chromeosdevices/list
*/
public final class ListDevice... |
Add more tests for Config | # -*- coding: utf-8 -*-
# Copyright 2015 grafana-dashboard-builder contributors
#
# 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 requi... | # -*- coding: utf-8 -*-
# Copyright 2015 grafana-dashboard-builder contributors
#
# 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 requi... |
Remove braces for one line functions | import React from 'react'
export const Checkbox = ({ id, nodes, onToggle }) => {
const node = nodes[id]
const { key, childIds, checked } = node
const handleChange = () => onToggle(id)
return (
<React.Fragment key={id}>
{key &&
<li>
<input type='checkbox' checked={checked} classNam... | import React from 'react'
export const Checkbox = ({ id, nodes, onToggle }) => {
const node = nodes[id]
const { key, childIds, checked } = node
const handleChange = () => {
onToggle(id)
}
return (
<React.Fragment key={id}>
{key &&
<li>
<input type='checkbox' checked={checked... |
Use py_limited_api="auto" in rust_with_cffi example | #!/usr/bin/env python
import platform
import sys
from setuptools import setup
from setuptools_rust import RustExtension
setup(
name="rust-with-cffi",
version="0.1.0",
classifiers=[
"License :: OSI Approved :: MIT License",
"Development Status :: 3 - Alpha",
"Intended Audience :: De... | #!/usr/bin/env python
import platform
import sys
from setuptools import setup
from setuptools_rust import RustExtension
setup(
name="rust-with-cffi",
version="0.1.0",
classifiers=[
"License :: OSI Approved :: MIT License",
"Development Status :: 3 - Alpha",
"Intended Audience :: De... |
Mark that we need Genshi from trunk. | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
from setuptools import setup
setup(
name = 'TracMasterTickets',
version = '2.1.1',
packages = ['mastertickets'],
package_data = { 'mastertickets': ['htdocs/*.js', 'htdocs/*.css' ] },
author = "Noah Kantrowitz",
author_email = "coderanger@yaho... | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
from setuptools import setup
setup(
name = 'TracMasterTickets',
version = '2.1',
packages = ['mastertickets'],
package_data = { 'mastertickets': ['htdocs/*.js', 'htdocs/*.css' ] },
author = "Noah Kantrowitz",
author_email = "coderanger@yahoo.... |
Move static propTypes & defaultProps outside of the component class | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Avatar extends PureComponent {
render() {
const { children, className, image, imageAlt, imageClassName, size, ...others } = this.props;
... | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Avatar extends PureComponent {
static propTypes = {
/** Component that will be placed top right of the avatar image. */
children: Pro... |
Add support for custom explorer URL | var loopback = require('loopback');
var boot = require('loopback-boot');
var explorer = require('loopback-component-explorer');
var path = require('path');
var app = module.exports = loopback();
//app.use(customBaseUrl+'/explorer', loopback.rest());
app.start = function() {
// start the web server
var customBa... | var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s... |
Make the children field in the api read only. | from rest_framework import serializers
from models import Page
class PageSerializer(serializers.ModelSerializer):
parent = serializers.PrimaryKeyRelatedField(required=False)
children = serializers.PrimaryKeyRelatedField(many=True, required=False, read_only=True)
class Meta:
model = Page
... | from rest_framework import serializers
from models import Page
class PageSerializer(serializers.ModelSerializer):
parent = serializers.PrimaryKeyRelatedField(required=False)
children = serializers.PrimaryKeyRelatedField(many=True, required=False)
class Meta:
model = Page
fields = (
... |
Correct test for the right missing days and present days.
1st and 2nd of September 1752 happened, so did 14th. 3rd to 13th did not. | from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet... | from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet... |
Add setSpriteTexture to the SpriteSheet class | 'use strict';
import Sprite from './sprite';
export default class SpriteSheet {
constructor(texture, width, height) {
this.texture = texture;
this.width = width;
this.height = height;
this.spriteCoordinates = {};
}
register(name, x, y, width, height) {
this.spriteCoordinates[name] = {
x: ... | 'use strict';
import Sprite from './sprite';
export default class SpriteSheet {
constructor(texture, width, height) {
this.texture = texture;
this.width = width;
this.height = height;
this.spriteCoordinates = {};
}
register(name, x, y, width, height) {
this.spriteCoordinates[name] = {
x: ... |
Add fallbacks for parsed Url | <?php
namespace Collectivism\Router;
class Request
{
public $method;
public $scheme;
public $host;
public $uri;
public $query;
public $fragment;
public function __construct()
{
$url = $_SERVER['PATH_INFO'];
$parsedUrl = parse_url($url);
$this->method = $_SERVER... | <?php
namespace Collectivism\Router;
class Request
{
public $method;
public $scheme;
public $host;
public $uri;
public $query;
public $fragment;
public function __construct()
{
$url = $_SERVER['PATH_INFO'];
$urlParts = parse_url($url);
$this->method = $_SERVER[... |
Use the spring component as well to allow for migrations | package net.stickycode.bootstrap.spring3;
import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core... | package net.stickycode.bootstrap.spring3;
import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core... |
Test on structured patch method updated | const VERBOSE = false;
var diff = require('../diff');
function log() {
VERBOSE && console.log.apply(console, arguments);
}
describe('#structuredPatch', function() {
it('should handle files with the last line changed', function() {
var res = diff.structuredPatch(
'oldfile', 'newfile',
'line2\nlin... | const VERBOSE = false;
var diff = require('../diff');
function log() {
VERBOSE && console.log.apply(console, arguments);
}
describe('#structuredPatch', function() {
it('should handle files with the last line changed', function() {
var res = diff.structuredPatch(
'oldfile', 'newfile',
'line2\nlin... |
Remove [] from around open()...split('\n')
`split()` already returns a list so you don't need to wrap it in another list. | #!/usr/bin/env python
import os
from setuptools import setup
import versioneer
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="fsspec",
version=versioneer.get_version(),
cmdclass=versioneer.g... | #!/usr/bin/env python
import os
from setuptools import setup
import versioneer
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="fsspec",
version=versioneer.get_version(),
cmdclass=versioneer.g... |
Update live object tests so that they know they should fire at 120fps | QUnit.test("CanGetLiveTicks", function(assert) {
var someGame = new TameGame.StandardGame();
var someObject = someGame.createObject();
var someScene = someGame.createScene();
var numTicks = 0;
someScene.addObject(someObject);
someScene.events.onTick(TameGame.UpdatePass.Mechanics, function (... | QUnit.test("CanGetLiveTicks", function(assert) {
var someGame = new TameGame.StandardGame();
var someObject = someGame.createObject();
var someScene = someGame.createScene();
var numTicks = 0;
someScene.addObject(someObject);
someScene.events.onTick(TameGame.UpdatePass.Mechanics, function (... |
Enable keyword arguments when requesting metafields | import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self, _options=None, **kwargs):
if _option... | import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self):
return shopify.resources.Metafield.... |
Use new extension setup() API | from __future__ import unicode_literals
import os
import pygst
pygst.require('0.10')
import gst
import gobject
from mopidy import config, ext
__version__ = '1.0.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-NAD'
ext_name = 'nad'
version = __version__
def get_default_config(self):
... | from __future__ import unicode_literals
import os
import pygst
pygst.require('0.10')
import gst
import gobject
from mopidy import config, ext
__version__ = '1.0.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-NAD'
ext_name = 'nad'
version = __version__
def get_default_config(self):
... |
Simplify repository name component regexp | package common
import (
"regexp"
)
// RepositoryNameComponentRegexp restricts registtry path components names to
// start with at least two letters or numbers, with following parts able to
// separated by one period, dash or underscore.
var RepositoryNameComponentRegexp = regexp.MustCompile(`[a-z0-9]{2,}(?:[._-][a-z... | package common
import (
"regexp"
)
// RepositoryNameComponentRegexp restricts registtry path components names to
// start with at least two letters or numbers, with following parts able to
// separated by one period, dash or underscore.
var RepositoryNameComponentRegexp = regexp.MustCompile(`[a-z0-9](?:[a-z0-9]+[._-... |
Fix bug where vector calculations returned Ints only | """
Linear algebra is cool.
"""
import math
def rotation(point, axis, sign=1):
"""
Rotate a point (or vector) about the origin in 3D space.
"""
def Rx(x, y, z, theta):
return (round(x, 1),
round(math.cos(theta) * y - math.sin(theta) * z, 1),
round(math.sin(theta... | """
Linear algebra is cool.
"""
import math
def rotation(point, axis, sign=1):
"""
Rotate a point (or vector) about the origin in 3D space.
"""
def Rx(x, y, z, theta):
return (int(x),
int(math.cos(theta) * y - math.sin(theta) * z),
int(math.sin(theta) * y + math... |
Add english version in FooterTest | package pt.fccn.sobre.arquivo.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import pt.fccn.sobre.arquivo.tests.CommonQuestionsTest;
import pt.fccn.sobre.arquivo.tests.ExamplesTest;
import pt.fccn.sobre.arquivo.tests.FooterTest;
import pt.fccn.sobr... | package pt.fccn.sobre.arquivo.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import pt.fccn.sobre.arquivo.tests.CommonQuestionsTest;
import pt.fccn.sobre.arquivo.tests.ExamplesTest;
import pt.fccn.sobre.arquivo.tests.FooterTest;
import pt.fccn.sobr... |
Remove unnecessary check of php version
The minimum php version required in composer is 7.1 and the code
was checking with version 5 | <?php
namespace Doctrine\Instantiator\Exception;
use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
use function interface_exists;
use function sprintf;
use function trait_exists;
/**
* Exception for invalid arguments provided to the instantiator
*/
class InvalidArgumentException ex... | <?php
namespace Doctrine\Instantiator\Exception;
use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
use const PHP_VERSION_ID;
use function interface_exists;
use function sprintf;
use function trait_exists;
/**
* Exception for invalid arguments provided to the instantiator
*/
class I... |
Use 'array' rather than 'real' for data array name in olfactory stimulus generation script. | #!/usr/bin/env python
"""
Generate sample olfactory model stimulus.
"""
import numpy as np
import h5py
osn_num = 1375
dt = 1e-4 # time step
Ot = 2000 # number of data point during reset period
Rt = 1000 # number of data point during odor delivery period
Nt = 4*Ot + 3*Rt # number of data points in time
t = np.arang... | #!/usr/bin/env python
"""
Generate sample olfactory model stimulus.
"""
import numpy as np
import h5py
osn_num = 1375
dt = 1e-4 # time step
Ot = 2000 # number of data point during reset period
Rt = 1000 # number of data point during odor delivery period
Nt = 4*Ot + 3*Rt # number of data points in time
t = np.arang... |
Fix compilation error in test. | package alien4cloud.it.maintenance;
import static alien4cloud.it.Context.getRestClientInstance;
import org.alien4cloud.server.MaintenanceUpdateDTO;
import alien4cloud.it.Context;
import cucumber.api.java.en.When;
/**
* Steps for maintenance mode cucumber rest it.
*/
public class MaintenanceStepsDefinition {
... | package alien4cloud.it.maintenance;
import static alien4cloud.it.Context.getRestClientInstance;
import org.alien4cloud.server.MaintenanceUpdateDTO;
import alien4cloud.it.Context;
import cucumber.api.java.en.When;
/**
* Steps for maintenance mode cucumber rest it.
*/
public class MaintenanceStepsDefinition {
... |
Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'. | """
Dummy layout. Used when somebody creates an `Application` without specifying a
`Layout`.
"""
from __future__ import unicode_literals
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
from .containers import Window
from .controls import FormattedTextControl
from .dim... | """
Dummy layout. Used when somebody creates an `Application` without specifying a
`Layout`.
"""
from __future__ import unicode_literals
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
from .containers import Window
from .controls import FormattedTextControl
from .dim... |
Move method list to node client | var RestClient = require('carbon-client')
var util = require('util')
var fibrous = require('fibrous');
/****************************************************************************************************
* monkey patch the endpoint class to support sync get/post/put/delete/head/patch
*/
var Endpoint = RestClient.... | var RestClient = require('carbon-client')
var util = require('util')
var fibrous = require('fibrous');
/****************************************************************************************************
* monkey patch the endpoint class to support sync get/post/put/delete/head/patch
*/
var Endpoint = RestClient.s... |
Fix file name on webpack configuration |
/**
* Module dependencies.
*/
import webpack from 'webpack';
/**
* Webpack configuration.
*/
export default {
entry: './src/browser/index.js',
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
plugins: [
['transform-es2015-for-of', {
... |
/**
* Module dependencies.
*/
import packageConfig from './package.json';
import webpack from 'webpack';
/**
* Webpack configuration.
*/
export default {
entry: './src/browser/index.js',
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
... |
Fix for the return value of delete method | from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""... | from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""... |
Update format of welcome message and notification | let Config = require('../../config');
let url = require('url');
let webHook = url.resolve(Config.app.url, '/codeship/');
class FormatterService {
format(type, build) {
return defaultFormat(build)
}
getStartMessage(chatId) {
let hook = this.getWebHook(chatId);
return `${FormatterService.EMOJI.ship} Hi! I see... | let Config = require('../../config');
let url = require('url');
let webHook = url.resolve(Config.app.url, '/codeship/');
class FormatterService {
format(type, build) {
return defaultFormat(build)
}
getStartMessage(chatId) {
let hook = this.getWebHook(chatId);
return `${FormatterService.EMOJI.ship} Add this ... |
Rename the resultant CSS file to fix the empty demo problem | var gulp = require('gulp'),
sass = require('gulp-sass'),
neat = require('node-neat'),
styleguide = require('./lib/styleguide'),
source = 'lib/app/**/*.scss',
outputPath = 'demo-output';
gulp.task('styleguide:generate', function() {
return gulp.src(source)
.pipe(styleguide.generate({
title: 'SC5... | var gulp = require('gulp'),
sass = require('gulp-sass'),
neat = require('node-neat'),
styleguide = require('./lib/styleguide'),
source = 'lib/app/**/*.scss',
outputPath = 'demo-output';
gulp.task('styleguide:generate', function() {
return gulp.src(source)
.pipe(styleguide.generate({
title: 'SC5... |
Change toString()
Rename field thingClass to contentType | package ru.nsu.ccfit.bogush.factory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
private Storage<T> storage;
private static final long DEFAULT_PERIOD = 0;
private Class<T> conten... | package ru.nsu.ccfit.bogush.factory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
private Storage<T> storage;
private static final long DEFAULT_PERIOD = 0;
private Class<T> thingC... |
Fix wrongly documented return type | <?php
namespace Brick\Geo\Engine;
use Brick\Geo\Exception\GeometryEngineException;
/**
* This class holds the GeometryEngine implementation to use for calculations.
*/
final class GeometryEngineRegistry
{
/**
* @var GeometryEngine|null
*/
private static $engine;
/**
* Returns whether a ... | <?php
namespace Brick\Geo\Engine;
use Brick\Geo\Exception\GeometryEngineException;
/**
* This class holds the GeometryEngine implementation to use for calculations.
*/
final class GeometryEngineRegistry
{
/**
* @var GeometryEngine|null
*/
private static $engine;
/**
* Returns whether a ... |
Rename Source's get_episodes_for() method to fetch() | from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode file... | from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode file... |
Handle rejected promise, handle zero message case. | /*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
... | /*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.