text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add test for module_path extension | <?php
namespace Nwidart\Modules\Tests;
use Illuminate\Support\Str;
class HelpersTest extends BaseTestCase
{
/**
* @var \Illuminate\Filesystem\Filesystem
*/
private $finder;
/**
* @var string
*/
private $modulePath;
public function setUp(): void
{
parent::setUp();
... | <?php
namespace Nwidart\Modules\Tests;
use Illuminate\Support\Str;
class HelpersTest extends BaseTestCase
{
/**
* @var \Illuminate\Filesystem\Filesystem
*/
private $finder;
/**
* @var string
*/
private $modulePath;
public function setUp(): void
{
parent::setUp();
... |
Fix documentation. PHP does not allow arbitrary class casting.
svn commit r12147 | <?php
require_once 'Swat/Swat.php';
require_once 'Swat/SwatError.php';
require_once 'Swat/exceptions/SwatException.php';
/**
* The base object type
*
* @package Swat
* @copyright 2004-2006 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatObject
{
// {{{ public f... | <?php
require_once 'Swat/Swat.php';
require_once 'Swat/SwatError.php';
require_once 'Swat/exceptions/SwatException.php';
/**
* The base object type
*
* @package Swat
* @copyright 2004-2006 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatObject
{
// {{{ public f... |
Change function from public to protected | <?php namespace Lio\Forum\Replies;
use Lio\Core\FormModel;
use Validator;
class ReplyForm extends FormModel
{
protected $validationRules = [
'body' => 'required',
'_time' => 'min_time:2',
];
protected function beforeValidation()
{
$type = isset($this->inputData['_type']) ? $t... | <?php namespace Lio\Forum\Replies;
use Lio\Core\FormModel;
use Validator;
class ReplyForm extends FormModel
{
protected $validationRules = [
'body' => 'required',
'_time' => 'min_time:2',
];
public function beforeValidation()
{
$type = isset($this->inputData['_type']) ? $this... |
Fix flash message on test add | <?php
namespace Egzaminer\Exam;
use Egzaminer\Admin\Dashboard as Controller;
class ExamAdd extends Controller
{
public function addAction()
{
if (isset($_POST['add'])) {
$model = new ExamAddModel();
if ($id = $model->add($_POST)) {
$_SESSION['valid'] = true;
... | <?php
namespace Egzaminer\Exam;
use Egzaminer\Admin\Dashboard as Controller;
class ExamAdd extends Controller
{
public function addAction()
{
if (isset($_POST['add'])) {
$model = new ExamAddModel();
if ($id = $model->add($_POST)) {
$this->data['valid'] = true;
... |
Make the reset datastore servlet clear ride requests | package com.sheepdog.mashmesh.debug;
import com.googlecode.objectify.Objectify;
import com.sheepdog.mashmesh.models.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ResetDatastoreServlet ext... | package com.sheepdog.mashmesh.debug;
import com.googlecode.objectify.Objectify;
import com.sheepdog.mashmesh.models.OfyService;
import com.sheepdog.mashmesh.models.RideRecord;
import com.sheepdog.mashmesh.models.UserProfile;
import com.sheepdog.mashmesh.models.VolunteerProfile;
import javax.servlet.http.HttpServlet;
... |
Allow addon to be nested at depth of n | /* jshint node: true */
'use strict';
var VersionChecker = require('ember-cli-version-checker');
module.exports = {
name: 'ember-scrollable',
init: function() {
this._super.init && this._super.init.apply(this, arguments);
var checker = new VersionChecker(this);
this._checkerForEmber = checker.for('... | /* jshint node: true */
'use strict';
var VersionChecker = require('ember-cli-version-checker');
module.exports = {
name: 'ember-scrollable',
init: function() {
this._super.init && this._super.init.apply(this, arguments);
var checker = new VersionChecker(this);
this._checkerForEmber = checker.for('... |
Send emails to non @uprise.org accounts in production settings. | const path = require('path');
module.exports = {
sessionOptions: {
secret: process.env.SESSION_SECRET_KEY,
saveUninitialized: true, // save new sessions
resave: false, // do not automatically write to the session store
cookie: {
httpOnly: true,
maxAge: 2419200000
} // TODO set sec... | const path = require('path');
module.exports = {
sessionOptions: {
secret: process.env.SESSION_SECRET_KEY,
saveUninitialized: true, // save new sessions
resave: false, // do not automatically write to the session store
cookie: {
httpOnly: true,
maxAge: 2419200000
} // TODO set sec... |
Add display name for clock | import React, {Component} from 'react';
import moment from 'moment-timezone';
import classnames from 'classnames';
import styles from './style.scss';
export default class Dashboard extends Component {
componentWillMount() {
this.timeTick();
setInterval(this.timeTick.bind(this), 1000 /* ms */);
}
timeT... | import React, {Component} from 'react';
import moment from 'moment-timezone';
import classnames from 'classnames';
import styles from './style.scss';
export default class Dashboard extends Component {
componentWillMount() {
this.timeTick();
setInterval(this.timeTick.bind(this), 1000 /* ms */);
}
timeT... |
Update request class so specing of controllers can progress | <?php
/**
* MageSpec
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT License, that is bundled with this
* package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
*
* http://opensource.org/licenses/MIT
*
* If you did not receive a copy of the license and ar... | <?php
/**
* MageSpec
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT License, that is bundled with this
* package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
*
* http://opensource.org/licenses/MIT
*
* If you did not receive a copy of the license and ar... |
Disable some tests in test_hbase_insert to fix the build.
Change-Id: I037b292d0eb93c5c743a201b2045eb2ba0712ae7
Reviewed-on: http://gerrit.ent.cloudera.com:8080/387
Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
Tested-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@clouder... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'f... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Targeted Impala HBase Tests
#
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestHBaseQueries(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'f... |
Rewrite urlpatterns to new format | from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views as core_views
urlpatterns = [ # pylint: disable=invalid-name
url(r'^$', core_views.upload_app, name="upload_app"),
url(r'^potrditev$',
TemplateV... | from __future__ import absolute_import, unicode_literals
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns( # pylint: disable=invalid-name
'',
url(r'^$', 'uploader.views.upload_app', name="upload_app"),
url(r'^potrditev$',
TemplateVie... |
Verify non-generic members also work just fine | <?php namespace net\xp_framework\unittest\core\generics;
use util\Objects;
/**
* Lookup map
*/
#[@generic(self= 'K, V', parent= 'K, V')]
class Lookup extends AbstractDictionary {
protected $size;
#[@generic(var= '[:V]')]
protected $elements= [];
/**
* Put a key/value pairt
*
* @param K key
... | <?php namespace net\xp_framework\unittest\core\generics;
use util\Objects;
/**
* Lookup map
*/
#[@generic(self= 'K, V', parent= 'K, V')]
class Lookup extends AbstractDictionary {
#[@generic(var= '[:V]')]
protected $elements= [];
/**
* Put a key/value pairt
*
* @param K key
* @param V value... |
Update redis config from deprecated - pooling enabled by default | package fi.nls.oskari.spring.session;
import fi.nls.oskari.util.PropertyUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisStandaloneConfigura... | package fi.nls.oskari.spring.session;
import fi.nls.oskari.util.PropertyUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.jedis.JedisConnectionFac... |
Increase search history max items to 99 and always push latest search word to top order | import { SEARCH_HISTORY } from '../constants/actionTypes';
export default function searchHistory(
state = {
items: [],
},
action = {},
) {
switch (action.type) {
case SEARCH_HISTORY.ADD: {
let newItems;
const { items } = state;
const newItem = action.payload.item;
if (items && i... | import { SEARCH_HISTORY } from '../constants/actionTypes';
export default function searchHistory(
state = {
items: [],
},
action = {},
) {
switch (action.type) {
case SEARCH_HISTORY.ADD: {
let newItems;
const items = state.items;
const newItem = action.payload.item;
if (items &&... |
Add scipy in requirements list | from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Developme... | from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Developme... |
Fix up the /ajax/translate/ sanitizing | <?php
/**
* @package content
*/
/**
* The AjaxTranslate page is used for translating strings on the fly
* that are used in Symphony's javascript
*/
Class contentAjaxTranslate extends AjaxPage{
public function handleFailedAuthorisation(){
$this->_status = self::STATUS_UNAUTHORISED;
$this->_Result =... | <?php
/**
* @package content
*/
/**
* The AjaxTranslate page is used for translating strings on the fly
* that are used in Symphony's javascript
*/
Class contentAjaxTranslate extends AjaxPage{
public function handleFailedAuthorisation(){
$this->_status = self::STATUS_UNAUTHORISED;
$this->_Result =... |
FIx tests for America/Adak timezone | var parse = require('../parse/index.js')
var getDaysInMonth = require('../get_days_in_month/index.js')
/**
* @category Month Helpers
* @summary Set the month to the given date.
*
* @description
* Set the month to the given date.
*
* @param {Date|String|Number} date - the date to be changed
* @param {Number} mo... | var parse = require('../parse/index.js')
var getDaysInMonth = require('../get_days_in_month/index.js')
/**
* @category Month Helpers
* @summary Set the month to the given date.
*
* @description
* Set the month to the given date.
*
* @param {Date|String|Number} date - the date to be changed
* @param {Number} mo... |
Add URL matching to Wikipedia module | const wiki = require('wikijs').default;
module.exports.commands = ['wiki', 'wikipedia'];
const urlRegex = /^(?:https?:\/\/)?(?:en\.)?wikipedia\.org\/wiki\/(.+)/;
const errorMessage = term => `No Wikipedia page found for "${term}"`;
function shortSummary(page, withUrl) {
return page.summary()
// Get the first ... | const wiki = require('wikijs').default;
module.exports.commands = ['wiki', 'wikipedia'];
function prettyPage(page) {
return page.summary()
// Get the first "sentence" (hopefully)
.then(str => str.substr(0, str.indexOf('.') + 1))
// Truncate with an ellipsis if length exceeds 250 chars
.then(str => (... |
Fix datetime usage in memorize model | from datetime import datetime, timedelta
from django.utils.timezone import utc
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from .algorithm import interval
class Practice(models.Mo... | from datetime import datetime, timedelta
import datetime
from django.utils.timezone import utc
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from .algorithm import interval
class Pra... |
Remove padding characters from cert URL.
This makes the URL prettier by removing reserved characters, and matches
the behavior of the planned AMP CDN URL. | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
Add error handler on html preprocessing
Close #238 | 'use strict';
var gulp = require('gulp');
var paths = gulp.paths;
var $ = require('gulp-load-plugins')();
gulp.task('markups', function() {
function renameToHtml(path) {
path.extname = '.html';
}
return gulp.src(paths.src + '/{app,components}/**/*.<%= props.htmlPreprocessor.extension %>')
<% if (props.ht... | 'use strict';
var gulp = require('gulp');
var paths = gulp.paths;
var $ = require('gulp-load-plugins')();
gulp.task('markups', function() {
function renameToHtml(path) {
path.extname = '.html';
}
return gulp.src(paths.src + '/{app,components}/**/*.<%= props.htmlPreprocessor.extension %>')
<% if (props.ht... |
Fix country ISO code for US | import pytest
from mock import Mock
from saleor.core.utils import (
Country, get_country_by_ip, get_currency_for_country)
@pytest.mark.parametrize('ip_data, expected_country', [
({'country': {'iso_code': 'PL'}}, Country('PL')),
({'country': {'iso_code': 'UNKNOWN'}}, None),
(None, None),
({}, None... | import pytest
from mock import Mock
from saleor.core.utils import (
Country, get_country_by_ip, get_currency_for_country)
@pytest.mark.parametrize('ip_data, expected_country', [
({'country': {'iso_code': 'PL'}}, Country('PL')),
({'country': {'iso_code': 'UNKNOWN'}}, None),
(None, None),
({}, None... |
Fix bug in rate limiting when processing commits | package client
import (
"sync"
"github.com/calebamiles/github-client/comments"
"github.com/calebamiles/github-client/commits"
)
func (c *DefaultClient) processCommits(commitWithoutComments commits.CommitWithoutComments, cs *commitAccumulator, ready chan struct{}, wg *sync.WaitGroup, errs *errorAccumulator) {
def... | package client
import (
"sync"
"github.com/calebamiles/github-client/comments"
"github.com/calebamiles/github-client/commits"
)
func (c *DefaultClient) processCommits(commitWithoutComments commits.CommitWithoutComments, cs *commitAccumulator, ready chan struct{}, wg *sync.WaitGroup, errs *errorAccumulator) {
def... |
Add - Simplest code to turn the Given into concrete actions (HTTP request to check that a POST resource exists) | /*
We use the output messages from the cucumber runner to create Step Definitions:
the glue between features written in Gherkin and the actual system under test.
Use Given, When, Then.
*/
let request = require('request');
const {defineSupportCode} = require('cucumber');
defineSupportCode(function({Given, Then, When}... | /*
We use the output messages from the cucumber runner to create Step Definitions:
the glue between features written in Gherkin and the actual system under test.
Use Given, When, Then.
*/
let request = require('request');
const {defineSupportCode} = require('cucumber');
defineSupportCode(function({Given, Then, When... |
Use the pool instead the database connection | package db
import (
"github.com/garyburd/redigo/redis"
)
// Save takes a key (struct used as template for all data containers to ease the managing of the DB)
// and generates an unique key in order to add the record to the DB.
func Save(key string, value []byte) error {
conn := pool.Get()
defer conn.Close()
_, e... | package db
import (
"github.com/garyburd/redigo/redis"
)
// Save takes a key (struct used as template for all data containers to ease the managing of the DB)
// and generates an unique key in order to add the record to the DB.
func Save(key string, value []byte) error {
defer mutex.Unlock()
mutex.Lock()
_, err :... |
Add columns and values to repr | from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
... | from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
... |
Fix for escaping single quote character(s) | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __in... | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __in... |
Set action set's for Kotlin perspective: open type, launch configurations | /*******************************************************************************
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.a... | /*******************************************************************************
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.a... |
Refactor server tree context menu into it's own component | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.blazzify.jasonium.ui;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.contr... | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.blazzify.jasonium.ui;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.contr... |
Change progress plugin javascript to replace progress with custom field value | window.GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController = (function() {
function GobiertoCommonCustomFieldRecordsProgressPluginController() {}
GobiertoCommonCustomFieldRecordsProgressPluginController.prototype.form = function(opts = {}) {
_handlePluginData(opts.uid);
};
function _ha... | window.GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController = (function() {
function GobiertoCommonCustomFieldRecordsProgressPluginController() {}
var grid;
GobiertoCommonCustomFieldRecordsProgressPluginController.prototype.form = function(opts = {}) {
_handlePluginData(opts.uid);
};
... |
Add in ability to instantiate non public default constructors | /***
*
* Copyright 2014 Andrew Hall
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agre... | /***
*
* Copyright 2014 Andrew Hall
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agre... |
Use verbose method name to avoid conflict with implementing class.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Support\Traits;
use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Orchestra\Support\Str;
trait UploadableTrait
{
/**
* Save uploaded file into directory.
*
* @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
... | <?php namespace Orchestra\Support\Traits;
use Orchestra\Support\Str;
use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
trait UploadableTrait {
/**
* Save uploaded file into directory
*
* @param use Symfony\Component\HttpFoundation\File\UploadedFile
... |
Make MNIST example py3 compatible. | import os
import gzip
import pickle
import sys
# Python 2/3 compatibility.
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
'''Adapted from theano tutorial'''
def load_mnist(data_file = './mnist.pkl.gz'):
if not os.path.exists(data_file):
origin = ... | import os
import gzip
import pickle
import urllib
import sys
'''Adapted from theano tutorial'''
def load_mnist(data_file = './mnist.pkl.gz'):
if not os.path.exists(data_file):
origin = ('http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz')
print('Downloading data from %s' % origin)
... |
Use cluster to utilize multiple cores
Add cluster module to utilize multiple cores. Closes #54. | // server.js
//
// entry point activity pump application
//
// Copyright 2011-2012, StatusNet 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... | // server.js
//
// entry point activity pump application
//
// Copyright 2011-2012, StatusNet 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... |
Fix molecule offset on mobile devices.
Use renderer size instead of canvas' |
import * as THREE from 'three';
function Axes(target, targetCamera) {
this._target = target;
this._targetCamera = targetCamera;
this._camera = new THREE.PerspectiveCamera(targetCamera.fov, targetCamera.aspect, 1, 100);
this._object = new THREE.AxisHelper(1);
this._scene = new THREE.Scene();
this._scene.a... |
import * as THREE from 'three';
function Axes(target, targetCamera) {
this._target = target;
this._targetCamera = targetCamera;
this._camera = new THREE.PerspectiveCamera(targetCamera.fov, targetCamera.aspect, 1, 100);
this._object = new THREE.AxisHelper(1);
this._scene = new THREE.Scene();
this._scene.a... |
Declare package_data to ensure month.aliases is included | from setuptools import setup, find_packages
def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#"))
def _read_requirements(filename):
"""Returns a list of package requirements re... | from setuptools import setup, find_packages
def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#"))
def _read_requirements(filename):
"""Returns a list of package requirements re... |
Use Args in cobra.Command to validate args.
Also re-use context.
Signed-off-by: Daniel Nephin <6347c07ae509164cffebfb1e2a0d6ed64958db19@docker.com> | package cli
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
// NoArgs validate args and returns an error if there are any args
func NoArgs(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
if cmd.HasSubCommands() {
return fmt.Errorf("\n" + strings.TrimRight(cmd.UsageString(),... | package cli
import (
"fmt"
"github.com/spf13/cobra"
)
// MinRequiredArgs checks if the minimum number of args exists, and returns an
// error if they do not.
func MinRequiredArgs(args []string, min int, cmd *cobra.Command) error {
if len(args) >= min {
return nil
}
return fmt.Errorf(
"\"%s\" requires at le... |
:wrench: Change post id on comment fixtures by reference | <?php
namespace OAuthBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use WordPressBundle\Entity\Comment;
class LoadCommentData extend... | <?php
namespace OAuthBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use WordPressBundle\Entity\Comment;
class LoadCommentData extend... |
Add check for websocket URI | 'use strict';
function EoleWebsocketClient(autobahn, webSocketUri, $q) {
if (!webSocketUri.match(/wss?:\/\//)) {
throw 'Websocket URI must start with "ws://" or "wss://", got "'+webSocketUri+'".';
}
/**
* @param {String} accessToken
*
* @returns {Promise} A socket session promise.
... | 'use strict';
function EoleWebsocketClient(autobahn, webSocketUri, $q) {
/**
* @param {String} accessToken
*
* @returns {Promise} A socket session promise.
*/
this.openSocket = function (accessToken) {
return $q(function (resolve, reject) {
var successCallback = function... |
Remove a bit of logging | import socketio from 'socket.io-client'
import log from 'services/log'
import foodsharing from 'services/foodsharing'
export let io = null
export const subscribers = []
export default {
/*
* Subscribe to the websocket receive all messages
* Returns an unsubscribe function
*/
subscribe (fn) {
subscr... | import socketio from 'socket.io-client'
import log from 'services/log'
import foodsharing from 'services/foodsharing'
export let io = null
export const subscribers = []
export default {
/*
* Subscribe to the websocket receive all messages
* Returns an unsubscribe function
*/
subscribe (fn) {
subscr... |
Add data holder for realm service | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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... | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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... |
Fix incorrect Javascript for changing Share API settings | $(document).ready(function(){
$('#loglevel').change(function(){
$.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){
OC.Log.reload();
} );
});
$('#backgroundjobs input').change(function(){
if($(this).attr('checked')){
var mode = $(this).val();
if (mode == 'aja... | $(document).ready(function(){
$('#loglevel').change(function(){
$.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){
OC.Log.reload();
} );
});
$('#backgroundjobs input').change(function(){
if($(this).attr('checked')){
var mode = $(this).val();
if (mode == 'aja... |
Add the current working directory for the user scripts to the main process. Preparation for possible handling of require | import safeEval from 'safe-eval';
import dir from 'node-dir';
import path from 'path';
import {ipcRenderer} from 'electron';
const babel = require('babel-core');
const babelOptions = {
presets: ['es2015']
}
let scriptDirectory = process.env.script;
let options = {
match: /.js$/,
exclude: /^\./,
recursive: fal... | import safeEval from 'safe-eval';
import dir from 'node-dir';
import path from 'path';
import {ipcRenderer} from 'electron';
const babel = require('babel-core');
const babelOptions = {
presets: ['es2015']
}
let scriptDirectory = process.env.script;
let options = {
match: /.js$/,
exclude: /^\./,
recursive: fal... |
Make use of existing config and override if values provided | var _ = require('underscore');
//returns the process object with the passed data for pagination and sorting
var buildQueryConfig = function(req, config) {
var sort = req.query.sort,
order = req.query.order,
filter = req.query.filter,
select = req.query.select,
skip = req.query.skip,
limit = req.query.limit... | var _ = require('underscore');
//returns the process object with the passed data for pagination and sorting
var buildQueryConfig = function(req, config) {
var sort = req.query.sort,
order = req.query.order,
filter = req.query.filter,
select = req.query.select,
skip = req.query.skip,
limit = req.query.limit... |
Use raw string for regular expression. | import re
from urlparse import urlsplit
class URLParser(object):
"""A minimal URL parser and splitter."""
scheme_re = re.compile(r'^(\S+?)://')
def get_scheme(self, url):
match = self.scheme_re.match(url)
if match is not None:
return match.group(1)
return ''
def... | import re
from urlparse import urlsplit
class URLParser(object):
"""A minimal URL parser and splitter."""
scheme_re = re.compile('^(\S+?)://')
def get_scheme(self, url):
match = self.scheme_re.match(url)
if match is not None:
return match.group(1)
return ''
def ... |
Add toString for better logging/output | package com.fundynamic.d2tm.game.math;
public class Vector2D<T extends Number> {
private final T x, y;
public static Vector2D zero() {
return new Vector2D(0, 0);
}
public Vector2D(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {
return x;
}
pu... | package com.fundynamic.d2tm.game.math;
public class Vector2D<T extends Number> {
private final T x, y;
public static Vector2D zero() {
return new Vector2D(0, 0);
}
public Vector2D(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {
return x;
}
pu... |
Check for missing config file name |
'use strict';
const path = require('path');
module.exports = (() => {
// const akasha = require('../index');
const Command = require('cmnd').Command;
class CopyAssetsCommand extends Command {
constructor() {
super('copy-assets');
}
help() {
... |
'use strict';
const path = require('path');
module.exports = (() => {
// const akasha = require('../index');
const Command = require('cmnd').Command;
class CopyAssetsCommand extends Command {
constructor() {
super('copy-assets');
}
help() {
... |
Fix SCSS name in fulpfile | // Run 'gulp' to do the important stuff
var gulp = require('gulp'),
prefixer = require('gulp-autoprefixer'),
sass = require('gulp-sass'),
livereload = require('gulp-livereload'),
nodemon = require('gulp-nodemon'),
jshint = require('gulp-jshint'),
connect = require('gulp-connect');
var path = require('path'... | // Run 'gulp' to do the important stuff
var gulp = require('gulp'),
prefixer = require('gulp-autoprefixer'),
sass = require('gulp-sass'),
livereload = require('gulp-livereload'),
nodemon = require('gulp-nodemon'),
jshint = require('gulp-jshint'),
connect = require('gulp-connect');
var path = require('path'... |
Use np.mean instead for unweighted mean
Signed-off-by: Lizhou Sha <d6acb26e253550574bc1141efa0eb5e6de15daeb@mit.edu> | import astropy.io.fits as fits
import numpy as np
import sys
from .util import stack_fits_data
METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True),
"average": lambda x: np.mean(x, axis=0),
"sum": lambda x: np.sum(x, axis=0)}
def create_parser(subparsers):
pars... | import astropy.io.fits as fits
import numpy as np
import sys
from .util import stack_fits_data
METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True),
"average": lambda x: np.average(x, axis=0),
"sum": lambda x: np.sum(x, axis=0)}
def create_parser(subparsers):
p... |
Switch to new music server | export const OFFICIAL_SERVER_URL = 'https://music4.bemuse.ninja/server'
export async function load(serverUrl, { fetch = global.fetch } = {}) {
const indexUrl = getServerIndexFileUrl(serverUrl)
const data = await fetch(indexUrl).then((response) => response.json())
if (Array.isArray(data.songs)) {
return data... | export const OFFICIAL_SERVER_URL = 'https://music.bemuse.ninja/live'
export async function load(serverUrl, { fetch = global.fetch } = {}) {
const indexUrl = getServerIndexFileUrl(serverUrl)
const data = await fetch(indexUrl).then((response) => response.json())
if (Array.isArray(data.songs)) {
return data
... |
Write test for duplicate kinds | package stow_test
import (
"errors"
"net/url"
"testing"
"github.com/cheekybits/is"
"github.com/graymeta/stow"
)
func TestKindByURL(t *testing.T) {
is := is.New(t)
u, err := url.Parse("test://container/item")
is.NoErr(err)
kind, err := stow.KindByURL(u)
is.NoErr(err)
is.Equal(kind, testKind)
}
func TestKi... | package stow_test
import (
"errors"
"net/url"
"testing"
"github.com/cheekybits/is"
"github.com/graymeta/stow"
)
func TestKindByURL(t *testing.T) {
is := is.New(t)
u, err := url.Parse("test://container/item")
is.NoErr(err)
kind, err := stow.KindByURL(u)
is.NoErr(err)
is.Equal(kind, testKind)
}
func TestKi... |
Add clears to common declarations |
const commonDeclarations = {
boxSizing: [
'border-box'
],
display: [
'block',
'inline-block',
'inline',
'table',
'table-cell',
'none'
],
float: [
'none',
'left',
'right'
],
clear: [
'none',
'left',
'right',
'both'
],
textAlign: [
'left',
... |
const commonDeclarations = {
boxSizing: [
'border-box'
],
display: [
'block',
'inline-block',
'inline',
'table',
'table-cell',
'none'
],
float: [
'none',
'left',
'right'
],
textAlign: [
'left',
'center',
'right',
'justify'
],
fontWeight: [
... |
Add io_profile in cli test | package cli
import (
"testing"
"github.com/libopenstorage/openstorage/api"
"github.com/stretchr/testify/require"
)
func TestCmdMarshalProto(t *testing.T) {
volumeSpec := &api.VolumeSpec{
Size: 64,
Format: api.FSType_FS_TYPE_EXT4,
}
data := cmdMarshalProto(volumeSpec, false)
require.Equal(
t,
`{
"ep... | package cli
import (
"testing"
"github.com/libopenstorage/openstorage/api"
"github.com/stretchr/testify/require"
)
func TestCmdMarshalProto(t *testing.T) {
volumeSpec := &api.VolumeSpec{
Size: 64,
Format: api.FSType_FS_TYPE_EXT4,
}
data := cmdMarshalProto(volumeSpec, false)
require.Equal(
t,
`{
"ep... |
Add META with 'order_separator' key to Japanese spelling
This is required due to a change in how separators are loaded
in spellnum.py. | # -*- coding: utf-8 -*-
"""Japanese rules and tables for the spellnum module"""
RULES = """
1x = 十{x}
ab = {a}十{b}
1xx = {100}{x}
axx = {a}{100}{x}
axxx = {a}千{x}
(a)xxxx = {a}{x}
"""
NUMBERS = {
0: '零',
1: '一',
2: '二',
3: '三',
4: '四',
5: '五',
6: '六',
7: '七',
8: '八',
9: '九',
... | # -*- coding: utf-8 -*-
"""Japanese rules and tables for the spellnum module"""
RULES = """
1x = 十{x}
ab = {a}十{b}
1xx = {100}{x}
axx = {a}{100}{x}
axxx = {a}千{x}
(a)xxxx = {a}{x}
"""
NUMBERS = {
0: '零',
1: '一',
2: '二',
3: '三',
4: '四',
5: '五',
6: '六',
7: '七',
8: '八',
9: '九',
... |
Set port as an environment variable | #!/usr/bin/env node
var weechat = require('weechat'),
notify = require('osx-notifier'),
client;
var properties = {
server: process.env.SERVER,
port: process.env.PORT,
password: process.env.PASSWORD,
ssl: false,
nicks: process.env.NICKS.split(',')
};
var raiseNotification = function(f... | #!/usr/bin/env node
var weechat = require('weechat'),
notify = require('osx-notifier'),
client;
var properties = {
server: process.env.SERVER,
port: 8001,
password: process.env.PASSWORD,
ssl: false,
nicks: process.env.NICKS.split(',')
};
var raiseNotification = function(from, message... |
Use cache dir based on file location | "use strict";
module.exports = function Browscap (cacheDir) {
if (typeof cacheDir === 'undefined') {
cacheDir = __dirname + '/sources/';
}
this.cacheDir = cacheDir;
/**
* parses the given user agent to get the information about the browser
*
* if no user agent is given, it uses {@see \BrowscapPH... | "use strict";
module.exports = function Browscap (cacheDir) {
if (typeof cacheDir === 'undefined') {
cacheDir = './sources/';
}
this.cacheDir = cacheDir;
/**
* parses the given user agent to get the information about the browser
*
* if no user agent is given, it uses {@see \BrowscapPHP\Helper\Su... |
Update licence header + Introduction of docstrings | #!/bin/env python
# A-John-Shots - Python module/library for saving Security Hash Algorithms into JSON format.
# Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com>
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO... | #!/bin/env python
# A-John-Shots - Python module/library for saving Security Hash Algorithms into JSON format.
# Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Publi... |
Create new API key on launching a new stack | import response from 'cfn-response'
import SNS from 'aws/sns'
import { Settings } from 'model/settings'
export async function handle (event, context, callback) {
if (event.RequestType === 'Update' || event.RequestType === 'Delete') {
response.send(event, context, response.SUCCESS)
return
}
const {
A... | import response from 'cfn-response'
import SNS from 'aws/sns'
import { Settings } from 'model/settings'
export async function handle (event, context, callback) {
if (event.RequestType === 'Update' || event.RequestType === 'Delete') {
response.send(event, context, response.SUCCESS)
return
}
const {
A... |
Refactor auth middleware to be more readable | import express from 'express'
import bodyParser from 'body-parser'
import auth from './lib/auth.js'
const PORT = process.env.PORT || 8080
const API_KEY = process.env.API_KEY || 'abc123'
const SALT = process.env.SALT || 'def456'
const app = express()
// Authentication middleware
const authMiddleware = (req, res, next)... | import express from 'express'
import bodyParser from 'body-parser'
import auth from './lib/auth.js'
const PORT = process.env.PORT || 8080
const API_KEY = process.env.API_KEY || 'abc123'
const SALT = process.env.SALT || 'def456'
const app = express()
// Authentication middleware
const authMiddleware = (req, res, next)... |
Fix regex in test case | var expect = require('expect');
module.exports = function chunk2(callback) {
function forEachElement(el) {
var src = el.getAttribute('src') || el.getAttribute('href');
var integrity = el.getAttribute('integrity');
if (src) {
var match = src.match(/[^\/]+\.(js|css)/);
if (match && integrity &&... | var expect = require('expect');
module.exports = function chunk2(callback) {
function forEachElement(el) {
var src = el.getAttribute('src') || el.getAttribute('href');
var integrity = el.getAttribute('integrity');
if (src) {
var match = src.match(/[^\/]+\.(js|css)/);
if (match && integrity &&... |
Fix blur issue with auth form validation | import React, { PropTypes } from 'react';
import styles from './AuthPage.css';
function AuthInputField(props) {
const {
input, type, placeholder, className, meta,
} = props;
const {
dirty, error,
} = meta;
return (
<div>
<div>
<input
{...input}
type={type}
... | import React, { PropTypes } from 'react';
import styles from './AuthPage.css';
function AuthInputField(props) {
const {
input, type, placeholder, className, meta,
} = props;
const {
touched, error,
} = meta;
return (
<div>
<div>
<input
{...input}
type={type}
... |
Add some useful binary info | <?php
return Affinity\Config::create([
//
// The system php command
//
'php' => 'php',
//
// The document root
//
'docroot' => 'public',
//
// The execution mode determines default operation for some processes which should
// naturally differ depending on the environment (development vs. produ... | <?php
return Affinity\Config::create([
//
// The execution mode determines default operation for some processes which should
// naturally differ depending on the environment (development vs. production)
//
'execution_mode' => IW\EXEC_MODE\DEVELOPMENT,
//
// Timezone
//
'timezone' => 'US/Pacific... |
[form] Add checking befor getEntity value.. | var assign = require('object-assign');
var isFunction = require('lodash/lang/isFunction');
var actionMixin = {
/**
* Get the entity identifier for the form loading.
* @returns {object} - The identifier of the entity.
*/
_getId: function formGetId() {
if(this.getId){
return this.getId();
}
... | var assign = require('object-assign');
var actionMixin = {
/**
* Get the entity identifier for the form loading.
* @returns {object} - The identifier of the entity.
*/
_getId: function formGetId() {
if(this.getId){
return this.getId();
}
return this.state.id;
},
/**
* Get the constr... |
Allow retrieving list of supported charsets | 'use strict';
// eslint-disable-next-line import/no-internal-modules
const encodings = require('iconv-lite/encodings');
const { omitBy } = require('../utilities');
const { DEFAULT_INPUT_CHARSET } = require('./constants');
const { validateCharset } = require('./validate');
const { decodeCharset } = require('./transfo... | 'use strict';
const { DEFAULT_INPUT_CHARSET } = require('./constants');
const { validateCharset } = require('./validate');
const { decodeCharset } = require('./transform');
// Normalize charset, including adding defaults and validating
const getCharset = function (charset, { format } = {}) {
const charsetA = addDef... |
Disable jobs overview for anonymous users | from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin
from daiquiri.core.utils import get_model_field_meta
from .models import QueryJob, Example
class QueryView(AnonymousAccessMixin, Template... | from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin
from daiquiri.core.utils import get_model_field_meta
from .models import QueryJob, Example
class QueryView(AnonymousAccessMixin, TemplateView):
template_name = 'query/query.html'
anonymou... |
DevTools: Fix forwarding keyboard shortcuts from target page
This was regressed by crrev.com/c/devtools/devtools-frontend/+/1942290
which removed an unused variable in response to a linting rule. That
variable referenced a call to construct a ForwardedInputEventHandler
instance. That constructor has a side-effect of r... | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Host from '../host/host.js';
import {KeyboardShortcut} from './KeyboardShortcut.js';
import {ForwardedShortcut} from './ShortcutRegistry.js';
... | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Host from '../host/host.js';
import {KeyboardShortcut} from './KeyboardShortcut.js';
import {ForwardedShortcut} from './ShortcutRegistry.js';
... |
Allow for more flexible url pattern | var Backbone = require('backbone');
var url = require('url');
"use strict";
exports.HistoryUpdate = Backbone.View.extend({
initialize : function () {
console.log('HistoryUpdate:initialize');
this.listenTo(this.model, "change:asset", this.assetChanged);
this.listenTo(this.model, "change:ac... | var Backbone = require('backbone');
var url = require('url');
"use strict";
exports.HistoryUpdate = Backbone.View.extend({
initialize : function () {
console.log('HistoryUpdate:initialize');
this.listenTo(this.model, "change:asset", this.assetChanged);
this.listenTo(this.model, "change:ac... |
Improve color display, remove gray from the texts | // ==UserScript==
// @name 网易云音乐海外助手
// @namespace http://www.sudodev.cn/music-163-access-abroad/
// @updateURL http://git.oschina.net/bobshi/NetEaseMusicHelper/raw/master/netease_music_helper.user.js
// @version 0.2
// @description 让海外的用户能正常听网易云音乐
// @author Bob
// @match http://music.163.c... | // ==UserScript==
// @name 网易云音乐海外助手
// @namespace http://www.sudodev.cn/music-163-access-abroad/
// @updateURL http://git.oschina.net/bobshi/NetEaseMusicHelper/raw/master/netease_music_helper.user.js
// @version 0.2
// @description 让海外的用户能正常听网易云音乐
// @author Bob
// @match http://music.163.c... |
Restructure redis returner, since it did notwork before anyway | '''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
'''
# Import python libs
import json
try:
... | '''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
'''
# Import python libs
import json
try:
... |
Use full paths & print our current command fully | #!/usr/bin/env python
import subprocess
import argparse
import os
parser = argparse.ArgumentParser(description="Tweet some Train Statuses!")
parser.add_argument("-s", "--station", dest="station", type=str, help="Station Short Code. Ex: 'SLM'")
parser.add_argument("-t", "--train", dest="train", type=int, help="Train N... | #!/usr/bin/env python
import subprocess
import argparse
parser = argparse.ArgumentParser(description="Tweet some Train Statuses!")
parser.add_argument("-s", "--station", dest="station", type=str, help="Station Short Code. Ex: 'SLM'")
parser.add_argument("-t", "--train", dest="train", type=int, help="Train Number. Ex:... |
Add note about virtualenv support | import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, most of this script could be replaced by:
#
# from d... | import sys
import sysconfig
import site
if __name__ == '__main__':
# This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured
# see discussion https://github.com/opencog/atomspace/issues/1782
#
# If the bug is fixed, this script could be replaced by:
#
# from distutils... |
Add semicolons and update comment | /**
* Directly export with short aliases to support browserify.
*/
exports.dot = exports.dotCase = require('dot-case');
exports.swap = exports.swapCase = require('swap-case');
exports.path = exports.pathCase = require('path-case');
exports.upper = exports.upperCase = require('u... | /**
* Straight exports with short alias, to support browserify.
*
*/
exports.dot = exports.dotCase = require('dot-case')
exports.swap = exports.swapCase = require('swap-case')
exports.path = exports.pathCase = require('path-case')
exports.upper = exports.upperCase = require('u... |
Remove quotes only when attributes do not contains whitespaces | <?php
namespace RenatoMarinho\LaravelPageSpeed\Middleware;
class RemoveQuotes extends PageSpeed
{
public function apply($buffer)
{
$replace = [
'/ src="(.\S*?)"/' => ' src=$1',
'/ width="(.\S*?)"/' => ' width=$1',
'/ height="(.\S*?)"/' => ' height=$1',
'... | <?php
namespace RenatoMarinho\LaravelPageSpeed\Middleware;
class RemoveQuotes extends PageSpeed
{
public function apply($buffer)
{
$replace = [
'/ src="(.*?)"/' => ' src=$1',
'/ width="(.*?)"/' => ' width=$1',
'/ height="(.*?)"/' => ' height=$1',
'/ name... |
Fix formatting errors reported by flake8. | import json
import requests
class RPCClient(object):
def __init__(self, hostname, port):
self.url = 'http://' + str(hostname) + ':' + str(port) + '/mopidy/rpc'
self.id = 0
def _do_rpc(self, method, params=None):
self.id += 1
data = {'method': method, 'jsonrpc': '2.0', 'id':... | import json
import requests
class RPCClient(object):
def __init__(self, hostname, port):
self.url = 'http://' + str(hostname) + ':' + str(port) + '/mopidy/rpc'
self.id = 0
def _do_rpc(self, method, params=None):
self.id += 1
data = { 'method': method, 'jsonrpc': '2.0', 'id'... |
chore(test): Use common ts compiler options in karma test and webpack build | module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'sinon-chrome', 'karma-typescript'],
files: [
'src/ts/**/*.ts'
],
exclude: [
'src/ts/constants.ts'
],
preprocessors: {
'src/ts/**/*.ts': ['karma-typescript']
},
client: {
c... | module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'sinon-chrome', 'karma-typescript'],
files: [
'src/ts/**/*.ts'
],
exclude: [
'src/ts/constants.ts'
],
preprocessors: {
'src/ts/**/*.ts': ['karma-typescript']
},
client: {
c... |
Reduce log spam from diesel. | import diesel
from aspen.server import BaseEngine
from diesel.protocols import wsgi
class Engine(BaseEngine):
diesel_app = None # a diesel diesel_app instance
def bind(self):
self.diesel_app = wsgi.WSGIApplication( self.website
, self.website.address[1]
... | import diesel
from aspen.server import BaseEngine
from diesel.protocols import wsgi
class Engine(BaseEngine):
app = None # a diesel app instance
def bind(self):
self.app = wsgi.WSGIApplication( self.website
, self.website.address[1]
... |
Fix issue with missing username | #! /usr/bin/env node
'use strict';
import {processIM, processChannel, processGroup, saveData} from './commons.js';
import PleasantProgress from 'pleasant-progress';
export function slackHistoryExport(args) {
const progress = new PleasantProgress();
progress.start('working');
if(args.type === 'dm') {
process... | #! /usr/bin/env node
'use strict';
import {processIM, processChannel, processGroup, saveData} from './commons.js';
import PleasantProgress from 'pleasant-progress';
export function slackHistoryExport(args) {
const progress = new PleasantProgress();
progress.start('working');
if(args.type === 'dm') {
process... |
Fix on soundcloudToHtml method name | <?php
/**
* Laravel4-SirTrevorJs
*
* @link https://github.com/caouecs/Laravel4-SirTrevorJS
*/
namespace Caouecs\Sirtrevorjs\Converter;
/**
* Sound for Sir Trevor Js
*
* @package Caouecs\Sirtrevorjs\Converter
*/
class SoundConverter
{
/**
* List of types for sound
*
* @access protected
... | <?php
/**
* Laravel4-SirTrevorJs
*
* @link https://github.com/caouecs/Laravel4-SirTrevorJS
*/
namespace Caouecs\Sirtrevorjs\Converter;
/**
* Sound for Sir Trevor Js
*
* @package Caouecs\Sirtrevorjs\Converter
*/
class SoundConverter
{
/**
* List of types for sound
*
* @access protected
... |
Include version from package.json in build output file name | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
compress: {
main: {
options: {
archive: 'GeocachingUtils_<%= pkg.version %>.zip'
},
files: [
{
src: ['source/**'],
dest: ''
}
... | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
compress: {
main: {
options: {
archive: 'Geocaching_Utils.zip'
},
files: [
{
src: ['source/**'],
dest: ''
}
]
}
... |
Allow for comments in the sql file that do not start the line. | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... |
Add temp button in candidate section | import React from 'react'
import './candidatesection.css'
import { Route } from 'react-router-dom'
import { Button } from 'semantic-ui-react'
export default class CandidateSection extends React.Component {
constructor () {
super()
this.state = { data : [] }
}
componentDidMount () {
this.loadAllCandi... | import React from 'react'
import './candidatesection.css'
export default class CandidateSection extends React.Component {
constructor () {
super()
this.state = { data : [] }
}
componentDidMount () {
this.loadAllCandidate()
}
loadAllCandidate () {
}
render () {
return (
<div clas... |
Add description usage for ExpireDate class | <?php
/**
* Description of Date
*
* Usage:
* <code>
* $expire_date = new Merchant_Billing_ExpiryDate(5, 2010);
* </code>
* Public methods:
* + is_expired() returns a boolean about expiration of given data
* + expiration() returns expiration date as Unix timestamp
*
*
*
* @package Aktive Merchant
* @author... | <?php
/**
* Description of Date
*
* @package Aktive Merchant
* @author Andreas Kollaros
* @license http://www.opensource.org/licenses/mit-license.php
*/
class Merchant_Billing_ExpiryDate {
private $year;
private $month;
public function __construct($month, $year) {
$this->year = $year;
$this->mon... |
Remove person from organization serializer | from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
... | from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
... |
Use strict was causing invalid javascript on bundling | this.ckan.module('collapsible', function($) {
return {
initialize: function() {
this.activateCollapsibles()
},
activateCollapsibles: function() {
var elements = $('.collapsible');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function () {
... | 'use strict';
this.ckan.module('collapsible', function($) {
return {
initialize: function() {
this.activateCollapsibles()
},
activateCollapsibles: function() {
var elements = $('.collapsible');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', ... |
Add flickr api key and secret options | export default {
authToken: process.env.AUTH_TOKEN || 'secret',
env: process.env.NODE_ENV,
flickr: {
apiKey: process.env.FLICKR_API_KEY || '123abc',
secret: process.env.FLICKR_SECRET || '123abc'
},
host: process.env.HOST || 'localhost',
github: {
apiUrl: 'https://api.github.com',
username: p... | export default {
authToken: process.env.AUTH_TOKEN || 'secret',
env: process.env.NODE_ENV,
host: process.env.HOST || 'localhost',
github: {
apiUrl: 'https://api.github.com',
username: process.env.GITHUB_USERNAME || 'username',
accessToken: process.env.GITHUB_ACCESS_TOKEN || '123abc'
},
jobs: {
... |
Fix for high level registration test.
* Exported single components now have compiled render function,
not a template property. | import Vue from 'vue'
import {
default as VueMdl,
MdlCheckbox,
MdlBadge,
components,
directives
} from '../../../src/vue-mdl'
describe('Register', () => {
it('exports single components', () => {
MdlCheckbox.should.exist.and.be.an.Object
MdlCheckbox.should.have.property('render')
})
it('exports... | import Vue from 'vue'
import {
default as VueMdl,
MdlCheckbox,
MdlBadge,
components,
directives
} from '../../../src/vue-mdl'
describe('Register', () => {
it('exports single components', () => {
MdlCheckbox.should.exist.and.be.an.Object
MdlCheckbox.should.have.property('template')
})
it('expor... |
Add simplified factory for channel | package org.realityforge.replicant.client;
import arez.Arez;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* The Channel object contains the address of the channel and the optional filter for... | package org.realityforge.replicant.client;
import arez.Arez;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* The Channel object contains the address of the channel and the optional filter for... |
Make logs directory, simplify log to goat-yyyy-mm-dd.log | package goat
import (
"bufio"
"fmt"
"log"
"os"
"time"
)
func LogMng(doneChan chan bool, logChan chan string) {
// Create log directory and file, and pull current date to add to logfile name
now := time.Now()
os.Mkdir("logs", os.ModeDir|os.ModePerm)
logFile, err := os.Create(fmt.Sprintf("logs/goat-%d-%d-%d.lo... | package goat
import (
"bufio"
"fmt"
"log"
"os"
"time"
)
func LogMng(doneChan chan bool, logChan chan string) {
// create log file and pull current time to add to logfile name
currentTime := time.Now().String()
logFile, err := os.Create("GoatLog" + currentTime + ".log")
if err != nil {
fmt.Println(err)
}
... |
Use nose's test generator function | #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Test tvnamer's filename parser
"""
import os
import sys
from copy import copy
import unittest
sys.path.append(os.path... | #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Test tvnamer's filename parser
"""
import os
import sys
import unittest
sys.path.append(os.path.join(os.path.abspath(... |
Revert "Removed the "enabled" property since we're doing real deletes now"
This reverts commit 5309419656a4b33115c44693a9941553359dce1a. | package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support;
import java.util.Date;
import ca.corefacility.bioinformatics.irida.model.IridaThing;
/**
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
public class IdentifiableTestEntity implements IridaThing, Comparable<Identifi... | package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support;
import java.util.Date;
import ca.corefacility.bioinformatics.irida.model.IridaThing;
/**
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
public class IdentifiableTestEntity implements IridaThing, Comparable<Identifi... |
Make this derive from the correct type | import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
help = "run a (local, debug) server"
def add_arguments(self, parser):
parser.add_argument(
'-p',
'--port',
... | import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(object):
help = "run a (local, debug) server"
def add_arguments(self, parser):
parser.add_argument(
'-p',
'--port',
ty... |
Remove unintentional commas from argument list | #!/usr/bin/env python
"""Create a shop with article and order sequences.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
fr... | #!/usr/bin/env python
"""Create a shop with article and order sequences.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
fr... |
Update now returns the account info | var Account = require('../../app/models/account');
exports.update = function (req, res) {
Account.findById(req.params.id, function (err, account) {
if (!account)
return next(new Error('Could not load Document'));
else {
if (req.body.foreName) {
account.foreNa... | var Account = require('../../app/models/account');
exports.update = function (req, res) {
Account.findById(req.params.id, function (err, account) {
if (!account)
return next(new Error('Could not load Document'));
else {
if (req.body.foreName) {
account.foreNa... |
Add missing spotbugs annotations in xpath-impl
Somehow we have been missing this annotation import, fix that up.
Change-Id: Ib39814bca421b6518f7e1bb0e8c8ec38350747fb
Signed-off-by: Robert Varga <91ae5aa8c7a9f7e57b701db766e23e544aaa6ae9@pantheon.tech> | /*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
import org... | /*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
import org... |
Make the httpreason template tag return empty string on *any* exception. | from django import template
from django.template.defaultfilters import stringfilter, yesno
from django.http.response import REASON_PHRASES
register = template.Library()
@register.filter
@stringfilter
def truthy(value, arg=None):
"""Wraps django's yesno filter to allow for JavaScript-style true or false string val... | from django import template
from django.template.defaultfilters import stringfilter, yesno
from django.http.response import REASON_PHRASES
register = template.Library()
@register.filter
@stringfilter
def truthy(value, arg=None):
"""Wraps django's yesno filter to allow for JavaScript-style true or false string val... |
Update DotEnv registration to version 4 | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Bootstrap;
use Dotenv\Dotenv;... | <?php
declare(strict_types=1);
/**
* This file is part of Laravel Zero.
*
* (c) Nuno Maduro <enunomaduro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LaravelZero\Framework\Bootstrap;
use Dotenv\Dotenv;... |
Remove reference to container variable | <?php
namespace Noback\PHPUnitTestServiceContainer\PHPUnit;
use Noback\PHPUnitTestServiceContainer\ServiceContainer;
use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface;
use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface;
/**
* Extend from this test case to make use of a service container ... | <?php
namespace Noback\PHPUnitTestServiceContainer\PHPUnit;
use Noback\PHPUnitTestServiceContainer\ServiceContainer;
use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface;
use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface;
/**
* Extend from this test case to make use of a service container ... |
Make development status be Alpha. | #!/usr/bin/env python
from distutils.core import setup
import dougrain
base_url = "http://github.com/wharris/dougrain/"
setup(
name = 'dougrain',
version = dougrain.__version__,
description = 'HAL JSON parser and generator',
author = 'Will Harris',
author_email = 'will@greatlibrary.net',
url ... | #!/usr/bin/env python
from distutils.core import setup
import dougrain
base_url = "http://github.com/wharris/dougrain/"
setup(
name = 'dougrain',
version = dougrain.__version__,
description = 'HAL JSON parser and generator',
author = 'Will Harris',
author_email = 'will@greatlibrary.net',
url ... |
Use ES5 functions instead of arrow functions | var data = require('./data');
var accounting = require('accounting');
var CurrencyFormatter = function() {
this.defaultCurrency = {
symbol: '',
thousandsSeparator: ',',
decimalSeparator: '.',
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: false,
decimalDigits: 2
}
}
CurrencyFormatter.pro... | var data = require('./data');
var accounting = require('accounting');
var CurrencyFormatter = function() {
this.defaultCurrency = {
symbol: '',
thousandsSeparator: ',',
decimalSeparator: '.',
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: false,
decimalDigits: 2
}
}
CurrencyFormatter.pro... |
Update code to follow new Eslint rules, eslint-plugin-jsx-a11y | import React from 'react';
import Navbar from '../Navbar/NavbarComponent';
import Footer from '../Footer/FooterContainer';
import './App.scss';
export default class App extends React.Component {
static propTypes = {
children: React.PropTypes.object.isRequired,
viewer: React.PropTypes.object.isRequired
};
... | import React from 'react';
import Navbar from '../Navbar/NavbarComponent';
import Footer from '../Footer/FooterContainer';
import './App.scss';
export default class App extends React.Component {
static propTypes = {
children: React.PropTypes.object.isRequired,
viewer: React.PropTypes.object.isRequired
};
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.