text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use full path for eslint-config-airbnb | 'use strict'
const _ = require('lodash')
const extendConfig = require('../lib/extendConfig')
const mainRules = require('./main')
const eslintConfigAirbnb = extendConfig({
extends: 'eslint-config-airbnb'
})
const migratedRules = {}
const migrateRuleNames = [
'array-bracket-spacing',
'arrow-parens',
'generato... | 'use strict'
const _ = require('lodash')
const extendConfig = require('../lib/extendConfig')
const mainRules = require('./main')
const eslintConfigAirbnb = extendConfig({
extends: 'airbnb'
})
const migratedRules = {}
const migrateRuleNames = [
'array-bracket-spacing',
'arrow-parens',
'generator-star-spacing... |
Fix NPE for mispelled/missing directories in type-ahead file lookup |
package water.api;
import java.io.File;
import com.google.gson.*;
public class TypeaheadFileRequest extends TypeaheadRequest {
public TypeaheadFileRequest() {
super("Provides a simple JSON array of filtered local files.","");
}
@Override
protected JsonArray serve(String filter, int limit) {
File b... |
package water.api;
import java.io.File;
import com.google.gson.*;
public class TypeaheadFileRequest extends TypeaheadRequest {
public TypeaheadFileRequest() {
super("Provides a simple JSON array of filtered local files.","");
}
@Override
protected JsonArray serve(String filter, int limit) {
File b... |
Fix Dir resolver test to succeed with multiple CPUs
Fixes this problem:
$ go test -cpu=1,2 ./...
...
--- FAIL: TestResolve (0.00 seconds)
panic: chdir ../../testdata: no such file or directory [recovered]
See https://blog.splice.com/lesser-known-features-go-test/ | package dir_test
import (
"os"
"path"
"testing"
"github.com/mlafeldt/chef-runner/resolver/dir"
"github.com/mlafeldt/chef-runner/util"
"github.com/stretchr/testify/assert"
)
func TestResolve(t *testing.T) {
util.InDir("../../testdata", func() {
cookbookPath := "test-cookbooks"
defer os.RemoveAll(cookbookPa... | package dir_test
import (
"os"
"path"
"testing"
"github.com/mlafeldt/chef-runner/resolver/dir"
"github.com/mlafeldt/chef-runner/util"
"github.com/stretchr/testify/assert"
)
const CookbookPath = "test-cookbooks"
func TestResolve(t *testing.T) {
if err := os.Chdir("../../testdata"); err != nil {
panic(err)
... |
Fix updating to github gist | Template.viewGist.helpers({
description: function () {
return JSON.parse(this.content).description
},
files: function () {
return Object.keys(JSON.parse(this.content).files)
.map(filename => Object.assign(
JSON.parse(this.content).files[filename],
{ gistId: this._id }
))
}
})... | Template.viewGist.helpers({
description: function () {
return JSON.parse(this.content).description
},
files: function () {
console.log(JSON.parse(this.content).files)
const array = Object.keys(JSON.parse(this.content).files).map(filename => JSON.parse(this.content).files[filename])
return array
... |
Add a slash after port number | <?php namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class ServeCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'serve';
/**
* The console command description.
*
* @var string
... | <?php namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class ServeCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'serve';
/**
* The console command description.
*
* @var string
... |
Use double quotes for strings | # -*- coding: utf-8 -*-
import django
DEBUG = False
USE_TZ = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
INSTALLED_APPS = [
"easy_pjax",
"tests"
]
MIDDLEWARE_CLASSES = []
ROOT_URLCONF = "tests.urls"
SECRET_KEY = "secret"
if django.VERSION[:2] >= (1, 8):
TE... | # -*- coding: utf-8 -*-
import django
DEBUG = False
USE_TZ = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
INSTALLED_APPS = [
"easy_pjax",
"tests"
]
MIDDLEWARE_CLASSES = []
ROOT_URLCONF = "tests.urls"
SECRET_KEY = "secret"
if django.VERSION[:2] >= (1, 8):
TE... |
Switch to PEP 440 compliant version string and bump to 0.6.7.dev0. | import platform
import sys
__version__ = "0.6.7.dev0"
SERVER_ID = ','.join([platform.system(),
platform.release(),
'UPnP/1.0,Coherence UPnP framework',
__version__])
try:
from twisted import version as twisted_version
from twisted.web import ... | import platform
import sys
__version_info__ = (0, 6, 7)
__version__ = '.'.join(map(str, __version_info__))
SERVER_ID = ','.join([platform.system(),
platform.release(),
'UPnP/1.0,Coherence UPnP framework',
__version__])
try:
from twisted import ve... |
Drop test database after run the test | module.exports = function (grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'lib/**/*.js',
'test/**/*.js'
]
},
bgShell: {
dropDatabase: {
cmd: 'mongo mwc_logs_test --eval "db.dropDatabase()"',
bg: false
}
},
mochacli: {
o... | module.exports = function (grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'lib/**/*.js',
'test/**/*.js'
]
},
bgShell: {
dropDatabase: {
cmd: 'mongo mwc_logs_test --eval "db.dropDatabase()"',
bg: false
}
},
mochacli: {
o... |
Add integration test for db init | from piper import build
from piper.db import core as db
from piper.cli import cmd_piper
from piper.cli.cli import CLIBase
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piper.entry(self.mock)
c... | from piper import build
from piper.db import core as db
from piper.cli import cmd_piper
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piper.entry(self.mock)
clibase.assert_called_once_with(
... |
Use the url pathname so we don't include query args | var url = require('url')
exports.create = function(logger) {
return function(req, res, next) {
var rEnd = res.end;
// To track response time
req._rlStartTime = new Date();
// Setup the key-value object of data to log and include some basic info
req.kvLog = {
date: req._rlStartTime.toIS... | exports.create = function(logger) {
return function(req, res, next) {
var rEnd = res.end;
// To track response time
req._rlStartTime = new Date();
// Setup the key-value object of data to log and include some basic info
req.kvLog = {
date: req._rlStartTime.toISOString()
, method: ... |
Increase security loading the .env.testing file | <?php
/*
* This file is part of the Blackfire SDK package.
*
* (c) Blackfire <support@blackfire.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Blackfire\Bridge\Laravel;
use Dotenv\Dotenv;
use Illuminate\Contracts\... | <?php
/*
* This file is part of the Blackfire SDK package.
*
* (c) Blackfire <support@blackfire.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Blackfire\Bridge\Laravel;
use Dotenv\Dotenv;
use Illuminate\Contracts\... |
Fix incorrect container layouts being used
#35 #36 | package net.blay09.mods.trashslot.api;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.awt.Rectangle;
import java.util.List;
@SideOnly(Side.CLIENT)
public interface IGuiContainerLayout {
List<Rectan... | package net.blay09.mods.trashslot.api;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.awt.Rectangle;
import java.util.List;
@SideOnly(Side.CLIENT)
public interface IGuiContainerLayout {
List<Rectan... |
Disable fractal on empty config | <?php
namespace Aztech\Layers\Elements;
use Aztech\Layers\LayerBuilder;
use Aztech\Phinject\Container;
use League\Fractal\Manager;
use Symfony\Component\HttpFoundation\Request;
use Aztech\Layers\Layer;
class FractalRenderingLayerBuilder implements LayerBuilder
{
private $container;
private $manager;
p... | <?php
namespace Aztech\Layers\Elements;
use Aztech\Layers\LayerBuilder;
use Aztech\Phinject\Container;
use League\Fractal\Manager;
use Symfony\Component\HttpFoundation\Request;
use Aztech\Layers\Layer;
class FractalRenderingLayerBuilder implements LayerBuilder
{
private $container;
private $manager;
p... |
Update with reference to global nav partial | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var postcss = require('postcss')
var cssstats = require('cssstats')
var widths = require('tachyons-widths/package.json')
var widthsCss = fs.readFileSync('node_modules/tachyons-widths/tachyons-widths.min.... | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var postcss = require('postcss')
var cssstats = require('cssstats')
var tachyons = require('./package.json')
var widths = require('tachyons-widths/package.json')
var widthsCss = fs.readFileSync('node_mod... |
tests: Fix typo in mock usage
The error was made evident by a newer mock version that no longer
swallowed the wrong assert as regular use of a spec-less mock. | from __future__ import absolute_import, unicode_literals
from mock import patch
from tests.mpd import protocol
class ConnectionHandlerTest(protocol.BaseTestCase):
def test_close_closes_the_client_connection(self):
with patch.object(self.session, 'close') as close_mock:
self.send_request('cl... | from __future__ import absolute_import, unicode_literals
from mock import patch
from tests.mpd import protocol
class ConnectionHandlerTest(protocol.BaseTestCase):
def test_close_closes_the_client_connection(self):
with patch.object(self.session, 'close') as close_mock:
self.send_request('cl... |
Disable react-in-jsx-scope ESLint rule because of Flareact | module.exports = {
extends: ['airbnb', 'plugin:prettier/recommended', 'prettier/react'],
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true,
},
rules: {
'jsx-a11y/href-no-hash': ['off'],
'react/react-in-jsx-scope': ['off'],
'react/jsx-filename-extension': ['w... | module.exports = {
extends: ['airbnb', 'plugin:prettier/recommended', 'prettier/react'],
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true,
},
rules: {
'jsx-a11y/href-no-hash': ['off'],
'react/jsx-filename-extension': ['warn', { extensions: ['.js', '.jsx'] }],
... |
Move matrix calcs from webglshadows | import { LightShadow } from './LightShadow.js';
import { _Math } from '../math/Math.js';
import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js';
/**
* @author mrdoob / http://mrdoob.com/
*/
function SpotLightShadow() {
LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
}
SpotLightS... | import { LightShadow } from './LightShadow.js';
import { _Math } from '../math/Math.js';
import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js';
/**
* @author mrdoob / http://mrdoob.com/
*/
function SpotLightShadow() {
LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
}
SpotLightS... |
feat: Merge prior order_to_card_order with order id | # importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
grouped = order_products_prior_df.groupby('order_id', as_index = False)
grouped_data = pd.DataFrame()
gro... | # importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
print('length of orders_prior_df:', len(orders_prior_df))
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
print('length of order_products_prior_df:', len(or... |
Use PHPUnit's equality constraint for query assertion | <?php
namespace Helmich\MongoMock\Assert;
use Helmich\MongoMock\MockCollection;
use Helmich\MongoMock\Query;
class QueryWasExecutedConstraint extends \PHPUnit_Framework_Constraint
{
/** @var array */
private $filter;
/** @var array */
private $options;
public function __construct($filter, $opti... | <?php
namespace Helmich\MongoMock\Assert;
use Helmich\MongoMock\MockCollection;
use Helmich\MongoMock\Query;
class QueryWasExecutedConstraint extends \PHPUnit_Framework_Constraint
{
/** @var array */
private $filter;
/** @var array */
private $options;
public function __construct($filter, $opti... |
Remove BaseMail dependency on User object | from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(sel... | from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(sel... |
Remove this merge as numpy shouldn't be a dependency | # -*- coding: utf-8 -*-
"""
twython.compat
~~~~~~~~~~~~~~
This module contains imports and declarations for seamless Python 2 and
Python 3 compatibility.
"""
import sys
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplejson as json
except ... | # -*- coding: utf-8 -*-
"""
twython.compat
~~~~~~~~~~~~~~
This module contains imports and declarations for seamless Python 2 and
Python 3 compatibility.
"""
import sys
import numpy as np
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplej... |
Enable the correct exception check on the test, was disabled when inspecting the contents of the exception | package net.stickycode.configured.finder;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
public abstract class AbstractBeanFinderTest {
protected abstract BeanFinder getFinder();
@Test
public void lookupPrototype() {
Bean bean = getFinder().find(Bean.class);
assertTha... | package net.stickycode.configured.finder;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
public abstract class AbstractBeanFinderTest {
protected abstract BeanFinder getFinder();
@Test
public void lookupPrototype() {
Bean bean = getFinder().find(Bean.class);
assertTha... |
Set up argparse to accept params and display usage | """Perform static analysis on a Swift source file."""
import argparse
import os
import sys
PARENT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(PARENT_PATH)
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from tailor.listeners.mainlistener import MainListene... | import os
import sys
PARENT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(PARENT_PATH)
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from tailor.listeners.mainlistener import MainListener
from tailor.output.printer import Printer
from tailor.swift.swiftlexe... |
Create a new string, instead of modifying the `template` | import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
text = re.sub(r'<a.*?</a>', '', text)
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if not string:
return 'No Descri... | import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
text = re.sub(r'<a.*?</a>', '', text)
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if not string:
return 'No Descri... |
Remove page, add offset and limit to filtered filters | import React, { Component } from 'react'
import { isArray, forEach } from 'lodash'
import qs from 'qs'
import Datasets from './Datasets'
const DISABLED_FILTERS = [ 'q', 'offset', 'limit' ]
export function _extractFilters(query) {
let filters = []
forEach(query, function(value, key) {
if (DISABLED_FILTERS.incl... | import React, { Component } from 'react'
import { isArray, forEach } from 'lodash'
import qs from 'qs'
import Datasets from './Datasets'
const DISABLED_FILTERS = ['q', 'page', ]
export function _extractFilters(query) {
let filters = []
forEach(query, function(value, key) {
if (DISABLED_FILTERS.includes(key)) ... |
Add script, style, meta and link filters. | <?php
/**
* @version $Id$
* @package Nooku_Server
* @subpackage Articles
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Html View Class
*
* @a... | <?php
/**
* @version $Id$
* @package Nooku_Server
* @subpackage Articles
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Html View Class
*
* @a... |
Remove error handling and useless winston | var amqp = require('amqplib');
var amqpUrl, amqpConnection, intervalID;
function connect(_amqpUrl) {
amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost';
return amqp.connect(amqpUrl)
.then(function (_connection) {
amqpConnection = _connection;
_connection.on('close', reconnect)... | var amqp = require('amqplib');
var winston = require('winston');
var amqpUrl, amqpConnection, intervalID;
function connect(_amqpUrl) {
amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost';
return amqp.connect(amqpUrl)
.then(function (_connection) {
amqpConnection = _connection;
... |
Switch from deprecated ActionBarActivity to AppCompatActivity | package io.github.hidroh.materialistic;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.analytics.GoogleAnalytics;
public abstract class TrackableActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
... | package io.github.hidroh.materialistic;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import com.google.android.gms.analytics.GoogleAnalytics;
public abstract class TrackableActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
... |
Fix sources protocol to HTTPS. | module.exports = function (grunt) {
return {
options: {
separator: Array(3).join(grunt.util.linefeed),
sourceRoot: process.env.CI ? 'https://raw.github.com/' + process.env.TRAVIS_REPO_SLUG + '/' + process.env.TRAVIS_COMMIT : '../..'
},
all: {
files: {
'dist/<%= pkgName %>.js': [
'umd/header.js'... | module.exports = function (grunt) {
return {
options: {
separator: Array(3).join(grunt.util.linefeed),
sourceRoot: process.env.CI ? 'http://raw.github.com/' + process.env.TRAVIS_REPO_SLUG + '/' + process.env.TRAVIS_COMMIT : '../..'
},
all: {
files: {
'dist/<%= pkgName %>.js': [
'umd/header.js',... |
Remove link to unused color palette | var $elements = {
game_over: document.getElementById('game_over'),
you_won: document.getElementById('you_won'),
};
var canvas = SVG('canvas').size(window.innerWidth-40, window.innerHeight-document.getElementById('canvas').offsetTop-20);
var board = new Board(canvas);
var stopwatch = new StopWatch({delay: 5, timer: ... | // http://www.colourlovers.com/palette/3459622/Flowering_Tiles
var $elements = {
game_over: document.getElementById('game_over'),
you_won: document.getElementById('you_won'),
};
var canvas = SVG('canvas').size(window.innerWidth-40, window.innerHeight-document.getElementById('canvas').offsetTop-20);
var board = new... |
Rename Promise var to avoid conflict with native promise | var base = require('42-cent-base');
var util = require('util');
var P = require('bluebird');
function GatewayMock(options) {
base.BaseGateway.call(this);
this.options = options;
}
util.inherits(GatewayMock, base.BaseGateway);
GatewayMock.prototype.submitTransaction = function (order, cc, prospect, other) {
va... | var base = require('42-cent-base');
var util = require('util');
var Promise = require('bluebird');
function GatewayMock(options) {
base.BaseGateway.call(this);
this.options = options;
}
util.inherits(GatewayMock, base.BaseGateway);
GatewayMock.prototype.submitTransaction = function (order, cc, prospect, other) {... |
Add user activated Nova filter name | <?php
namespace OpenDominion\Nova\Filters;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;
class UserActivated extends Filter
{
/**
* The displayable name of the action.
*
* @var string
*/
public $name = 'Activated';
/**
* Apply the filter to the given query.
... | <?php
namespace OpenDominion\Nova\Filters;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;
class UserActivated extends Filter
{
/**
* Apply the filter to the given query.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Database\Eloquent\Builder $query
... |
Use new copy API (db, aws, callback)
The couch-to-s3 api was refactored, so we adjust. | #!/usr/bin/env node
var nconf = require('nconf');
var toS3 = require('couch-to-s3');
var cred = require('./lib/cred.js');
nconf.file('dev', 'config-dev.json').argv().env().file('config.json');
nconf.defaults({
"dbUrl": "http://localhost:5984",
"dbName": "database",
"s3BucketName": "bucket",
"awsCredentialsPath"... | #!/usr/bin/env node
var nconf = require('nconf');
var toS3 = require('couch-to-s3');
var cred = require('./lib/cred.js');
nconf.file('dev', 'config-dev.json').argv().env().file('config.json');
nconf.defaults({
"dbUrl": "http://localhost:5984",
"dbName": "database",
"s3BucketName": "bucket",
"awsCredentialsPath"... |
Add logging for missing CELERY_BROKER_URL | from celery import Celery
class NewAcropolisCelery(Celery):
def init_app(self, app):
if not app.config['CELERY_BROKER_URL']:
app.logger.info('Celery broker URL not set')
return
super(NewAcropolisCelery, self).__init__(
app.import_name,
broker=app.co... | from celery import Celery
class NewAcropolisCelery(Celery):
def init_app(self, app):
super(NewAcropolisCelery, self).__init__(
app.import_name,
broker=app.config['CELERY_BROKER_URL'],
)
app.logger.info('Setting up celery: %s', app.config['CELERY_BROKER_URL'])
... |
Fix mapping for codon keys for Tyrosine | # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UA... | # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UA... |
Check for nil file as well. | package main
// #include "types.h"
import "C"
import (
"fmt"
"github.com/amarburg/go-lazyquicktime"
)
//export MovInfo
func MovInfo(path *C.char) C.MovieInfo {
file, err := sourceFromCPath(path)
if file == nil || err != nil {
fmt.Printf("Error opening path: %s", err.Error())
return C.MovieInfo{}
}
qtInfo... | package main
// #include "types.h"
import "C"
import (
"fmt"
"github.com/amarburg/go-lazyquicktime"
)
//export MovInfo
func MovInfo(path *C.char) C.MovieInfo {
file, err := sourceFromCPath(path)
if err != nil {
fmt.Printf("Error opening path: %s", err.Error())
return C.MovieInfo{}
}
qtInfo, err := lazyqu... |
Validate the schema when loading it. | """The Pibstack.yaml parsing code."""
import yaml
from .schema import validate
class StackConfig(object):
"""The configuration for the stack."""
def __init__(self, path_to_repo):
self.services = {} # map service name to config dict
self.databases = {} # map database name to config dict
... | """The Pibstack.yaml parsing code."""
import yaml
class StackConfig(object):
"""The configuration for the stack."""
def __init__(self, path_to_repo):
self.services = {} # map service name to config dict
self.databases = {} # map database name to config dict
self.path_to_repo = pat... |
Set block to air after picking up fluids | package mariculture.core.handlers;
import mariculture.core.Core;
import mariculture.core.blocks.base.BlockFluid;
import mariculture.core.items.ItemBuckets;
import net.minecraft.block.Block;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.FillBucketEve... | package mariculture.core.handlers;
import mariculture.core.Core;
import mariculture.core.blocks.base.BlockFluid;
import mariculture.core.items.ItemBuckets;
import net.minecraft.block.Block;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.FillBucketEve... |
Use Device.js to determine mobile editor use
Ref #2570
- Adds new library, device.js to determine if the user is on an ios mobile
or tablet. | /*global CodeMirror, device*/
import mobileUtils from 'ghost/utils/mobile-utils';
import createTouchEditor from 'ghost/assets/lib/touch-editor';
var setupMobileCodeMirror,
TouchEditor,
init;
setupMobileCodeMirror = function setupMobileCodeMirror() {
var noop = function () {},
key;
for (key in... | /*global CodeMirror*/
import mobileUtils from 'ghost/utils/mobile-utils';
import createTouchEditor from 'ghost/assets/lib/touch-editor';
var setupMobileCodeMirror,
TouchEditor,
init;
setupMobileCodeMirror = function setupMobileCodeMirror() {
var noop = function () {},
key;
for (key in CodeMir... |
Make constructor public, needs to be accessible from org.glassfish.jersey.* | /*
* Copyright 2014, The OpenNMS Group
*
* 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 2014, The OpenNMS Group
*
* 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... |
Apply mongoose and promise pattern. | var config = require('./config'),
Twit = require('twit'),
mongoose = require('mongoose');
var T = new Twit(config.oauth_creds),
quotes = mongoose.model('quotes', {msg: String, src: String});
var tweet = function () {
var promise = quotes.count().exec();
promise.then(function (cnt) {
var n = Math.f... | var config = require('./config'),
Twit = require('twit'),
MongoClient = require('mongodb').MongoClient;
var T = new Twit(config.oauth_creds);
var tweet = function() {
MongoClient.connect(config.db_uri, function (err, db) {
if (err) throw err;
var collection = db.collection('quotes');
collection... |
Add attribution to quotes in plugin | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... |
Disable RRD queue feature when testing so files are actually written when we write to them. :-) | package org.opennms.netmgt.dao.support;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.opennms.netmgt.rrd.RrdConfig;
import org.opennms.netmgt.rrd.RrdException;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy;
public class RrdTestUtils {
... | package org.opennms.netmgt.dao.support;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.opennms.netmgt.rrd.RrdConfig;
import org.opennms.netmgt.rrd.RrdException;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy;
public class RrdTestUtils {
... |
Set the alias of the function `val` to `v`. | # encoding: utf-8
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs = []
... | # encoding: utf-8
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs = []
... |
Add test to Path compare. | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize(... | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize(... |
Handle supplying metric collector by env var. | var net = require('net');
var config = require('hyperflowMonitoringPlugin.config.js');
var MonitoringPlugin = function () {
};
MonitoringPlugin.prototype.sendMetrics = function () {
var that = this;
//TODO: Create connection once and then try to reuse it
var parts = config.metricCollector.split(':');
... | var net = require('net');
var config = require('hyperflowMonitoringPlugin.config.js');
var MonitoringPlugin = function () {
};
MonitoringPlugin.prototype.sendMetrics = function () {
var that = this;
//TODO: Create connection once and then try to reuse it
var parts = config.metricCollector.split(':');
... |
Use professional vs instead of community if found | #!/bin/python3.5
import os
config = """
.WindowsSDKBasePath10 = 'C:/Program Files (x86)/Windows Kits/10'
.WindowsSDKSubVersion = '10.0.15063.0'
#if __WINDOWS__
.FazEPath = 'CURRENT_DIRECTORY'
.FBuildCache = 'C:/temp/fazecache'
.VulkanSDKBasePath = 'C:/VulkanSDK/1.0.54.0'
#endif
#if __LINUX__
.FazEPath = 'CURRENT_DIREC... | #!/bin/python3.5
import os
config = """
.VSBasePath = 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community'
.WindowsSDKBasePath10 = 'C:/Program Files (x86)/Windows Kits/10'
.WindowsSDKSubVersion = '10.0.15063.0'
#if __WINDOWS__
.FazEPath = 'CURRENT_DIRECTORY'
.FBuildCache = 'C:/temp/fazecache'
.VulkanSDK... |
Reword and add emoji on reference | export function createPostbackAction(label, input, issuedAt) {
return {
type: 'postback',
label,
data: JSON.stringify({
input,
issuedAt,
}),
};
}
export function createFeedbackWords(feedbacks) {
let positive = 0;
let negative = 0;
feedbacks.forEach(e => {
if (e.score > 0) {
... | export function createPostbackAction(label, input, issuedAt) {
return {
type: 'postback',
label,
data: JSON.stringify({
input,
issuedAt,
}),
};
}
export function createFeedbackWords(feedbacks) {
let positive = 0, negative = 0;
feedbacks.forEach(e => {
if (e.score > 0) {
po... |
Allow install of multiple programs
Fixes #26 | #!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var meow = require('meow');
var process = require('process');
var allPrograms = [
'atom',
'bash',
'bin',
'git',
'gnome-terminal',
'vim',
'vscode'
];
var cli = meow({
help: [
'Usage: dotfiles install [<program>...]',
'',
'where <prog... | #!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var meow = require('meow');
var process = require('process');
var allPrograms = [
'atom',
'bash',
'bin',
'git',
'gnome-terminal',
'vim',
'vscode'
];
var cli = meow({
help: [
'Usage: dotfiles install [<program>]',
'',
'where <program... |
Add a download_url for pypi | #!/usr/bin/python
import distutils
from setuptools import setup, Extension
long_desc = """This is a C extension module for Python which
implements extended attributes manipulation. It is a wrapper on top
of the attr C library - see attr(5)."""
version = "0.5.1"
author = "Iustin Pop"
author_email = "iusty@k1024.org"
m... | #!/usr/bin/python
import distutils
from setuptools import setup, Extension
long_desc = """This is a C extension module for Python which
implements extended attributes manipulation. It is a wrapper on top
of the attr C library - see attr(5)."""
version = "0.5.1"
author = "Iustin Pop"
author_email = "iusty@k1024.org"
m... |
Return *SMSResponse for text and *CALLResponse for call | package twigo
func NewClient(account_sid, auth_token, number string) (*Client, error) {
c := &Client{AccountSid:account_sid,AuthToken:auth_token,Number:number}
err := Validate(*c)
if err != nil {
return nil,err
}
return c, nil
}
func (c *Client) Text(msg_sms *SMS) (*SMSResponse, error) {
err := Validate(... | package twigo
func NewClient(account_sid, auth_token, number string) (*Client, error) {
c := &Client{AccountSid:account_sid,AuthToken:auth_token,Number:number}
err := Validate(*c)
if err != nil {
return nil,err
}
return c, nil
}
func (c *Client) Text(msg_sms *SMS) (interface{}, error) {
err := Validate(*... |
Fix fixture for older versions | import pytest
import factory
from factory.alchemy import SQLAlchemyModelFactory
from pytest_factoryboy import register
from ckan.plugins import toolkit
import ckan.model as model
from ckanext.googleanalytics.model import PackageStats, ResourceStats
if toolkit.requires_ckan_version("2.9"):
@pytest.fixture()
... | import pytest
import factory
from factory.alchemy import SQLAlchemyModelFactory
from pytest_factoryboy import register
import ckan.model as model
from ckanext.googleanalytics.model import PackageStats, ResourceStats
@pytest.fixture()
def clean_db(reset_db, migrate_db_for):
reset_db()
migrate_db_for("google... |
Remove apply shortcut from external api | "use strict";
window.arethusaExternalApi = function () {
var obj = {};
obj.isArethusaLoaded = function() {
try {
angular.module('arethusa');
return true;
} catch(err) {
return false;
}
};
// I guess it might come to this sort of guarding close, so that other plugin
// can impl... | "use strict";
window.arethusaExternalApi = function () {
var obj = {};
obj.isArethusaLoaded = function() {
try {
angular.module('arethusa');
return true;
} catch(err) {
return false;
}
};
// I guess it might come to this sort of guarding close, so that other plugin
// can impl... |
Simplify tests to new format. | """
Test suite for Reflex Axelrod PD player.
"""
import axelrod
from test_player import TestPlayer
class Reflex_test(TestPlayer):
name = "Reflex"
player = axelrod.Reflex
stochastic = False
def test_strategy(self):
""" First response should always be cooperation. """
p1 = axelrod.Ref... | """
Test suite for Reflex Axelrod PD player.
"""
import axelrod
from test_player import TestPlayer
class Reflex_test(TestPlayer):
def test_initial_nice_strategy(self):
""" First response should always be cooperation. """
p1 = axelrod.Reflex()
p2 = axelrod.Player()
self.assertEqual... |
serve: Remove plugin name from URL before passing it to the plugin. | import { createServer } from 'http'
import { Plugin } from 'munar-core'
import micro, { createError } from 'micro'
export default class Serve extends Plugin {
static defaultOptions = {
port: 3000
}
enable () {
this.server = micro(this.onRequest)
this.server.listen(this.options.port)
}
disable ... | import { createServer } from 'http'
import { Plugin } from 'munar-core'
import micro, { createError } from 'micro'
export default class Serve extends Plugin {
static defaultOptions = {
port: 3000
}
enable () {
this.server = micro(this.onRequest)
this.server.listen(this.options.port)
}
disable ... |
Fix ClickableBox dropping styles when not clickable | // @flow
import React from 'react'
import type {Props} from './clickable-box'
import Box from './box'
import {TouchableHighlight, TouchableWithoutFeedback} from 'react-native'
import {globalColors} from '../styles'
const ClickableBox = ({onClick, onLongPress, style, children, underlayColor, onPressIn, onPressOut, feed... | // @flow
import React from 'react'
import type {Props} from './clickable-box'
import {TouchableHighlight, TouchableWithoutFeedback} from 'react-native'
import {globalColors} from '../styles'
const ClickableBox = ({onClick, onLongPress, style, children, underlayColor, onPressIn, onPressOut, feedback = true}: Props) => ... |
Fix location type in get video
- Can just use raw int from C* | import Promise from 'bluebird';
import { GetVideoResponse, VideoLocationType } from './protos';
import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions';
import { NotFoundError } from '../common/grpc-errors';
import { getCassandraClient } from '../../common/cassandra';
/**
... | import Promise from 'bluebird';
import { GetVideoResponse, VideoLocationType } from './protos';
import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions';
import { NotFoundError } from '../common/grpc-errors';
import { getCassandraClient } from '../../common/cassandra';
/**
... |
Check to see if the url has the context path first. | /**
* Since IRIDA can be served within a container, all requests need to have
* the correct base url. This will add, if required, the base url.
*
* NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL
* BE AUTOMATICALLY HANDLED.
*
* @param {string} url
* @return {string|*}
*/
export functi... | /**
* Since IRIDA can be served within a container, all requests need to have
* the correct base url. This will add, if required, the base url.
*
* NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL
* BE AUTOMATICALLY HANDLED.
*
* @param {string} url
* @return {string|*}
*/
export functi... |
Add error message to NFC sample | scanButton.addEventListener("click", async () => {
log("User clicked scan button");
try {
const reader = new NDEFReader();
await reader.scan();
log("> Scan started");
reader.addEventListener("error", () => {
log(`Argh! ${error.message}`);
});
reader.addEventListener("reading", ({ me... | scanButton.addEventListener("click", async () => {
log("User clicked scan button");
try {
const reader = new NDEFReader();
await reader.scan();
log("> Scan started");
reader.addEventListener("error", () => {
log("Argh! Cannot read data from the NFC tag. Try a different one?");
});
r... |
Make it clearer that exactly one item allows psum < 0 | def _dynamic_wrap(items, limit):
scores, trace = [0], []
for j in range(len(items)):
best, psum, index = float('inf'), limit, -1
for i in reversed(range(j + 1)):
psum -= items[i]
score = scores[i] + psum ** 2
if score < best and (psum >= 0 or i == j):
... | def _dynamic_wrap(items, limit):
scores, trace = [0], []
for j in range(len(items)):
best, psum, index = 0, limit, -1
for i in reversed(range(j + 1)):
psum -= items[i]
score = scores[i] + psum ** 2
if i == j or score < best and psum >= 0:
best ... |
Fix argument count on `Error` | import ls from 'local-storage';
const defaulGetDocumentStorageId = (doc, name) => {
const { _id, conversationId } = doc
if (_id && name) { return {id: `${_id}${name}`, verify: true}}
if (_id) { return {id: _id, verify: true }}
if (conversationId) { return {id: conversationId, verify: true }}
if (name) { retu... | import ls from 'local-storage';
const defaulGetDocumentStorageId = (doc, name) => {
const { _id, conversationId } = doc
if (_id && name) { return {id: `${_id}${name}`, verify: true}}
if (_id) { return {id: _id, verify: true }}
if (conversationId) { return {id: conversationId, verify: true }}
if (name) { retu... |
Fix JSCS violation that snuck in while the reporter was broken | (function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'orders.details': {
url: '/details/:orderId',
templateUrl: 'app/states/ord... | (function(){
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'orders.details': {
url: '/details/:orderId',
templateUrl: 'app/states/orde... |
Fix for BISERVER-7626
Unable to create a CSV based data source | package org.pentaho.platform.dataaccess.datasource.wizard.models;
/**
* User: nbaker
* Date: Aug 13, 2010
*/
public class DatasourceDTOUtil {
public static DatasourceDTO generateDTO(DatasourceModel model){
DatasourceDTO dto = new DatasourceDTO();
dto.setDatasourceName(model.getDatasourceName());
dto.... | package org.pentaho.platform.dataaccess.datasource.wizard.models;
/**
* User: nbaker
* Date: Aug 13, 2010
*/
public class DatasourceDTOUtil {
public static DatasourceDTO generateDTO(DatasourceModel model){
DatasourceDTO dto = new DatasourceDTO();
dto.setDatasourceName(model.getDatasourceName());
dto.... |
Check if dataset exist on `head` node
document.body migth not be present if scripts are loaded in <head/> | module.exports=dataset;
/*global document*/
// replace namesLikeThis with names-like-this
function toDashed(name) {
return name.replace(/([A-Z])/g, function(u) {
return "-" + u.toLowerCase();
});
}
var fn;
if (document.head.dataset) {
fn = {
set: function(node, attr, value) {
node.dataset[attr]... | module.exports=dataset;
/*global document*/
// replace namesLikeThis with names-like-this
function toDashed(name) {
return name.replace(/([A-Z])/g, function(u) {
return "-" + u.toLowerCase();
});
}
var fn;
if (document.body.dataset) {
fn = {
set: function(node, attr, value) {
node.dataset[attr]... |
Add users count to json representation. | from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuMo... | from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuMo... |
Clean up the temporary file when done with it. | import os
from test_support import TESTFN
from UserList import UserList
# verify writelines with instance sequence
l = UserList(['1', '2'])
f = open(TESTFN, 'wb')
f.writelines(l)
f.close()
f = open(TESTFN, 'rb')
buf = f.read()
f.close()
assert buf == '12'
# verify writelines with integers
f = open(TESTFN, 'wb')
try:... | from test_support import TESTFN
from UserList import UserList
# verify writelines with instance sequence
l = UserList(['1', '2'])
f = open(TESTFN, 'wb')
f.writelines(l)
f.close()
f = open(TESTFN, 'rb')
buf = f.read()
f.close()
assert buf == '12'
# verify writelines with integers
f = open(TESTFN, 'wb')
try:
f.writ... |
fix: Use new interface for twine | """PyPI
"""
from invoke import run
from twine import settings
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi ... | """PyPI
"""
from invoke import run
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dis... |
Use django reverse function to obtain url instead of hard-coding | from django.views import View
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib import messages
from django import http
from django.urls import reverse
class LoginView(TemplateView):
template_name = "admin/login.html"
def post(self, request):
username =... | from django.views import View
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib import messages
from django import http
class LoginView(TemplateView):
template_name = "admin/login.html"
def post(self, request):
username = request.POST['username']
... |
Add 'Q' as a hotkey for panning | /*globals svgEditor, svgCanvas*/
/*jslint eqeq: true*/
/*
* ext-panning.js
*
* Licensed under the MIT License
*
* Copyright(c) 2013 Luis Aguirre
*
*/
/*
This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem
*/
svgEditor.addExtension('ext-panning', function() {'use stri... | /*globals svgEditor, svgCanvas*/
/*jslint eqeq: true*/
/*
* ext-panning.js
*
* Licensed under the MIT License
*
* Copyright(c) 2013 Luis Aguirre
*
*/
/*
This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem
*/
svgEditor.addExtension('ext-panning', function() {'use stri... |
Fix webpack bundle output path | /* global require */
var webpack = require('webpack');
//noinspection JSUnresolvedVariable
module.exports = {
entry: './client/main.js',
output: {
path: __dirname,
filename: './server/src/static/scripts/bundle.js'
},
module: {
rules: [
{
test: /\.js$... | /* global require */
var webpack = require('webpack');
//noinspection JSUnresolvedVariable
module.exports = {
entry: './client/main.js',
output: {
path: __dirname,
filename: './server/static/scripts/bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
... |
Make naming consistent with our standard (camelcase always, even with acronymn) | import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Insta... | import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Insta... |
Add java 6 compatible generic declaration | package controllers;
import models.Panic;
import play.mvc.Controller;
import play.mvc.results.RenderJson;
import java.util.ArrayList;
import java.util.List;
public class Application extends Controller {
public static List<Panic> panics = new ArrayList<Panic>();
public static void index() {
render()... | package controllers;
import models.Panic;
import play.mvc.Controller;
import play.mvc.results.RenderJson;
import java.util.ArrayList;
import java.util.List;
public class Application extends Controller {
public static List<Panic> panics = new ArrayList<>();
public static void index() {
render();
... |
Update aerial-accounts version -> 0.4.0 | Package.describe({
name: 'bquarks:aerialjs',
version: '0.1.4',
// Brief, one-line summary of the package.
summary: 'Suite Aerialjs to connect Meteor applications with Corble Platform.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/bquarks/aerialjs.git',
... | Package.describe({
name: 'bquarks:aerialjs',
version: '0.1.4',
// Brief, one-line summary of the package.
summary: 'Suite Aerialjs to connect Meteor applications with Corble Platform.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/bquarks/aerialjs.git',
... |
Support for listing all packages | package cmd
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
"sort"
)
func init() {
RootCmd.AddCommand(searchCommand)
}
var searchCommand = &cobra.Command{
Use: "search [TERM]",
Short: "Search for packages on Docker Hub",
Long: "Sea... | package cmd
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
)
func init() {
RootCmd.AddCommand(searchCommand)
}
var searchCommand = &cobra.Command{
Use: "search TERM",
Short: "Search for packages on Docker Hub",
RunE: func(cmd *cobra... |
Use throw instead of reject when possible | import fs from 'fs';
import crypto from 'crypto';
import multihash from 'multihashes';
import bs58 from 'bs58';
export const HASH_MAP = {
sha1: 'sha1',
sha256: 'sha2-256',
sha512: 'sha2-512'
};
export default function hashFile(input, algorithm) {
return new Promise((resolve, reject) => {
const algorithmNa... | import fs from 'fs';
import crypto from 'crypto';
import multihash from 'multihashes';
import bs58 from 'bs58';
export const HASH_MAP = {
sha1: 'sha1',
sha256: 'sha2-256',
sha512: 'sha2-512'
};
export default function hashFile(input, algorithm) {
return new Promise((resolve, reject) => {
const algorithmNa... |
Add ignore all events function | type LivEventHandler = (msgData: Object) => void;
export default class LiveEvents {
messageHandlers: Object;
constructor() {
this.messageHandlers = {};
}
emitSingle(msgType: string, msgData: Object) {
const handlers = this.messageHandlers[msgType] || [];
handlers.forEach(hand... | type LivEventHandler = (msgData: Object) => void;
export default class LiveEvents {
messageHandlers: Object;
constructor() {
this.messageHandlers = {};
}
emitSingle(msgType: string, msgData: Object) {
const handlers = this.messageHandlers[msgType] || [];
handlers.forEach(hand... |
Update link to IRC page | <article>
<h1>Welcome to laravel.io</h1>
<p>Laravel: Ins and Outs is a project created and maintained by the {{ HTML::link('http://laravel.io/irc', '#Laravel community on irc.freenode.net') }}. Our focus is to provide regular study topics that will grow our combined knowledge of the Laravel framework.</p>
... | <article>
<h1>Welcome to laravel.io</h1>
<p>Laravel: Ins and Outs is a project created and maintained by the {{ HTML::link('http://laravel.com/irc', '#Laravel community on irc.freenode.net') }}. Our focus is to provide regular study topics that will grow our combined knowledge of the Laravel framework.</p>
... |
Fix browsertesting tests behaving differently on different browsers | describe('admin add contexts', function() {
it('should add new contexts', function() {
var deferred = protractor.promise.defer();
browser.setLocation('admin/contexts');
var add_context = function(context) {
element(by.model('new_context.name')).sendKeys(context);
return element(by.css('[data... | describe('admin add contexts', function() {
it('should add new contexts', function() {
var deferred = protractor.promise.defer();
browser.setLocation('admin/contexts');
var add_context = function(context) {
element(by.model('new_context.name')).sendKeys(context);
return element(by.css('[data... |
Add only() option for filtering clients for a broadcast | var EventEmitter = require('events').EventEmitter;
function ClientPool(){
var list = {};
var client_pool = this;
this.list = list;
this.count = 0;
//called in the context of the client (this = client)
this._on_client_disconnect = function(){
client_pool.remove(this);
}
}
var proto = ClientPool.prototype = ... | var EventEmitter = require('events').EventEmitter;
function ClientPool(){
var list = {};
var client_pool = this;
this.list = list;
this.count = 0;
//called in the context of the client (this = client)
this._on_client_disconnect = function(){
client_pool.remove(this);
}
}
var proto = ClientPool.prototype = ... |
Add DIR to HOME
* Add .pyrosar directory to HOME-path. | from setuptools import setup, find_packages
import os
# Create .pyrosar in HOME - Directory
directory = os.path.join(os.path.expanduser("~"), '.pyrosar')
if not os.path.exists(directory):
os.makedirs(directory)
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='... | from setuptools import setup, find_packages
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
in... |
Clarify tusks solenoid on slot 2 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kevin Wang
*/
public class Tusks extends Subsystem {
... | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kevin Wang
*/
public class Tusks extends Subsystem {
... |
Change $Identity so that it can be used as part of an html identifier | /* eslint no-unused-vars: 0 */
/***********************************/
/** data-calculate-row-identities **/
/***********************************/
gridState.processors['data-calculate-row-identities'] = {
watches: ['data', 'columns'],
runs: function (options) {
if (!options.model.ui.selectable) {
... | /* eslint no-unused-vars: 0 */
/***********************************/
/** data-calculate-row-identities **/
/***********************************/
gridState.processors['data-calculate-row-identities'] = {
watches: ['data', 'columns'],
runs: function (options) {
if (!options.model.ui.selectable) {
... |
Throw undefined error more friendly | import { helper } from 'ember-helper'
import { defaultLocale, changeLocale, localeHasBeenChanged } from '../utils/locale'
import generateImageURL from '../utils/image'
import faker from 'faker'
faker.locale = defaultLocale
export function fake([signature, ...args], {parse = false, locale, ...opts}) {
// running in ... | import { helper } from 'ember-helper'
import { defaultLocale, changeLocale, localeHasBeenChanged } from '../utils/locale'
import generateImageURL from '../utils/image'
import faker from 'faker'
faker.locale = defaultLocale
export function fake([signature, ...args], {parse = false, locale, ...opts}) {
// running in ... |
Enable SASI indexes when running mapper tests against C* 4 | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wri... | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wri... |
Hide window by hotkey if it is visible | import { BrowserWindow, globalShortcut } from 'electron';
import {
INPUT_HEIGHT,
WINDOW_WIDTH,
RESULT_HEIGHT,
MIN_VISIBLE_RESULTS
} from './constants/ui';
import buildMenu from './createWindow/buildMenu';
export default (url) => {
const mainWindow = new BrowserWindow({
alwaysOnTop: true,
show: false... | import { BrowserWindow, globalShortcut } from 'electron';
import {
INPUT_HEIGHT,
WINDOW_WIDTH,
RESULT_HEIGHT,
MIN_VISIBLE_RESULTS
} from './constants/ui';
import buildMenu from './createWindow/buildMenu';
export default (url) => {
const mainWindow = new BrowserWindow({
alwaysOnTop: true,
show: false... |
Move proxyRes out of request handler; trap errors | var httpProxy = require('http-proxy');
var http = require('http');
var CORS_HEADERS = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE',
'access-control-max-age': '86400',
'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Conten... | var httpProxy = require('http-proxy');
var http = require('http');
var CORS_HEADERS = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE',
'access-control-max-age': '86400',
'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Conten... |
Stop using soft ipmi resets until figuring out why it does not work in a lot of cases | import time
import logging
import multiprocessing.pool
from rackattack.physical.ipmi import IPMI
class ColdReclaim:
_CONCURRENCY = 8
_pool = None
def __init__(self, hostname, username, password, hardReset):
self._hostname = hostname
self._username = username
self._password = pas... | import time
import logging
import multiprocessing.pool
from rackattack.physical.ipmi import IPMI
class ColdReclaim:
_CONCURRENCY = 8
_pool = None
def __init__(self, hostname, username, password, hardReset):
self._hostname = hostname
self._username = username
self._password = pas... |
Fix config variable exposing to global scope | /**
* Simple wrapper to wrap around the Cacheman nodejs package to integrate easily with SailsJS for caching.
* @param {[string]} name Name the Cache Instance.
*/
var Cache = function (name) {
var Cacheman = require('cacheman');
var _ = require('underscore');
var options = {};
// Get configuration
va... | /**
* Simple wrapper to wrap around the Cacheman nodejs package to integrate easily with SailsJS for caching.
* @param {[string]} name Name the Cache Instance.
*/
var Cache = function (name) {
var Cacheman = require('cacheman');
var _ = require('underscore');
var options = {};
// Get configuration
co... |
Remove duplicate addFiles in test-in-browser
This actually resulted in two copies of diff_match_patch in the package! | Package.describe({
summary: "Run tests interactively in the browser",
version: '1.0.7',
documentation: null
});
Package.onUse(function (api) {
// XXX this should go away, and there should be a clean interface
// that tinytest and the driver both implement?
api.use('tinytest');
api.use('bootstrap@1.0.1');... | Package.describe({
summary: "Run tests interactively in the browser",
version: '1.0.7',
documentation: null
});
Package.onUse(function (api) {
// XXX this should go away, and there should be a clean interface
// that tinytest and the driver both implement?
api.use('tinytest');
api.use('bootstrap@1.0.1');... |
Change RemindableInterface to correct namespace | <?php namespace Analogue\LaravelAuth;
use Analogue\ORM\Entity;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Entity implements UserInterface, RemindableInterface {
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
publ... | <?php namespace Analogue\LaravelAuth;
use Analogue\ORM\Entity;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\RemindableInterface;
class User extends Entity implements UserInterface, RemindableInterface {
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public functio... |
Fix NodeJS shim in Vector2 file | function Vector2(x, y) {
this.x = x;
this.y = y;
}
Vector2.prototype.add = function(other) {
if (!(other instanceof Vector2)) throw new TypeError("Cannot add '" + other + "'' to '" + this + "'!");
return new Vector2(this.x + other.x, this.y + other.y);
};
Vector2.prototype.subtract = function(other) {
if (!(other ... | function Vector2(x, y) {
this.x = x;
this.y = y;
}
Vector2.prototype.add = function(other) {
if (!(other instanceof Vector2)) throw new TypeError("Cannot add '" + other + "'' to '" + this + "'!");
return new Vector2(this.x + other.x, this.y + other.y);
};
Vector2.prototype.subtract = function(other) {
if (!(other ... |
Add test case for svg() (like h() is) | 'use strict';
/* global describe, it */
let assert = require('assert');
let Cycle = require('../../src/cycle');
describe('Cycle', function () {
describe('API', function () {
it('should have `applyToDOM`', function () {
assert.strictEqual(typeof Cycle.applyToDOM, 'function');
});
it('should have `r... | 'use strict';
/* global describe, it */
let assert = require('assert');
let Cycle = require('../../src/cycle');
describe('Cycle', function () {
describe('API', function () {
it('should have `applyToDOM`', function () {
assert.strictEqual(typeof Cycle.applyToDOM, 'function');
});
it('should have `r... |
Remove phase from project factory | import factory
import logging
from django.conf import settings
from bluebottle.projects.models import (
Project, ProjectTheme, ProjectDetailField, ProjectBudgetLine)
from .accounts import BlueBottleUserFactory
# Suppress debug information for Factory Boy
logging.getLogger('factory').setLevel(logging.WARN)
clas... | import factory
import logging
from django.conf import settings
from bluebottle.projects.models import (
Project, ProjectTheme, ProjectDetailField, ProjectBudgetLine)
from .accounts import BlueBottleUserFactory
# Suppress debug information for Factory Boy
logging.getLogger('factory').setLevel(logging.WARN)
clas... |
Save compressed files to a different directory | var gulp = require('gulp')
, concat = require('gulp-concat')
, uglify = require('gulp-uglify');
gulp.task('compress-css', function () {
gulp.src([
"public/css/leaflet.css",
"public/css/bootstrap.min.css",
"public/css/main.css"
])
.pipe(concat('build.css'))
.pipe(gulp.dest('public/dist/'))... | var gulp = require('gulp')
, concat = require('gulp-concat')
, uglify = require('gulp-uglify');
gulp.task('compress-css', function () {
gulp.src([
"public/css/leaflet.css",
"public/css/bootstrap.min.css",
"public/css/main.css"
])
.pipe(concat('build.css'))
.pipe(gulp.dest('public/css'));
... |
Allow formSelector directive as attribute | "use strict";
angular.module('arethusa.morph').directive('formSelector', function() {
return {
restrict: 'AE',
replace: true,
controller: function($scope, $element, $attrs) {
var id = $scope.id;
var form = $scope.form;
$scope.selected = function() {
return $scope.plugin.isFormSe... | "use strict";
angular.module('arethusa.morph').directive('formSelector', function() {
return {
restrict: 'E',
replace: true,
controller: function($scope, $element, $attrs) {
var id = $scope.id;
var form = $scope.form;
$scope.selected = function() {
return $scope.plugin.isFormSel... |
Remove placeholders in the controller arrays | 'use strict';
var kanjiApp = angular.module('kanjiApp', []);
kanjiApp.controller('KanjiCtrl', ['$scope', 'search', 'kanjiDictionary', function($scope, search, kanjiDictionary) {
$scope.saved = [];
$scope.findKanji = search.findKanji;
$scope.findWords = search.findWords;
$scope.getKanjiMeaning = kanjiDictionar... | 'use strict';
var kanjiApp = angular.module('kanjiApp', []);
kanjiApp.controller('KanjiCtrl', ['$scope', 'search', 'kanjiDictionary', function($scope, search, kanjiDictionary) {
$scope.saved = ["blah"];
$scope.findKanji = search.findKanji;
$scope.findWords = search.findWords;
$scope.getKanjiMeaning = kanjiDic... |
Use shortcut instead of an ID as a key. | import './Gallery.scss';
import React, { Component, PropTypes } from 'react';
import Image from './Image.react';
import map from 'lodash/collection/map';
import AssetSchema from '../schemas/asset';
import BaguetteBox from 'baguettebox.js';
class Gallery extends Component {
constructor(props, context) {
super(pro... | import './Gallery.scss';
import React, { Component, PropTypes } from 'react';
import Image from './Image.react';
import map from 'lodash/collection/map';
import AssetSchema from '../schemas/asset';
import BaguetteBox from 'baguettebox.js';
class Gallery extends Component {
constructor(props, context) {
super(pro... |
Support multi-db for user creation signal | from __future__ import absolute_import, print_function
from django.db import router
from django.db.models.signals import post_syncdb
from sentry.models import User
def create_first_user(app, created_models, verbosity, db, **kwargs):
if User not in created_models:
return
if not router.allow_syncdb(db... | from __future__ import absolute_import, print_function
from django.db.models.signals import post_syncdb
from sentry.models import User
def create_first_user(app, created_models, verbosity, db, **kwargs):
if User not in created_models:
return
if not kwargs.get('interactive', True):
return
... |
Fix currency converter. Use multiply. | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\MoneyBundle\Converter;
use Sylius\Bundle\ResourceBundle\Model\RepositoryInter... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\MoneyBundle\Converter;
use Sylius\Bundle\ResourceBundle\Model\RepositoryInter... |
Fix an issue with the Jasmine log not outputting the full string. | var vui = vui || {};
vui.matchers = vui.matchers || {};
vui.matchers.jasmine = {
toMatchRecordedObjectAt: function() {
return {
compare: function ( actual, recordedObjectPath, exceptions ) {
var expectedResult;
//@if !RECORDING
expectedResult = vui.records.getRecord(recordedObjectPath);
//@endi... | var vui = vui || {};
vui.matchers = vui.matchers || {};
vui.matchers.jasmine = {
toMatchRecordedObjectAt: function() {
return {
compare: function ( actual, recordedObjectPath, exceptions ) {
var expectedResult;
//@if !RECORDING
expectedResult = vui.records.getRecord(recordedObjectPath);
//@endi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.