text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix app files test on windows | package cf_test
import (
. "cf"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"path/filepath"
"path"
)
var _ = Describe("AppFiles", func() {
fixturePath := filepath.Join("..", "fixtures", "applications")
Describe("AppFilesInDir", func() {
It("all files have '/' path separators", func() {
files, e... | package cf_test
import (
. "cf"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"path/filepath"
)
var _ = Describe("AppFiles", func() {
fixturePath := filepath.Join("..", "fixtures", "applications")
Describe("AppFilesInDir", func() {
It("all files have '/' path separators", func() {
files, err := Ap... |
Convert for use with Django | from django.conf import settings
import re
import sys
class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""
def __init__(self):
self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)]
def chunk(l,n):
retu... | #!/usr/bin/env python
import re
import sys
def chunk(l,n):
return (l[i:i+n] for i in xrange(0, len(l), n))
def is_disposable_email(email):
emails = [line.strip() for line in open('domain-list.txt')]
"""
Chunk it!
Regex parser doesn't deal with hundreds of groups
"""
for email_group ... |
Use 'template ...' for the SchemaTemplate verbose_name* | from django.db import models
from django.utils import six
from django.utils.functional import lazy
from boardinghouse.base import SharedSchemaMixin
from boardinghouse.schema import activate_schema, deactivate_schema, get_schema_model
def verbose_name_plural():
return u'template {}'.format(get_schema_model()._met... | from django.db import models
from django.utils import six
from boardinghouse.base import SharedSchemaMixin
from boardinghouse.schema import activate_schema, deactivate_schema
@six.python_2_unicode_compatible
class SchemaTemplate(SharedSchemaMixin, models.Model):
"""
A ``boardinghouse.contrib.template.models.... |
Increase the number of backill_meta_created iterations | #!/usr/bin/env python
# Copyright (C) 2019 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
import logging
logger = logging.getLogger(__name__)
def run_backfill_meta_created(script, opts, args):
if script.config.cluster.role != 'master':
logger.info('Not running bac... | #!/usr/bin/env python
# Copyright (C) 2019 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
import logging
logger = logging.getLogger(__name__)
def run_backfill_meta_created(script, opts, args):
if script.config.cluster.role != 'master':
logger.info('Not running bac... |
Fix javascript file ordering in manifest | //= require jquery
//= require jquery.ui.all
//= require jquery_ujs
//= require jquery-fileupload
//= require twitter/bootstrap
//= require select2
//= require shadowbox
//= require mousetrap
//= require ckeditor/init
//= require_tree .//ckeditor
//= require handlebars.runtime
//= require underscore
//= require backb... | //= require jquery
//= require jquery.ui.all
//= require jquery_ujs
//= require jquery-fileupload
//= require twitter/bootstrap
//= require select2
//= require shadowbox
//= require mousetrap
//= require ckeditor/init
//= require_tree .//ckeditor
//= require handlebars.runtime
//= require underscore
//= require backb... |
Fix import error by calling prepare_env first | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import logging
from awx import __version__ as tower_version
# Prepare the AWX environment.
from awx import prepare_env
prepare_env()
from django.core.wsgi import get_wsgi_application
"""
WSGI config for AWX project.
It exposes the WSGI callable as a module-... | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import logging
from django.core.wsgi import get_wsgi_application
from awx import prepare_env
from awx import __version__ as tower_version
"""
WSGI config for AWX project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more... |
Fix typeof check for allowed globals | var allowedGlobals = require('./allowed-globals'),
UNDEF = 'undefined',
cache;
/**
* Get global object based on what is available
* @private
*/
module.exports = function () {
if (typeof global !== UNDEF && global !== null && global.Array) {
return global;
}
if (typeof window !== UNDEF &... | var allowedGlobals = require('./allowed-globals'),
UNDEF = 'undefined',
cache;
/**
* Get global object based on what is available
* @private
*/
module.exports = function () {
if (typeof global !== UNDEF && global !== null && global.Array) {
return global;
}
if (typeof window !== UNDEF &... |
Add color log in the world generator | 'use strict';
const rethinkDB = require('rethinkdb');
const program = require('commander');
const log = require('./log');
var worldDB = 'labyrinth';
if (require.main === module) {
program
.version('0.0.1')
.option('-n, --dbname', 'Name of world database')
.option('-p, --port <n>', 'Port for RethinkDB, defau... | 'use strict';
const rethinkDB = require('rethinkdb');
const program = require('commander');
const log = require('./log');
var worldDB = 'labyrinth';
if (require.main === module) {
program
.version('0.0.1')
.option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015})
.optio... |
Make deployment script work from anywhere. | import logging
import os
import yaml
from fabric.api import lcd, env, task, local
from fabric.contrib.project import rsync_project
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
repo_root = local('git rev-parse --show-toplevel', capture=True)
try:
conf = yaml.load(open(os.path.join(repo_roo... | import logging
import yaml
from fabric.api import lcd, env, task
from fabric.contrib.project import rsync_project
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
try:
conf = yaml.load(open('deploy.yaml', 'rb').read())
except:
log.exception('error: unable to read deply.yaml config file:')... |
Remove legacy/deprecated code and cleanup. | package org.metaborg.meta.lang.spt.testrunner.cmd;
import org.metaborg.core.editor.IEditorRegistry;
import org.metaborg.core.editor.NullEditorRegistry;
import org.metaborg.core.project.IProjectService;
import org.metaborg.core.project.ISimpleProjectService;
import org.metaborg.core.project.SimpleProjectService;
import... | package org.metaborg.meta.lang.spt.testrunner.cmd;
import org.metaborg.core.editor.IEditorRegistry;
import org.metaborg.core.editor.NullEditorRegistry;
import org.metaborg.core.project.IProjectService;
import org.metaborg.core.project.ISimpleProjectService;
import org.metaborg.core.project.SimpleProjectService;
import... |
Troubleshoot script for displaying getting the counts of tickets assigned to each user. | /* global SW:true */
$(document).ready(function(){
'use strict';
console.log( 'Doing SW things!' );
var card = new SW.Card();
var helpdesk = card.services('helpdesk');
var assignmentCount = {};
helpdesk
.request('tickets')
.then( function(data){
console.log( 'got data!' );
$.each(data... | /* global SW:true */
$(document).ready(function(){
'use strict';
console.log( 'Doing SW things!' );
var card = new SW.Card();
var helpdesk = card.services('helpdesk');
helpdesk
.request('tickets')
.then( function(data){
console.log( 'got data!' );
var ticketCount = {};
$.each(data... |
HOTFIX: Replace Object.values with old-node friendly code | var locationGraph = require('../assets/data/dummy-picker-data-2.json')
function isCanonicalNode (node) {
return node.meta.canonical
}
function presentableName (node, locale) {
var requestedName = node['names'][locale]
var fallback = Object.keys(node['names']).map(k => node['names'][k])[0]
return requestedName... | var locationGraph = require('../assets/data/dummy-picker-data-2.json')
function isCanonicalNode (node) {
return node.meta.canonical
}
function presentableName (node, locale) {
var requestedName = node['names'][locale]
var fallback = Object.values(node['names'])[0]
return requestedName || fallback
}
var locat... |
Disable inline sourcemaps in postcss | /* eslint-env node */
'use strict'
const EmberApp = require('ember-cli/lib/broccoli/ember-app')
const cssnext = require('postcss-cssnext')
module.exports = function(defaults) {
let app = new EmberApp(defaults, {
postcssOptions: {
compile: {
enabled: false
},
filter: {
enabled: ... | /* eslint-env node */
'use strict'
const EmberApp = require('ember-cli/lib/broccoli/ember-app')
const cssnext = require('postcss-cssnext')
module.exports = function(defaults) {
let app = new EmberApp(defaults, {
postcssOptions: {
compile: {
enabled: false
},
filter: {
enabled: ... |
Add second argument to parse() | "use strict";
var renderNull = function () { return 'NULL' }
, parser
parser = require('editorsnotes-markup-parser')({
projectBaseURL: '/',
resolveItemText: renderNull,
makeBibliographyEntry: renderNull,
makeInlineCitation: function(citations) {
return { citations: citations.map(renderNull) }
}
});
f... | "use strict";
var renderNull = function () { return 'NULL' }
, parser
parser = require('editorsnotes-markup-parser')({
projectBaseURL: '/',
resolveItemText: renderNull,
makeBibliographyEntry: renderNull,
makeInlineCitation: function(citations) {
return { citations: citations.map(renderNull) }
}
});
f... |
Remove trailing slashes from requests in frontend | import axios from 'axios';
export function getRestaurants ({ commit }) {
return new Promise((resolve, reject) => {
axios
.get('/api/restaurant')
.then((response) => {
commit('updateRestaurants', response.data.restaurants);
resolve(response);
})
.catch((err) => {
r... | import axios from 'axios';
export function getRestaurants ({ commit }) {
return new Promise((resolve, reject) => {
axios
.get('/api/restaurant/')
.then((response) => {
commit('updateRestaurants', response.data.restaurants);
resolve(response);
})
.catch((err) => {
... |
Fix testHarness call for Windows | from SCons.Script import *
import shlex
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.... | from SCons.Script import *
import inspect
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spaw... |
Update match-id to equal that used in compd. | #!/usr/bin/env python
import os
import sys
import yaml
import score
MATCH_ID = 'match-{0}'
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
u... | #!/usr/bin/env python
import os
import sys
import yaml
import score
def usage():
print "Usage: score-match.py MATCH_NUMBER"
print " Scores the match file at matches/MATCH_NUMBER.yaml"
print " Outputs scoring format suitable for piping at compd"
if len(sys.argv) is not 2:
usage()
exit(1)
matc... |
Fix typo for js file. | const {resolve} = require('path');
const webpack =require('webpack');
module.exports = {
entry: [
'./index.tsx'
],
output:{
filename: 'bundle.js',
path: resolve(__dirname, 'static'),
publicPath: ''
},
resolve:{
extensions: ['.js', '.jsx', '.ts', '.tsx', '.css... | const {resolve} = require('path');
const webpack =require('webpack');
module.exports = {
entry: [
'./index.tsx'
],
output:{
filename: 'bundle.js',
path: resolve(__dirname, 'static'),
publicPath: ''
},
resolve:{
extensions: ['js', '.jsx', '.ts', '.tsx', '.css'... |
Update endpoint to remote api | package com.sanchez.fmf.service;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.OkHttpClient;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;
/**
* Created by dakota on 9/2/15.
*/
public class RestClient {
priv... | package com.sanchez.fmf.service;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.OkHttpClient;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;
/**
* Created by dakota on 9/2/15.
*/
public class RestClient {
priv... |
Add bin to package.json and move rc-loading to plugin.js | import postcss from "postcss"
import fs from "fs"
import gs from "glob-stream"
import { Transform } from "stream"
import plugin from "./plugin"
export default function ({ files, config } = {}) {
const linter = new Transform({ objectMode: true })
linter._transform = function (chunk, enc, callback) {
if (files)... | import postcss from "postcss"
import fs from "fs"
import gs from "glob-stream"
import rcLoader from "rc-loader"
import { Transform } from "stream"
import plugin from "./plugin"
export default function ({ files, config } = {}) {
const stylelintConfig = config || rcLoader("stylelint")
if (!stylelintConfig) {
thr... |
Make engine available in app. | #!/usr/bin/env python
# coding=utf8
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import model
import defaults
from views.frontend import frontend, oid
def create_app(config_filename):
app = Flask(__name__)
app.config.from_object(defaults)
app... | #!/usr/bin/env python
# coding=utf8
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import model
import defaults
from views.frontend import frontend, oid
def create_app(config_filename):
app = Flask(__name__)
app.config.from_object(defaults)
app... |
Add template fields to wcloud config. | package main
import (
"time"
)
// Deployment describes a deployment
type Deployment struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
ImageName string `json:"image_name"`
Version string `json:"version"`
Priority int `json:"priority"`
State string `json:"stat... | package main
import (
"time"
)
// Deployment describes a deployment
type Deployment struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
ImageName string `json:"image_name"`
Version string `json:"version"`
Priority int `json:"priority"`
State string `json:"stat... |
Fix old Safari by using `dispatchEvent` from `Element` rather than `EventTarget`. | /**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://... | /**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://... |
Refactor env in run command | 'use strict'
var path = require('path')
var async = require('async')
var config = require('./config')
var child_process = require('child_process')
var assign = require('object-assign')
function runCmd (cwd, argv) {
var scripts = argv._.slice(1)
var pkg = require(path.join(cwd, 'package.json'))
if (!scripts.len... | 'use strict'
var path = require('path')
var async = require('async')
var config = require('./config')
var child_process = require('child_process')
function runCmd (cwd, argv) {
var scripts = argv._.slice(1)
var pkg = require(path.join(cwd, 'package.json'))
if (!scripts.length) {
var availableScripts = Obje... |
Join channel and register on reconnect | var chat = angular.module('chat', ['btford.socket-io']);
var channel = new Channel('hellas');
var me = null;
chat.factory('chatServer', function (socketFactory) {
var url = '/';
if (location.port != '') {
url = ':' + location.port + '/';
}
return socketFactory({ioSocket: io.connect(url)})
});... | var chat = angular.module('chat', ['btford.socket-io']);
var channel = new Channel('hellas');
var me = null;
chat.factory('chatServer', function (socketFactory) {
var url = '/';
if (location.port != '') {
url = ':' + location.port + '/';
}
return socketFactory({ioSocket: io.connect(url)})
});... |
Fix error if column has empty string | <?php
namespace Maphper\DataSource;
//Replaces dates in an object graph with \DateTime instances
class DateInjector {
private $processCache;
public function replaceDates($obj, $reset = true) {
//prevent infinite recursion, only process each object once
if ($reset) $this->processCache = new \SplObjectStorage();
... | <?php
namespace Maphper\DataSource;
//Replaces dates in an object graph with \DateTime instances
class DateInjector {
private $processCache;
public function replaceDates($obj, $reset = true) {
//prevent infinite recursion, only process each object once
if ($reset) $this->processCache = new \SplObjectStorage();
... |
Include LICENSE.txt in the package tarball | from distutils.core import setup
VERSION='0.3.1'
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = VERSION,
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'h... | from distutils.core import setup
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = '0.3.0',
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'https://github.com/... |
Change import InviteForm from private.forms to accounts.forms | from django.contrib.auth.decorators import user_passes_test
from django.http import Http404
from django.shortcuts import redirect, render
from accounts.utils import send_activation_email
from accounts.forms import InviteForm
owner_required = user_passes_test(
lambda u: u.is_authenticated() and u.is_owner
)
@o... | from django.contrib.auth.decorators import user_passes_test
from django.http import Http404
from django.shortcuts import redirect, render
from accounts.utils import send_activation_email
from .forms import InviteForm
owner_required = user_passes_test(
lambda u: u.is_authenticated() and u.is_owner
)
@owner_req... |
Handle TZ change in iso8601 >=0.1.12
The iso8601 lib introduced a change such that if running on python
3.2 or later it internally uses the python timezone information
instead of its own implementation. This does not change direct
date handling, but when converting this value there is a slight
difference where now pyt... | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... |
Improve phonenumber formats for nl_NL | <?php
namespace Faker\Provider\nl_NL;
class PhoneNumber extends \Faker\Provider\PhoneNumber
{
protected static $formats = array(
'06 ########',
'06-########',
'+316-########',
'+31(0)6-########',
'+316 ########',
'+31(0)6 ########',
'01# #######',
'(... | <?php
namespace Faker\Provider\nl_NL;
class PhoneNumber extends \Faker\Provider\PhoneNumber
{
protected static $formats = array(
'+31(0)#########',
'+31(0)### ######',
'+31(0)## #######',
'+31(0)6 ########',
'+31#########',
'+31### ######',
'+31## #######',
... |
Allow mutation commands from the test client. | #!/usr/bin/env python
"""
Binary memcached test client.
Copyright (c) 2007 Dustin Sallings <dustin@spy.net>
"""
import sys
import socket
import random
import struct
from testServer import REQ_MAGIC_BYTE, PKT_FMT, MIN_RECV_PACKET, EXTRA_HDR_FMTS
from testServer import CMD_SET, CMD_ADD, CMD_REPLACE
if __name__ == '_... | #!/usr/bin/env python
"""
Binary memcached test client.
Copyright (c) 2007 Dustin Sallings <dustin@spy.net>
"""
import sys
import socket
import random
import struct
from testServer import REQ_MAGIC_BYTE, PKT_FMT, MIN_RECV_PACKET
if __name__ == '__main__':
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... |
Remove usage of ember jquery integration in tests
Note, the ember-jquery addon re-enables usage of this.$() within components without a depreciation warning.
https://deprecations.emberjs.com/v3.x/#toc_jquery-apis | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import $ from 'jquery';
module('Integration | Component | froala-content', function(hooks) {
setupRenderingTest(hooks);
test('.fr-view... | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | froala-content', function(hooks) {
setupRenderingTest(hooks);
test('.fr-view class is applied', asyn... |
Remove redundant ws accept replies
It's only relevent on connection | from channels.auth import channel_session_user_from_http, channel_session_user
from django.utils import timezone
from foodsaving.subscriptions.models import ChannelSubscription
@channel_session_user_from_http
def ws_connect(message):
"""The user has connected! Register their channel subscription."""
user = m... | from channels.auth import channel_session_user_from_http, channel_session_user
from django.utils import timezone
from foodsaving.subscriptions.models import ChannelSubscription
@channel_session_user_from_http
def ws_connect(message):
"""The user has connected! Register their channel subscription."""
user = m... |
Add COLOR as an available field type | /*
* Copyright 2008-2013 the original author or authors.
*
* 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 ... | /*
* Copyright 2008-2013 the original author or authors.
*
* 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 ... |
Add documentation menu to the front page.
svn commit r1956 | <?php
require_once 'DemoPage.php';
/**
* The front page of the demo application
*
* This page displays a quick introduction to the Swat Demo Application
*
* @package SwatDemo
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class FrontPage extends DemoP... | <?php
require_once 'DemoPage.php';
/**
* The front page of the demo application
*
* This page displays a quick introduction to the Swat Demo Application
*
* @package SwatDemo
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class FrontPage extends DemoP... |
Make abstract test case class abstract | <?php
/*
* This file is part of Laravel Algolia.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Vinkla\Tests\Algolia;
use GrahamCampbell\TestBench\AbstractPackageTestCase;
/... | <?php
/*
* This file is part of Laravel Algolia.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Vinkla\Tests\Algolia;
use GrahamCampbell\TestBench\AbstractPackageTestCase;
/... |
Use commit URL to get repo name | <?php declare(strict_types=1);
namespace ApiClients\Client\Github\Resource\Async\Repository;
use ApiClients\Client\Github\CommandBus\Command\Repository\DetailedCommitCommand;
use ApiClients\Client\Github\Resource\Repository\Branch as BaseBranch;
use React\Promise\PromiseInterface;
class Branch extends BaseBranch
{
... | <?php declare(strict_types=1);
namespace ApiClients\Client\Github\Resource\Async\Repository;
use ApiClients\Client\Github\CommandBus\Command\Repository\DetailedCommitCommand;
use ApiClients\Client\Github\Resource\Repository\Branch as BaseBranch;
use React\Promise\PromiseInterface;
class Branch extends BaseBranch
{
... |
Add two more fields to StatsBase | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class SchoolYear(models.Model):
name = models.CharField(max_length=9)
def __str__(self):
return sel... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class SchoolYear(models.Model):
name = models.CharField(max_length=9)
def __str__(self):
return sel... |
Add a short description to NodeIterator | // A DOM node iterator.
//
// Has the ability to replace nodes on the fly and continue
// the iteration.
var NodeIterator = (function() {
var NodeIterator = function(root) {
this.root = root;
this.current = this.next = this.root;
};
NodeIterator.prototype.getNextTextNode = function() {
var next;
... | var NodeIterator = (function() {
var NodeIterator = function(root) {
this.root = root;
this.current = this.next = this.root;
};
NodeIterator.prototype.getNextTextNode = function() {
var next;
while ( (next = this.getNext()) ) {
if (next.nodeType === 3 && next.data !== '') {
return ... |
Change Camel-Mail example to
- not create 2 SMTP servers.
- use an integer instead of an integer-shaped string. | /*
* #%L
* Wildfly Swarm :: Examples :: Camel Mail
* %%
* Copyright (C) 2016 RedHat
* %%
* 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/LICENS... | /*
* #%L
* Wildfly Swarm :: Examples :: Camel Mail
* %%
* Copyright (C) 2016 RedHat
* %%
* 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/LICENS... |
Add link to release notes (to motivate myself write them) | import * as utils from 'base/utils';
import Dialog from '../_dialog';
import Vzb from 'vizabi';
/*
* Size dialog
*/
var About = Dialog.extend({
/**
* Initializes the dialog component
* @param config component configuration
* @param context component context (parent)
*/
init: function(config, parent) {
this.n... | import * as utils from 'base/utils';
import Dialog from '../_dialog';
import Vzb from 'vizabi';
/*
* Size dialog
*/
var About = Dialog.extend({
/**
* Initializes the dialog component
* @param config component configuration
* @param context component context (parent)
*/
init: function(config, parent) {
this.n... |
Test the actual get_zone call | import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def set... | import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def set... |
Use let instead of var | import Shogi from '../src/shogi';
import * as CONST from '../constants/actionTypes';
const InitialState = {
board: Shogi.Board,
isHoldingPiece: undefined
};
const ShogiReducer = (state = InitialState, action) => {
switch (action.type) {
case CONST.HOLD_PIECE:
if (action.piece.type == '*') {
return s... | import Shogi from '../src/shogi';
import * as CONST from '../constants/actionTypes';
const InitialState = {
board: Shogi.Board,
isHoldingPiece: undefined
};
const ShogiReducer = (state = InitialState, action) => {
switch (action.type) {
case CONST.HOLD_PIECE:
if (action.piece.type == '*') {
return s... |
Add try…catch block to track | import { addCallback } from 'meteor/vulcan:core';
export const initFunctions = [];
export const trackFunctions = [];
export const addInitFunction = f => {
initFunctions.push(f);
// execute init function as soon as possible
f();
};
export const addTrackFunction = f => {
trackFunctions.push(f);
};
export con... | import { addCallback } from 'meteor/vulcan:core';
export const initFunctions = [];
export const trackFunctions = [];
export const addInitFunction = f => {
initFunctions.push(f);
// execute init function as soon as possible
f();
};
export const addTrackFunction = f => {
trackFunctions.push(f);
};
export con... |
Add the instructor toggle functionality | var AdminPanel = function() {
var self = this;
$('.admin_toggle').change(function() {
self.togglePrivileges(this, $(this).data('url'), 'admin', this.checked);
});
$('.instructor_toggle').change(function() {
self.togglePrivileges(this, $(this).data('url'), 'instructor', this.checked);
... | var AdminPanel = function() {
var self = this;
$('.admin_toggle').change(function() {
self.togglePrivileges(this, $(this).data('url'), 'admin', this.checked);
});
$('.instructor_toggle').change(function() {
console.log('stub');
});
this.togglePrivileges = function(element, url, ... |
Add "long" package to webpack externals | import path from 'path';
export default {
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /node_modules/
}, {
test: /\.json$/,
loader: 'json-loader'
}]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryT... | import path from 'path';
export default {
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /node_modules/
}, {
test: /\.json$/,
loader: 'json-loader'
}]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryT... |
Use `canOpen` in GPIO `open` function | import Promise from "bluebird";
import gpio from "rpi-gpio";
import _ from "underscore";
class RpiGpioOpener {
constructor(config) {
gpio.setMode(gpio.MODE_BCM);
this.pins = config.pins;
this.opening = {};
}
canOpen(doorId) {
return !_.isUndefined(this.pins[doorId]);
}
open(doorId, time) {... | import Promise from "bluebird";
import gpio from "rpi-gpio";
import _ from "underscore";
class RpiGpioOpener {
constructor(config) {
gpio.setMode(gpio.MODE_BCM);
this.pins = config.pins;
this.opening = {};
}
canOpen(doorId) {
return !_.isUndefined(this.pins[doorId]);
}
open(doorId, time) {... |
:art: Apply colored image when you hover the link
Not just the image itself (there's padding on the link). | import React, { Component, PropTypes } from 'react';
import './SocialLink.css';
class SocialLink extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
icon: PropTypes.string.isRequired,
iconHover: PropTypes.string.isRequired,
};
state = {... | import React, { Component, PropTypes } from 'react';
import './SocialLink.css';
class SocialLink extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
icon: PropTypes.string.isRequired,
iconHover: PropTypes.string.isRequired,
};
state = {... |
Include an override to the default manager to allow geospatial querying. | from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = ... | from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = ... |
Fix protocol join group including the assigner metadata | const Encoder = require('../../../encoder')
const { JoinGroup: apiKey } = require('../../apiKeys')
/**
* JoinGroup Request (Version: 0) => group_id session_timeout member_id protocol_type [group_protocols]
* group_id => STRING
* session_timeout => INT32
* member_id => STRING
* protocol_type => STRING
* ... | const Encoder = require('../../../encoder')
const { JoinGroup: apiKey } = require('../../apiKeys')
/**
* JoinGroup Request (Version: 0) => group_id session_timeout member_id protocol_type [group_protocols]
* group_id => STRING
* session_timeout => INT32
* member_id => STRING
* protocol_type => STRING
* ... |
Fix old variable STACK_START name (not used anymore) | # State identifiers (begin and end).
NO_STATE = -1
BIND_START = 0
BIND_END = BIND_START + 1
INTER_SSH_START = 10
INTER_SSH_END = INTER_SSH_START + 1
GIT_SETUP_START = 20
GIT_SETUP_END = GIT_SETUP_START + 1
UPLOAD_REPO_START = 30
UPLOAD_REPO_END = UPLOAD_REPO_START + 1
INSTALL_PKG_START = 40
INSTALL_PKG_END = INST... | # State identifiers (begin and end).
NO_STATE = -1
BIND_START = 0
BIND_END = BIND_START + 1
INTER_SSH_START = 10
INTER_SSH_END = INTER_SSH_START + 1
GIT_SETUP_START = 20
GIT_SETUP_END = GIT_SETUP_START + 1
UPLOAD_REPO_START = 30
UPLOAD_REPO_END = UPLOAD_REPO_START + 1
INSTALL_PKG_START = 40
INSTALL_PKG_END = INST... |
Use process.exit(0) if none found | 'use strict'
var fs = require('fs')
var miss = require('mississippi')
var config = require('../config')
function filterJobsList (jobs) {
var list = []
jobs.forEach(function (job) {
if (job.indexOf('.json') > -1) {
list.push(job)
}
})
return list
}
var getNextJob = miss.through(function (chunc... | 'use strict'
var fs = require('fs')
var miss = require('mississippi')
var config = require('../config')
function filterJobsList (jobs) {
var list = []
jobs.forEach(function (job) {
if (job.indexOf('.json') > -1) {
list.push(job)
}
})
return list
}
var getNextJob = miss.through(function (chunc... |
Copy identities from context to event model | var Promise = require('bluebird');
var deepExtend = require('deep-extend');
var AnalyticsContext = require('./AnalyticsContext');
var AnalyticsEventModel = require('./AnalyticsEventModel');
var AnalyticsDispatcher = require('./AnalyticsDispatcher');
var createEventModel = function(eventName, context){
var eventMode... | var Promise = require('bluebird');
var deepExtend = require('deep-extend');
var AnalyticsContext = require('./AnalyticsContext');
var AnalyticsEventModel = require('./AnalyticsEventModel');
var AnalyticsDispatcher = require('./AnalyticsDispatcher');
var createEventModel = function(eventName, context){
var eventMode... |
Add ResizerObserver shim for tests. | import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
global.requestAnimationFrame = function(callback) {
setTimeout(callback, 0);
};
try {
require('canvas');
} catch(err) {
global.HAS_CANVAS = false;
global.HTMLCanvasElement = function() {};
global.HTMLCanvasElement.protot... | import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
global.requestAnimationFrame = function(callback) {
setTimeout(callback, 0);
};
try {
require('canvas');
} catch(err) {
global.HAS_CANVAS = false;
global.HTMLCanvasElement = function() {};
global.HTMLCanvasElement.protot... |
Remove unnecessary call to promisify | const command = {
command: "console",
description:
"Run a console with contract abstractions and commands available",
builder: {},
help: {
usage: "truffle console [--network <name>] [--verbose-rpc]",
options: [
{
option: "--network <name>",
description:
"Specify the n... | const { promisify } = require("util");
const command = {
command: "console",
description:
"Run a console with contract abstractions and commands available",
builder: {},
help: {
usage: "truffle console [--network <name>] [--verbose-rpc]",
options: [
{
option: "--network <name>",
... |
Make sure to update correct load balancer | #!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum',... | #!/usr/bin/env python3
import argparse
import subprocess
import json
import sys
parser = argparse.ArgumentParser()
args = parser.parse_args()
def info(msg):
sys.stdout.write('* {}\n'.format(msg))
sys.stdout.flush()
info('Determining current production details...')
output = subprocess.check_output(['tutum',... |
Indent with tabs in generated xml | 'use strict';
const neatCsv = require('neat-csv');
const pify = require('pify');
const Promise = require('pinkie-promise');
const redent = require('redent');
const trimNewlines = require('trim-newlines');
module.exports = (str, opts) => {
opts = opts || {};
opts.attributes = opts.attributes || {};
if (typeof str !... | 'use strict';
const neatCsv = require('neat-csv');
const pify = require('pify');
const Promise = require('pinkie-promise');
const redent = require('redent');
const trimNewlines = require('trim-newlines');
module.exports = (str, opts) => {
opts = opts || {};
opts.attributes = opts.attributes || {};
if (typeof str !... |
Prepare for config and command line arguments | #!/usr/bin/env python3
# Pianette
# A command-line emulator of a PS2 Game Pad Controller
# that asynchronously listens to GPIO EDGE_RISING
# inputs from sensors and sends Serial commands to
# an ATMEGA328P acting as a fake SPI Slave for the Console.
# Written in Python 3.
import pianette.config
import sys
from p... | #!/usr/bin/env python3
# Pianette
# A command-line emulator of a PS2 Game Pad Controller
# that asynchronously listens to GPIO EDGE_RISING
# inputs from sensors and sends Serial commands to
# an ATMEGA328P acting as a fake SPI Slave for the Console.
# Written in Python 3.
import pianette.config
import sys
from p... |
Use the right comment style for jsdoc | // @flow
/**
* Transform a Promise-returning function into a function that can optionally
* take a callback as the last parameter instead.
*
* @param {Function} fn a function that returns a Promise
* @param {Object} self (optional) `this` to be used when applying fn
* @return {Functi... | // @flow
/* Transform a Promise-returning function into a function that can optionally
* take a callback as the last parameter instead.
*
* @param {Function} fn a function that returns a Promise
* @param {Object} self (optional) `this` to be used when applying fn
* @return {Function} ... |
Refactor slash-unpickiness as a function and redecorate | import projects
from flask import Flask, render_template, abort
app = Flask(__name__)
def route(*a, **kw):
kw['strict_slashes'] = kw.get('strict_slashes', False)
return app.route(*a, **kw)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@route('/')
def index():
... | import projects
from flask import Flask, render_template, abort
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/')
def index():
project_list = projects.get_projects()
return render_template('index.html', projects=project_list)
@app... |
Use includes to make code simplier | export function getInterfaceLanguage() {
if (!!navigator && !!navigator.language) {
return navigator.language;
} else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
return navigator.languages[0];
} else if (!!navigator && !!navigator.userLanguage) {
return navigator.userLangua... | export function getInterfaceLanguage() {
if (!!navigator && !!navigator.language) {
return navigator.language;
} else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
return navigator.languages[0];
} else if (!!navigator && !!navigator.userLanguage) {
return navigator.userLangua... |
Add more verbose error to reporte on Travis parserXML.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
tr... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
tr... |
Substitute console logs with proper asserts | /* jshint mocha: true */
'use strict';
const assert = require('assert');
const jenkins = require('../lib/jenkins');
describe('jenkins', function() {
describe('getComputers()', function() {
it('returns all nodes', function(done) {
this.timeout(10000);
jenkins.getComputers(function(err, nodes) {
... | /* jshint mocha: true */
'use strict';
const assert = require('assert');
const jenkins = require('../lib/jenkins');
describe('jenkins', function() {
describe('getComputers()', function() {
it('returns all nodes', function(done) {
this.timeout(10000);
jenkins.getComputers(function(err, nodes) {
... |
Remove useless mock side effect | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest... | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest... |
Modify test worker unit test
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com> | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def setup(self):
self.worker = Worker()
def test_init(self):
as... | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def test_init(self):
worker = Worker()
assert isinstance(worker.work... |
Make sure random values are random across processes | import logging
import random
import os
from unittest import TestLoader, TestSuite
import unittest.util
from exchangelib.util import PrettyXmlHandler
class RandomTestSuite(TestSuite):
def __iter__(self):
tests = list(super().__iter__())
random.shuffle(tests)
return iter(tests)
# Execute ... | import logging
import random
import os
from unittest import TestLoader, TestSuite
import unittest.util
from exchangelib.util import PrettyXmlHandler
class RandomTestSuite(TestSuite):
def __iter__(self):
tests = list(super().__iter__())
random.shuffle(tests)
return iter(tests)
# Execute ... |
Delete useless param $response in redirect() | <?php
namespace Rudolf\Framework\Controller;
use Rudolf\Component\Http\Response;
abstract class BaseController
{
protected $request;
public function __construct($request)
{
$this->request = $request;
if (method_exists($this, 'init')) {
$this->init();
}
}
/**... | <?php
namespace Rudolf\Framework\Controller;
use Rudolf\Component\Http\Response;
abstract class BaseController
{
protected $request;
public function __construct($request)
{
$this->request = $request;
if (method_exists($this, 'init')) {
$this->init();
}
}
/**... |
Return new object instead of modifying input objects | var angular = require('angular')
require('../app').directive('previewPictures', /* @ngInject */function () {
return {
restrict: 'EA',
templateUrl: '/views/directives/previewpictures.html',
scope: {
pictures: '='
},
bindToController: true,
link: function ($scope, $element, $attrs, $ctrl)... | require('../app').directive('previewPictures', /* @ngInject */function () {
return {
restrict: 'EA',
templateUrl: '/views/directives/previewpictures.html',
scope: {
pictures: '='
},
bindToController: true,
link: function ($scope, $element, $attrs, $ctrl) {
$element.on('click', $ctr... |
Make the propTypes removal explicit.
See:
https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types#with-comment-annotation | import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
const createHelpers = '##CREATEHELPERS##'
const width = '##WIDTH##'
const height = '##HEIGHT##'
const viewBox = '##VIEWBOX##'
const { getDimensions, getCss, propsToCss, sanitizeSizes } = createH... | import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
const createHelpers = '##CREATEHELPERS##'
const width = '##WIDTH##'
const height = '##HEIGHT##'
const viewBox = '##VIEWBOX##'
const { getDimensions, getCss, propsToCss, sanitizeSizes } = createH... |
Remove simplejson as a dependency for python 2.6+
Python 2.6 introduced the ``json`` module into the core language and so ``simplejson`` is only required in python versions prior to python 2.6. This fix ensures that pip will only install simplejson if the version of python being run is less than 2.6. This stops the un... | from authy import __version__
from setuptools import setup, find_packages
# to install authy type the following command:
# python setup.py install
with open('README.md') as f:
long_description = f.read()
setup(
name="authy",
version=__version__,
description="Authy API Client",
author="Authy I... | from authy import __version__
from setuptools import setup, find_packages
# to install authy type the following command:
# python setup.py install
with open('README.md') as f:
long_description = f.read()
setup(
name="authy",
version=__version__,
description="Authy API Client",
author="Authy I... |
Use $sections instead of sections
As the variable is a JQuery object, give it a $name instead of a name | (function() {
"use strict";
window.GOVUK = window.GOVUK || {};
function CollapsibleCollection(options){
this.collapsibles = {};
this.$sections = options.el.find('section');
this.$sections.each($.proxy(this.initCollapsible, this));
this.closeAll();
}
CollapsibleCollection.prototype.initColl... | (function() {
"use strict";
window.GOVUK = window.GOVUK || {};
function CollapsibleCollection(options){
this.collapsibles = {};
this.sections = options.el.find('section');
this.sections.each($.proxy(this.initCollapsible, this));
this.closeAll();
}
CollapsibleCollection.prototype.initCollap... |
Update docblocks to return the model after calling save on the repository. | <?php
namespace Enzyme\Axiom\Repositories;
use Enzyme\Axiom\Models\ModelInterface;
use Enzyme\Axiom\Atoms\AtomInterface;
/**
* Manages a collection of models.
*/
interface RepositoryInterface
{
/**
* Get a collection of all models for this type.
*
* @return array
*/
public function getA... | <?php
namespace Enzyme\Axiom\Repositories;
use Enzyme\Axiom\Models\ModelInterface;
use Enzyme\Axiom\Atoms\AtomInterface;
/**
* Manages a collection of models.
*/
interface RepositoryInterface
{
/**
* Get a collection of all models for this type.
*
* @return array
*/
public function getA... |
Improve English for checkbox label | <?php
namespace MarkMx\SkelBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
class ResetDbType extends AbstractType
{
public function buil... | <?php
namespace MarkMx\SkelBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
class ResetDbType extends AbstractType
{
public function buil... |
Change @bench to return a list, because there will never be more than 1 key in the dict | from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res... | from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res... |
Use correct background & icon colors according to design | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';
import Box from '../box';
import Icon from '../icon';
import { IconTeamMediumOutline, IconTeamSmallOutline } from '@teamleader/ui-icons';
class AvatarTeam extends PureComponen... | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';
import Box from '../box';
import Icon from '../icon';
import { IconTeamMediumOutline, IconTeamSmallOutline } from '@teamleader/ui-icons';
class AvatarTeam extends PureComponen... |
Add gulp serve no build task | /* ************************************ */
/* Server */
/* ************************************ */
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['browser-*']
});
var proxyMiddleware ... | /* ************************************ */
/* Server */
/* ************************************ */
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['browser-*']
});
var proxyMiddleware ... |
HG-1871: Fix missing tools package install | from setuptools import setup
import subprocess, os
version = open('pymoku/version.txt').read().strip()
setup(
name='pymoku',
version=version,
author='Ben Nizette',
author_email='ben.nizette@liquidinstruments.com',
packages=['pymoku', 'pymoku.tools'],
package_dir={'pymoku': 'pymoku/'},
package_data={
'pymoku'... | from setuptools import setup
import subprocess, os
version = open('pymoku/version.txt').read().strip()
setup(
name='pymoku',
version=version,
author='Ben Nizette',
author_email='ben.nizette@liquidinstruments.com',
packages=['pymoku'],
package_dir={'pymoku': 'pymoku/'},
package_data={
'pymoku' : ['version.txt... |
Add .isEmpty() on slate value container | import toSlate from './conversion/toSlate'
import fromSlate from './conversion/fromSlate'
export default class SlateValueContainer {
static deserialize(value, context) {
const state = toSlate(value || [], context)
return new SlateValueContainer(state, context)
}
constructor(state, context) {
this.s... | import toSlate from './conversion/toSlate'
import fromSlate from './conversion/fromSlate'
export default class SlateValueContainer {
static deserialize(value, context) {
const state = toSlate(value || [], context)
return new SlateValueContainer(state, context)
}
constructor(state, context) {
this.s... |
Fix bug in relationships via REST API. | 'use strict';
var DataCollection = require('data-collection'),
_ = require('lodash');
/**
* Given a array of relationship data and the HTTP query, filters it
* @param {Array} data Array of data coming from a relationship
* @param {Object} httpQuery
* @return {Array}
*/
module.exports = function filterRel... | 'use strict';
var DataCollection = require('data-collection');
/**
* Given a array of relationship data and the HTTP query, filters it
* @param {Array} data Array of data coming from a relationship
* @param {Object} httpQuery
* @return {Array}
*/
module.exports = function filterRelationship(data, httpQuer... |
Fix 'global is not defined' error | const path = require('path');
function resolvePath(pathToResolve) {
return path.resolve(__dirname, pathToResolve);
}
module.exports = {
lintOnSave: false,
pages: {
'index': {
entry: 'src/main.js',
chunks: ['chunk-vendors', 'chunk-common', 'index', 'preload'],
},
'options/options': {
... | const path = require('path');
function resolvePath(pathToResolve) {
return path.resolve(__dirname, pathToResolve);
}
module.exports = {
lintOnSave: false,
pages: {
'index': {
entry: 'src/main.js',
chunks: ['chunk-vendors', 'chunk-common', 'index', 'preload'],
},
'options/options': {
... |
Handle patterns as String or RegExp. | 'use strict';
var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
function Command() {
this.actions = [];
this.token;
mixin(this, EventEmitter.prototype, false);
}
Command.prototype.setToken = function (token) {
this.token = token;
}
Command.prototype._checkToken = ... | 'use strict';
var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
function Command() {
this.actions = [];
this.token;
mixin(this, EventEmitter.prototype, false);
}
Command.prototype.setToken = function (token) {
this.token = token;
}
Command.prototype._checkToken = ... |
Add space to separate arguments. | package executors;
public class CommandCreator {
public String createCommand(String userCommand) {
String[] tokens = userCommand.split("\\s+");
switch(tokens[0]) {
case "security":
switch (tokens[1]) {
case "tls":
return "nm... | package executors;
public class CommandCreator {
public String createCommand(String userCommand) {
String[] tokens = userCommand.split("\\s+");
switch(tokens[0]) {
case "security":
switch (tokens[1]) {
case "tls":
return "nm... |
Add sphinx autosection label plugin. | from datetime import date
import guzzle_sphinx_theme
from pyinfra import __version__
copyright = 'Nick Barrett {0} — pyinfra v{1}'.format(
date.today().year,
__version__,
)
extensions = [
# Official
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.autosectionlabel',
]
autosectionlab... | from datetime import date
import guzzle_sphinx_theme
from pyinfra import __version__
copyright = 'Nick Barrett {0} — pyinfra v{1}'.format(
date.today().year,
__version__,
)
extensions = [
# Official
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
]
extensions.append('guzzle_sphinx_theme')
source... |
Remove process.exit(0) when windows is closed | /* ---------- Electron init ------------------------------------------------- */
import { app, BrowserWindow } from 'electron'
/* ---------- Requires ------------------------------------------------------ */
import { host, port } from '../scripts/config'
import { isDev } from '../scripts/env'
import path from 'path'
/*... | /* ---------- Electron init ------------------------------------------------- */
import { app, BrowserWindow } from 'electron'
/* ---------- Requires ------------------------------------------------------ */
import { host, port } from '../scripts/config'
import { isDev } from '../scripts/env'
import path from 'path'
/*... |
Set default value for event stream module | /*
* 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
* distribut... | /*
* 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
* distribut... |
Change response status type from string to bool | package handlers
import (
"encoding/json"
"log"
"net/http"
)
//ReturnInternalServerError returns an Internal Server Error
func ReturnInternalServerError(w http.ResponseWriter, message string) {
log.Println(message)
response := make(map[string]interface{})
response["status"] = false
w.WriteHeader(http.StatusInt... | package handlers
import (
"encoding/json"
"log"
"net/http"
)
//ReturnInternalServerError returns an Internal Server Error
func ReturnInternalServerError(w http.ResponseWriter, message string) {
log.Println(message)
response := make(map[string]string)
response["status"] = "false"
w.WriteHeader(http.StatusIntern... |
Make sure ESLint covers all JS unit tests | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* global __dirname, require */
var gulp = require('gulp');
var karma = require('karma');
var eslint = require('g... | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* global __dirname, require */
var gulp = require('gulp');
var karma = require('karma');
var eslint = require('g... |
Fix LCD display of the first line. | "use strict";
const env = require('../../env');
if (env.lcd.enable) {
let Lcd;
if (env.inDevMode) {
Lcd = require('gpio-peripherals-test').lcd;
} else {
Lcd = require('lcd');
}
let lcd = new Lcd({
cols: env.lcd.cols,
rows: env.lcd.rows,
rs: env.lcd.rs,
e: env.lcd.e,
data: env.lcd.data
});
let p... | "use strict";
const env = require('../../env');
if (env.lcd.enable) {
let Lcd;
if (env.inDevMode) {
Lcd = require('gpio-peripherals-test').lcd;
} else {
Lcd = require('lcd');
}
let lcd = new Lcd({
cols: env.lcd.cols,
rows: env.lcd.rows,
rs: env.lcd.rs,
e: env.lcd.e,
data: env.lcd.data
});
let p... |
Update oslo log messages with translation domains
Update the incubator code to use different domains for log
messages at different levels.
Update the import exceptions setting for hacking to allow
multiple functions to be imported from gettextutils on one
line.
bp log-messages-translation-domain
Change-Id: I6ce0f4a... | # Copyright (c) 2013 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | # Copyright (c) 2013 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
Make Lisk counters patch more robust
Summary:
We need to revert this patch and we will need to re-apply it later.
We can't drop the table and delete these rows as we need to run both versions for a temporary period.
Test Plan: Applied it.
Reviewers: epriestley, nh
Reviewed By: epriestley
CC: aran, Korvin
Differen... | <?php
// Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs.
// Set the initial counter ID to be larger than any known task ID.
$active_table = new PhabricatorWorkerActiveTask();
$archive_table = new PhabricatorWorkerArchiveTask();
$conn_w = $active_table->establishConnection('w');
$active_aut... | <?php
// Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs.
// Set the initial counter ID to be larger than any known task ID.
$active_table = new PhabricatorWorkerActiveTask();
$archive_table = new PhabricatorWorkerArchiveTask();
$conn_w = $active_table->establishConnection('w');
$active_aut... |
Add 4,000Mbps plan to VPCRouter | // Copyright 2016-2019 The Libsacloud Authors
//
// 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... | // Copyright 2016-2019 The Libsacloud Authors
//
// 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... |
Remove nginx as a directly supported option. | 'use strict';
var _ = require('lodash');
var prompts = [
{
type: 'input',
name: 'projectName',
message: 'Machine-name of your project?',
// Name of the parent directory.
default: _.last(process.cwd().split('/')),
validate: function (input) {
return (input.search(' ') === -1) ? true : '... | 'use strict';
var _ = require('lodash');
var prompts = [
{
type: 'input',
name: 'projectName',
message: 'Machine-name of your project?',
// Name of the parent directory.
default: _.last(process.cwd().split('/')),
validate: function (input) {
return (input.search(' ') === -1) ? true : '... |
Fix Wishlist add button on Spree 4.1 | (function() {
Spree.ready(function($) {
$('#new_wished_product').on('submit', function() {
var cart_quantity, selected_variant_id;
selected_variant_id = $('#product-variants input[type=radio]:checked').val();
if (selected_variant_id) {
$('#wished_product_variant_id').val(selected_variant... | (function() {
Spree.ready(function($) {
$('#new_wished_product').on('submit', function() {
var cart_quantity, selected_variant_id;
selected_variant_id = $('#product-variants input[type=radio]:checked').val();
if (selected_variant_id) {
$('#wished_product_variant_id').val(selected_variant... |
Refresh widget when config changes | import BoardView from 'app/components/serverboard/board'
import store from 'app/utils/store'
import {
serverboards_widget_list,
serverboard_update_widget_catalog,
board_update_now
} from 'app/actions/serverboard'
const Board = store.connect({
state: (state) => ({
widgets: state.serverboard.widgets,
w... | import BoardView from 'app/components/serverboard/board'
import store from 'app/utils/store'
import {
serverboards_widget_list,
serverboard_update_widget_catalog,
board_update_now
} from 'app/actions/serverboard'
const Board = store.connect({
state: (state) => ({
widgets: state.serverboard.widgets,
w... |
Use Setext strategy in GitHub built in Collector | """
File that initializes a Collector object designed for GitHub style markdown
files.
"""
from anchorhub.collector import Collector
from anchorhub.builtin.github.cstrategies import \
MarkdownATXCollectorStrategy, MarkdownSetextCollectorStrategy
import anchorhub.builtin.github.converter as converter
import anchorh... | """
File that initializes a Collector object designed for GitHub style markdown
files.
"""
from anchorhub.collector import Collector
from anchorhub.builtin.github.cstrategies import MarkdownATXCollectorStrategy
import anchorhub.builtin.github.converter as converter
import anchorhub.builtin.github.switches as ghswitche... |
Use io.open for py2/py3 compat | import os
import io
import json
from setuptools import setup
with io.open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding="utf-8") as f:
readme = f.read()
with io.open(os.path.join(os.path.dirname(__file__), 'package.json'), encoding="utf-8") as f:
package = json.loads(f.read())
setup(
nam... | import os
import json
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding="utf-8") as f:
readme = f.read()
with open(os.path.join(os.path.dirname(__file__), 'package.json'), encoding="utf-8") as f:
package = json.loads(f.read())
setup(
name=package['name'... |
Set the target of zombies spawned by the Zombie curse | /*
* Copyright (c) 2014 Wyatt Childers.
*
* All Rights Reserved
*/
package com.skelril.aurora.prayer.PrayerFX;
import com.skelril.aurora.prayer.PrayerType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
/**
* Author: Turtle9598
*/
public class ZombieFX extends AbstractEffect {
@Override... | /*
* Copyright (c) 2014 Wyatt Childers.
*
* All Rights Reserved
*/
package com.skelril.aurora.prayer.PrayerFX;
import com.skelril.aurora.prayer.PrayerType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
/**
* Author: Turtle9598
*/
public class ZombieFX extends AbstractEffect {
@Override... |
Add delegated credential to remove operation
git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1376 e217846f-e12e-0410-a4e5-89ccaea66ff7 | package edu.usc.glidein.service.impl;
import java.rmi.RemoteException;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.ResourceContext;
import edu.usc.glidein.stubs.RemoveRequest;
import edu.usc.glidein.stubs.types.EmptyObject;
import edu.usc.glidein.stubs.types.Site;
public ... | package edu.usc.glidein.service.impl;
import java.rmi.RemoteException;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.ResourceContext;
import edu.usc.glidein.stubs.types.EmptyObject;
import edu.usc.glidein.stubs.types.Site;
public class SiteService
{
private SiteResource g... |
Use object attributes; adjust appearance | Template.homeResidentActivityLevelTrend.rendered = function () {
// Get reference to template instance
var instance = this;
instance.autorun(function () {
// Get reference to Route
var router = Router.current();
// Get current Home ID
var homeId = router.params.homeId;
// Get data for trend... | Template.homeResidentActivityLevelTrend.rendered = function () {
// Get reference to template instance
var instance = this;
instance.autorun(function () {
// Get reference to Route
var router = Router.current();
// Get current Home ID
var homeId = router.params.homeId;
// Get data for trend... |
Use sets to define allowed regions for plugins | from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self, attrs=None):
default_attrs = {"class": ... | from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self, attrs=None):
default_attrs = {"class": ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.