text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Fix widget url generation when missing apikey and authtoken | var _ = require('underscore');
var Model = require('../../core/model');
/**
* This model is used for getting the total amount of values
* from the category.
*
*/
module.exports = Model.extend({
defaults: {
url: '',
totalCount: 0,
categoriesCount: 0
},
url: function () {
var url = this.get... | var _ = require('underscore');
var Model = require('../../core/model');
/**
* This model is used for getting the total amount of values
* from the category.
*
*/
module.exports = Model.extend({
defaults: {
url: '',
totalCount: 0,
categoriesCount: 0
},
url: function () {
var url = this.get... |
Make valid schema types and validator error type configurable | var util = require('util');
/**
* @param {mongoose.Schema} schema
* @param {?Object=} options
*/
module.exports = exports = function constantPlugin(schema, options) {
options = options || {};
options.ValidSchemaTypes = options.ValidSchemaTypes || ['String', 'Number', 'Date', 'ObjectID'];
options.ErrorT... | /**
* @param {mongoose.Schema} schema
* @param {?Object=} options
*/
module.exports = exports = function constantPlugin(schema, options) {
var validSchemaTypes = ['String', 'Number', 'Date', 'ObjectID'];
function validateSchemaType(path, schemaType) {
if (!~validSchemaTypes.indexOf(schemaType.instan... |
Comment out active round check in round:sStart | <?php
namespace OpenDominion\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;
class RoundStartCommand extends Command
{
protected $signature = 'round:start';
protected $description = 'Starts a new round (dev only)';
... | <?php
namespace OpenDominion\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
use OpenDominion\Models\Round;
use OpenDominion\Models\RoundLeague;
class RoundStartCommand extends Command
{
protected $signature = 'round:start';
protected $description = 'Starts a new round (dev only)';
... |
Check search text before submitting post search event. | import React from 'react';
import ReactDOM from 'react-dom';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handl... | import React from 'react';
import ReactDOM from 'react-dom';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handl... |
Use logApplicationPackage so users might get a notification | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content.cluster;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
import com.yahoo.vespa.model.content.Res... | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content.cluster;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
import com.yahoo.vespa.model.content.Res... |
Fix bug in multiple input fields interaction for media section | define('media-input', ['jquery', 'z'], function($, z) {
function createInput($section) {
$section.append($('<input>', {
type: 'url',
placeholder: $section.data('placeholder'),
pattern: 'https?://.*'
}));
}
z.page.on('loaded', function() {
$... | define('media-input', ['jquery', 'z'], function($, z) {
function createInput($section) {
$section.append($('<input>', {
type: 'url',
placeholder: $section.data('placeholder'),
pattern: 'https?://.*'
}));
}
z.page.on('loaded', function() {
$... |
Update OpenJDK version to support both 8 and 9. | import re
from versions.software.utils import get_command_stderr, get_soup, \
get_text_between
def name():
"""Return the precise name for the software."""
return 'Zulu OpenJDK'
def installed_version():
"""Return the installed version of the jdk, or None if not installed."""
try:
version... | import re
from versions.software.utils import get_command_stderr, get_soup, \
get_text_between
def name():
"""Return the precise name for the software."""
return 'Zulu OpenJDK'
def installed_version():
"""Return the installed version of the jdk, or None if not installed."""
try:
version... |
Disable auto-update until next season | 'use strict';
function config() {
const periodFormat = '{0}-{1}';
const firstHandledYear = 2000;
const lastHandledPeriod = 2021;
const currentPeriod = periodFormat.replace('{0}', lastHandledPeriod).replace('{1}', lastHandledPeriod + 1);
const availablesPeriod = [];
for (let i = last... | 'use strict';
function config() {
const periodFormat = '{0}-{1}';
const firstHandledYear = 2000;
const lastHandledPeriod = 2021;
const currentPeriod = periodFormat.replace('{0}', lastHandledPeriod).replace('{1}', lastHandledPeriod + 1);
const availablesPeriod = [];
for (let i = last... |
Remove unused defaultParams from state | import React from 'react';
import classnames from 'classnames';
import Store from './Store';
import ActionCreator from './ActionCreator';
import urlUtil from './urlUtil';
const Url = React.createClass({
propTypes: {
pathname: React.PropTypes.string,
query: React.PropTypes.object,
children: React.PropTyp... | import React from 'react';
import classnames from 'classnames';
import Store from './Store';
import ActionCreator from './ActionCreator';
import urlUtil from './urlUtil';
const Url = React.createClass({
propTypes: {
pathname: React.PropTypes.string,
query: React.PropTypes.object,
children: React.PropTyp... |
Use partial for duplicated partial string | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
... | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
... |
Fix plugin import for astropy 2.x | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
import os
try:
from astropy.tests.plugins.displa... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
import os
try:
from astropy.tests.plugins.displa... |
Stop using reserved JavaScript keyword `package` | 'use babel';
export function loadFile(path) {
return window.nvim.command(`e ${path}`);
}
export async function loadFileGetBufferContents(path) {
await loadFile(path);
const buffer = await window.nvim.getCurrentBuffer();
const lineCount = await buffer.lineCount();
return await buffer.getLineSlice(... | 'use babel';
export function loadFile(path) {
return window.nvim.command(`e ${path}`);
}
export async function loadFileGetBufferContents(path) {
await loadFile(path);
const buffer = await window.nvim.getCurrentBuffer();
const lineCount = await buffer.lineCount();
return await buffer.getLineSlice(... |
Add user context to Raven client, if the user is logged in | <?php
require_once 'Zend/Log/Writer/Abstract.php';
/**
* Publish SilverStripe errors and warnings to Sentry using the Raven client.
*/
class SentryLogger extends Zend_Log_Writer_Abstract {
private $sentry;
private $logLevels = array(
'NOTICE' => Raven_Client::INFO,
'WARN' => Raven_... | <?php
require_once 'Zend/Log/Writer/Abstract.php';
/**
* Publish SilverStripe errors and warnings to Sentry using the Raven client.
*/
class SentryLogger extends Zend_Log_Writer_Abstract {
private $sentry;
private $logLevels = array(
'NOTICE' => Raven_Client::INFO,
'WARN' => Raven_... |
Add allowed_system as a class variable | import platform
class OSXDodger(object):
allowed_version = "10.6.1"
allowed_system = "darwin"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_i... | import platform
class OSXDodger(object):
allowed_version = "10.12.1"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_is_macintosh()
def select... |
Set up options structure, require dateSlug | /*
* grunt-deploy
* https://github.com/kevinschaul/strib-deploy
*
* Copyright (c) 2013 Kevin Schaul
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
... | /*
* grunt-deploy
* https://github.com/kevinschaul/strib-deploy
*
* Copyright (c) 2013 Kevin Schaul
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
... |
Update state when commands context changed | var Model = codebox.require("hr.model");
var Collection = codebox.require("hr.collection");
var _ = codebox.require("hr.utils");
var commands = codebox.require("core/commands");
var MenuItem = Model.extend({
defaults: {
type: "entry",
caption: "",
command: "",
items: [],
arg... | var Model = codebox.require("hr.model");
var Collection = codebox.require("hr.collection");
var _ = codebox.require("hr.utils");
var commands = codebox.require("core/commands");
var MenuItem = Model.extend({
defaults: {
type: "entry",
caption: "",
command: "",
items: [],
arg... |
Change to use logging and set log level to INFO |
import os
import logging
from decouple import config
FOLDER = 'public'
FOLDER = FOLDER.strip('/')
logging.basicConfig(level=logging.INFO)
def deploy():
import boto
from boto.s3.connection import S3Connection
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET... |
import os
import logging
from decouple import config
FOLDER = 'public'
FOLDER = FOLDER.strip('/')
log = logging.getLogger('deploy')
def deploy():
import boto
from boto.s3.connection import S3Connection
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCES... |
Add 'rc' as prereleaseName in grunt bump | module.exports = function(grunt) {
grunt.initConfig({
watch: {
all: {
options: {
livereload: true
},
files: [
'*.html',
'examples/**/*.html',
'test/*.js',
... | module.exports = function(grunt) {
grunt.initConfig({
watch: {
all: {
options: {
livereload: true
},
files: [
'*.html',
'examples/**/*.html',
'test/*.js',
... |
Allow .js extension for JSX files | module.exports = {
parser: 'babel-eslint',
extends: [
'airbnb',
'plugin:ava/recommended',
],
plugins: [
'import',
'ava',
],
rules: {
indent: ['error', 4, {
SwitchCase: 1,
MemberExpression: 1,
VariableDeclarator: 1,
... | module.exports = {
parser: 'babel-eslint',
extends: [
'airbnb',
'plugin:ava/recommended',
],
plugins: [
'import',
'ava',
],
rules: {
indent: ['error', 4, {
SwitchCase: 1,
MemberExpression: 1,
VariableDeclarator: 1,
... |
Fix issue when use text search and count | /*
** Module dependencies
*/
var mongoose = require('mongoose');
var Record = mongoose.model('Record');
var async = require('async');
exports.search = function(req, res, next) {
function buildQuery() {
var query = Record.find().where('metadata.type').in(['dataset', 'series']);
if (req.query.q && re... | /*
** Module dependencies
*/
var mongoose = require('mongoose');
var Record = mongoose.model('Record');
var async = require('async');
exports.search = function(req, res, next) {
function buildQuery() {
var query = Record.find().where('metadata.type').in(['dataset', 'series']);
if (req.query.q && re... |
Include phones in default org object | import React, { Component } from 'react'
import { fetchOrganization } from '../../core/firebaseRestAPI'
import { authenticate } from '../../lib/session'
import { uuid } from '../../lib/uuid'
import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import OrganizationEdit from '../..... | import React, { Component } from 'react'
import { fetchOrganization } from '../../core/firebaseRestAPI'
import { authenticate } from '../../lib/session'
import { uuid } from '../../lib/uuid'
import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import OrganizationEdit from '../..... |
Fix "Call to a member function close() on null" exception | <?php
namespace VladimirYuldashev\LaravelQueueRabbitMQ;
use Illuminate\Queue\QueueManager;
use Illuminate\Support\ServiceProvider;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\... | <?php
namespace VladimirYuldashev\LaravelQueueRabbitMQ;
use Illuminate\Queue\QueueManager;
use Illuminate\Support\ServiceProvider;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnectorSSL;
class LaravelQueueRabbitM... |
Change error status with config problems to critical | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... |
Fix missing backslash on exception | <?php
namespace Stevebauman\Maintenance\Services;
use Stevebauman\Maintenance\Models\Note;
/**
* Class NoteService
* @package Stevebauman\Maintenance\Services
*/
class NoteService extends BaseModelService
{
/**
* @var SentryService
*/
protected $sentry;
/**
* Constructor.
*
*... | <?php
namespace Stevebauman\Maintenance\Services;
use Stevebauman\Maintenance\Models\Note;
/**
* Class NoteService
* @package Stevebauman\Maintenance\Services
*/
class NoteService extends BaseModelService
{
/**
* @var SentryService
*/
protected $sentry;
/**
* @param Note $note
* @... |
Use arrow functions whenver possible | (function () {
function initTwinklingStars() {
const devicePixelRatio = Math.min(window.devicePixelRatio, 3) || 1;
particlesJS('stars', {
particles: {
number: {
value: 180,
density: {
enable: true,
... | (function () {
function initTwinklingStars() {
const devicePixelRatio = Math.min(window.devicePixelRatio, 3) || 1;
particlesJS('stars', {
particles: {
number: {
value: 180,
density: {
enable: true,
... |
Use Play's ok() for chunked responses | package controllers;
import org.sagebionetworks.bridge.models.UserSession;
import org.sagebionetworks.bridge.services.backfill.BackfillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.spr... | package controllers;
import org.sagebionetworks.bridge.models.UserSession;
import org.sagebionetworks.bridge.services.backfill.BackfillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.spr... |
Use new with gutil plugin error. | /* jshint node:true */
'use strict';
var csso = require('csso'),
gutil = require('gulp-util'),
transform = require('stream').Transform,
bufferstreams = require('bufferstreams'),
PLUGIN_NAME = 'gulp-csso';
function cssoTransform(optimise) {
// Returns a callback t... | /* jshint node:true */
'use strict';
var csso = require('csso'),
gutil = require('gulp-util'),
transform = require('stream').Transform,
bufferstreams = require('bufferstreams'),
PLUGIN_NAME = 'gulp-csso';
function cssoTransform(optimise) {
// Returns a callback t... |
Use unicode strings for 'no javascript' just so it's consistent with browser-retrieved values | class FingerprintAgent(object):
def __init__(self, request):
self.request = request
def detect_server_whorls(self):
vars = {}
# get cookie enabled
if self.request.cookies:
vars['cookie_enabled'] = 'Yes'
else:
vars['cookie_enabled'] = 'No'
... | class FingerprintAgent(object):
def __init__(self, request):
self.request = request
def detect_server_whorls(self):
vars = {}
# get cookie enabled
if self.request.cookies:
vars['cookie_enabled'] = 'Yes'
else:
vars['cookie_enabled'] = 'No'
... |
Update status color based on response code | <?php
/**
* Class Sheep_Debug_Block_Controller
*
* @category Sheep
* @package Sheep_Debug
* @license Copyright: Pirate Sheep, 2016, All Rights reserved.
* @link https://piratesheep.com
*/
class Sheep_Debug_Block_Controller extends Sheep_Debug_Block_Panel
{
public function getSubTitle()
... | <?php
/**
* Class Sheep_Debug_Block_Controller
*
* @category Sheep
* @package Sheep_Debug
* @license Copyright: Pirate Sheep, 2016, All Rights reserved.
* @link https://piratesheep.com
*/
class Sheep_Debug_Block_Controller extends Sheep_Debug_Block_Panel
{
public function getSubTitle()
... |
Add changes missing from commit a3a01cd | <?php
require('ErrorsContainer.php');
class AddSegmentsErrors extends ErrorsContainer {
public function __constructor() {
$this->errors = [
'missingCategory' => false,
'categoryInvalidFormat' => false,
'missingAlbum' => false,
'm... | <?php
require('ErrorsContainer.php');
class AddSegmentsErrors extends ErrorsContainer {
public function __constructor() {
$this->errors = [
'missingAlbum' => false,
'missingAuthor' => false,
'missingName' => false,
'missingAdNumb... |
Allow user to type :) | import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInit... | import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInit... |
Add missing trailing commas in new webpack config | /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarget:... | /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarget:... |
Move setting VCAP_SERVICES out of fixture
This was inconsistent with the source data for the fixture being
overidden in some of the tests. We only need to set it in the env
once, so it makes sense to just put the code there. | import json
import os
import pytest
from app.cloudfoundry_config import (
extract_cloudfoundry_config,
set_config_env_vars,
)
@pytest.fixture
def cloudfoundry_config():
return {
'postgres': [{
'credentials': {
'uri': 'postgres uri'
}
}],
'u... | import json
import os
import pytest
from app.cloudfoundry_config import (
extract_cloudfoundry_config,
set_config_env_vars,
)
@pytest.fixture
def cloudfoundry_config():
return {
'postgres': [{
'credentials': {
'uri': 'postgres uri'
}
}],
'u... |
Disable echo of sql alchemy | import sqlalchemy as sa
engine = None
metadata = None
task_table = None
metadata_table = None
def setup_db(db_url):
global engine, metadata
engine = sa.create_engine(db_url, echo=False)
metadata = sa.MetaData(engine)
make_task_table()
metadata.create_all(engine)
def make_task_table():
globa... | import sqlalchemy as sa
engine = None
metadata = None
task_table = None
metadata_table = None
def setup_db(db_url):
global engine, metadata
engine = sa.create_engine(db_url, echo=True)
metadata = sa.MetaData(engine)
make_task_table()
metadata.create_all(engine)
def make_task_table():
global... |
Fix error when showing content app in media section | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
if (currentVariant && currentVariant.language) {
... | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
if (currentVariant.language) {
vm.culture =... |
Add compare function to lang Field | <?php
namespace Splash\Tests\Tools\Fields;
/**
* @abstract Language Field : ISO Language Code
*
* @example en_US, fr_FR, fr_BE
*
* @see ISO 639-1 : http://www.iso.org/iso/language_codes
*/
class Oolang extends Oovarchar
{
//=====================================================================... | <?php
namespace Splash\Tests\Tools\Fields;
/**
* @abstract Language Field : ISO Language Code
*
* @example en_US, fr_FR, fr_BE
*
* @see ISO 639-1 : http://www.iso.org/iso/language_codes
*/
class Oolang
{
//==============================================================================
// ... |
Validate data, and use a different password creation method | <?php
namespace Korobi\WebBundle\Security;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider;
use Symfony\Component\Security\Core\User\UserInterface;
class UserProvider extends FOSUBUserProvider {
public function loadUserByOAuthUserRe... | <?php
namespace Korobi\WebBundle\Security;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider;
use Symfony\Component\Security\Core\User\UserInterface;
class UserProvider extends FOSUBUserProvider {
public function loadUserByOAuthUserRe... |
Add image url to item model. |
package com.uwetrottmann.shopr.algorithm.model;
import java.math.BigDecimal;
/**
* Represents a item (e.g. clothing item), or one case in the case-base.
*/
public class Item {
private int id;
private String name;
private BigDecimal price;
private String image_url;
private int shop_id;
... |
package com.uwetrottmann.shopr.algorithm.model;
import java.math.BigDecimal;
/**
* Represents a item (e.g. clothing item), or one case in the case-base.
*/
public class Item {
private int id;
private String name;
private BigDecimal price;
private int shop_id;
private Attributes attrs;
... |
Stop disabling update button while updating | import React from 'react';
import { formatRelative } from 'date-fns';
import './Projects.css';
const Projects = ({ projects, toggle, update }) => {
return (
<ul
className="ToggleProjects__list list-unstyled"
>
{projects.map(project => (
<li
key={project.id}
className="... | import React from 'react';
import { formatRelative } from 'date-fns';
import './Projects.css';
const Projects = ({ projects, toggle, update }) => {
return (
<ul
className="ToggleProjects__list list-unstyled"
>
{projects.map(project => (
<li
key={project.id}
className="... |
Copy built package to QA Folder | module.exports = function(grunt) {
grunt.initConfig({
copyPackageTo: "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package",
movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build",
jobName: process.... | module.exports = function(grunt) {
grunt.initConfig({
movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build",
jobName: process.env["JOB_NAME"] || "local",
buildNumber: process.env["BUILD_NUMBER"] || "non-ci",
d... |
Set middleware function to be definable | 'use strict';
module.exports = function(gulp, $, config, _) {
var proxyTarget = _.get(config, 'proxy.url', config.consts.proxy.url);
var proxyPrefixes = _.get(config, 'proxy.prefixes', config.consts.proxy.prefixes);
var proxy = $.httpProxy.createProxyServer({
target: proxyTarget
});
function isProxiedPrefix... | 'use strict';
module.exports = function(gulp, $, config, _) {
var proxyTarget = _.get(config, 'proxy.url', config.consts.proxy.url);
var proxyPrefixes = _.get(config, 'proxy.prefixes', config.consts.proxy.prefixes);
var proxy = $.httpProxy.createProxyServer({
target: proxyTarget
});
function isProxiedPrefix... |
Make array lib that much more awesome | <?php
namespace Lib;
class Arr
{
public static function set(string $key, $value, array $container = []): array
{
list($keys, $valueKey) = static::breakKey($key);
$end = &static::seekEnd($keys, $container);
$end[$valueKey] = $value;
return $container;
}
private static f... | <?php
namespace Lib;
class Arr
{
public static function set(string $key, $value, array $container = []): array
{
$keys = explode('.', $key);
$valueKey = array_pop($keys);
return static::delve(function (array &$end, array &$container) use ($valueKey, $value) {
$end[$valueKey... |
Update setup to include new scripts | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurfer-libs
from distutils.core import setup
setup(name='fsurfer-libs',
version='PKG_VERSION',
description='Python module to help create freesurfer workflows',
author='Suchandra Thapa',
... | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurfer-libs
from distutils.core import setup
setup(name='fsurfer-libs',
version='PKG_VERSION',
description='Python module to help create freesurfer workflows',
author='Suchandra Thapa',
... |
Add the missing return statement
Simply return the 'X-RateLimit-Remaining' as expected. | <?php
namespace Github\HttpClient\Message;
use Guzzle\Http\Message\Response;
use Github\Exception\ApiLimitExceedException;
class ResponseMediator
{
public static function getContent(Response $response)
{
$body = $response->getBody(true);
$content = json_decode($body, true);
if (JS... | <?php
namespace Github\HttpClient\Message;
use Guzzle\Http\Message\Response;
use Github\Exception\ApiLimitExceedException;
class ResponseMediator
{
public static function getContent(Response $response)
{
$body = $response->getBody(true);
$content = json_decode($body, true);
if (JS... |
Make maximum number of words a parameter | import os
from operator import itemgetter
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitline... | import os
from operator import itemgetter
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitline... |
Test failed because these was no expected-output file, but always printed
to stdout. Repaired by not printing at all except in verbose mode.
Made the test about 6x faster -- envelope analysis showed it took time
proportional to the square of the # of tasks. Now it's linear. | # Very rudimentary test of threading module
# Create a bunch of threads, let each do some work, wait until all are done
from test_support import verbose
import random
import threading
import time
# This takes about n/3 seconds to run (about n/3 clumps of tasks, times
# about 1 second per clump).
numtasks = 10
# no ... | # Very rudimentary test of threading module
# Create a bunch of threads, let each do some work, wait until all are done
from test_support import verbose
import random
import threading
import time
numtasks = 10
# no more than 3 of the 10 can run at once
sema = threading.BoundedSemaphore(value=3)
mutex = threading.RL... |
Use six.text_type for python3 compat | import decimal
import msgpack
from dateutil.parser import parse
from django.utils.six import text_type
from rest_framework.parsers import BaseParser
from rest_framework.exceptions import ParseError
class MessagePackDecoder(object):
def decode(self, obj):
if '__class__' in obj:
decode_func =... | import decimal
import msgpack
from dateutil.parser import parse
from rest_framework.parsers import BaseParser
from rest_framework.exceptions import ParseError
class MessagePackDecoder(object):
def decode(self, obj):
if '__class__' in obj:
decode_func = getattr(self, 'decode_%s' % obj['__clas... |
Return migrations helper by reference | <?php
/*
* This file is part of the Active Collab DatabaseMigrations project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\DatabaseMigrations\Command;
use ActiveCollab\DatabaseMigrations\MigrationsInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfon... | <?php
/*
* This file is part of the Active Collab DatabaseMigrations project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
namespace ActiveCollab\DatabaseMigrations\Command;
use ActiveCollab\DatabaseMigrations\MigrationsInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfon... |
Upgrade to a newer gevent for OSX Yosemity compat
See https://github.com/gevent/gevent/issues/656 | #!/usr/bin/python
from setuptools import setup
setup(name="catsnap",
version="6.0.0",
description="catalog and store images",
author="Erin Call",
author_email="hello@erincall.com",
url="https://github.com/ErinCall/",
packages=['catsnap',
'catsnap.document',
... | #!/usr/bin/python
from setuptools import setup
setup(name="catsnap",
version="6.0.0",
description="catalog and store images",
author="Erin Call",
author_email="hello@erincall.com",
url="https://github.com/ErinCall/",
packages=['catsnap',
'catsnap.document',
... |
Fix forgotten ionic beta.2 changes | module.exports = {
proxies: null,
paths: {
html : {
src: ['app/**/*.html'],
dest: "www/build"
},
sass: {
src: ['app/theme/app.+(ios|md).scss'],
dest: 'www/build/css',
include: [
'node_modules/ionic-angular',
... | module.exports = {
proxies: null,
paths: {
html : {
src: ['app/**/*.html'],
dest: "www/build"
},
sass: {
src: ['app/theme/app.+(ios|md).scss'],
dest: 'www/build/css',
include: [
'node_modules/ionic-framework',
... |
Use new scheme for npmcdn | var loaders = [
{ test: /\.json$/, loader: "json-loader" },
];
module.exports = [
{// Notebook extension
entry: './src/extension.js',
output: {
filename: 'extension.js',
path: '../pythreejs/static',
libraryTarget: 'amd'
}
},
{// bqplot bundle ... | var loaders = [
{ test: /\.json$/, loader: "json-loader" },
];
module.exports = [
{// Notebook extension
entry: './src/extension.js',
output: {
filename: 'extension.js',
path: '../pythreejs/static',
libraryTarget: 'amd'
}
},
{// bqplot bundle ... |
Use the correct server for the Hitbox.tv preview image | <?php
class HitboxApi {
private static $baseUrl = 'https://www.hitbox.tv/api/';
public function getStreamsByGame( $game ){
$channelList = array();
// This is a temporary solution until Hitbox enables filter by game
$channels = $this->loadUrl( self::$baseUrl . 'media/live/list?liveonly=... | <?php
class HitboxApi {
private static $baseUrl = 'https://www.hitbox.tv/api/';
public function getStreamsByGame( $game ){
$channelList = array();
// This is a temporary solution until Hitbox enables filter by game
$channels = $this->loadUrl( self::$baseUrl . 'media/live/list?liveonly=... |
Add list of allowed elements to picture child def | <?php
class HTMLPurifier_ChildDef_Picture extends HTMLPurifier_ChildDef
{
public $type = 'picture';
public $elements = array(
'img' => true,
'source' => true,
);
/**
* @param array $children
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
... | <?php
class HTMLPurifier_ChildDef_Picture extends HTMLPurifier_ChildDef
{
public $type = 'picture';
/**
* @param array $children
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return array
*/
public function validateChildren($children, $config, $con... |
Throw ForbiddenException on unauthenticated request | <?php
namespace AnduFratu\Jwt;
\App::uses('BaseAuthenticate', 'Controller/Component/Auth');
class JwtAuthenticate extends \BaseAuthenticate
{
private $defaultSettings = array(
'param' => 'token',
'key' => 'EMPTY_KEY',
);
public function __construct(\ComponentCollection $collection, $setti... | <?php
namespace AnduFratu\Jwt;
\App::uses('BaseAuthenticate', 'Controller/Component/Auth');
class JwtAuthenticate extends \BaseAuthenticate
{
private $defaultSettings = array(
'param' => 'token',
'key' => 'EMPTY_KEY',
);
public function __construct(\ComponentCollection $collection, $setti... |
Return index.html in root and transform /status results | from flask import jsonify
from . import app
import mapper
import utils
from predict import predictor
@app.route("/", methods=["GET"])
def index():
return app.send_static_file("index.html")
@app.route("/build", methods=["POST"])
def build_model():
predictor.preprocess_airports()
if not predictor.model:
... | from flask import jsonify
from . import app
import mapper
import utils
from predict import predictor
@app.route("/", methods=["GET"])
def index():
firebase_dump = mapper.get_dump_firebase()
response = firebase_dump.get_all()
response = response or {}
return jsonify(response)
@app.route("/build", met... |
Allow WebbitSocket.on{error,close,open} to be hooked up. | function WebbitSocket(path, target) {
var self = this;
var ws = new WebSocket('ws://' + document.location.host + path);
ws.onclose = function() {
target.onclose && target.onclose();
self.onclose && self.onclose();
};
ws.onerror = function() {
target.onerror && target.onerror(... | function WebbitSocket(path, target) {
var self = this;
var ws = new WebSocket('ws://' + document.location.host + path);
ws.onclose = function() {
target.onclose && target.onclose();
};
ws.onmessage = function(e) {
var msg = JSON.parse(e.data);
if (msg.exports) {
m... |
Change class definitions from old style to new style | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import print_function
from __future__ import unicode_literals
from pytablewriter._function import convert_idx_to_alphabet
import pytest
class Test_convert_idx_to_alphabet(object):
@pytest.mark.parametrize(["value... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import print_function
from __future__ import unicode_literals
from pytablewriter._function import convert_idx_to_alphabet
import pytest
class Test_convert_idx_to_alphabet:
@pytest.mark.parametrize(["value", "expe... |
Add correct response code for error
404 not 200 c: | <?php
require $_SERVER['DOCUMENT_ROOT'] . '/../backend/outputObject.php';
require $_SERVER['DOCUMENT_ROOT'] . '/../backend/databaseOptions.php';
$id = $_GET['id'];
$output = new JsonOutput('v2');
if ($id != '') {
// Get dog by its ID
$dog = getSpecificDog($id);
$dogA... | <?php
require $_SERVER['DOCUMENT_ROOT'] . '/../backend/outputObject.php';
require $_SERVER['DOCUMENT_ROOT'] . '/../backend/databaseOptions.php';
$id = $_GET['id'];
$output = new JsonOutput('v2');
if ($id != '') {
// Get dog by its ID
$dog = getSpecificDog($id);
$dogA... |
Print detected content encoding info only if it's actually been detected | import re
import requests
from bs4 import BeautifulSoup as bs
from jfr_playoff.logger import PlayoffLogger
class RemoteUrl:
url_cache = {}
@classmethod
def fetch_raw(cls, url):
PlayoffLogger.get('remote').info(
'fetching content for: %s', url)
if url not in cls.url_cache:
... | import re
import requests
from bs4 import BeautifulSoup as bs
from jfr_playoff.logger import PlayoffLogger
class RemoteUrl:
url_cache = {}
@classmethod
def fetch_raw(cls, url):
PlayoffLogger.get('remote').info(
'fetching content for: %s', url)
if url not in cls.url_cache:
... |
Make static js methods actually work. | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.core',
name: 'Static',
extends: 'foam.core.AbstractMethod',
documentation: 'An Axiom for defining static methods.',
methods: [
function is... | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.core',
name: 'Static',
extends: 'foam.core.AbstractMethod',
documentation: 'An Axiom for defining static methods.',
methods: [
function is... |
Use shared_task instead of task. | from .models import FileImport
from .importers import ImportFailure
from django.db import transaction
import celery
assuming_failure_message = '{0} did not return True. Assuming failure.'
processing_status = 'processing'
processing_description = 'Processing the data in {filename}.'
success_status = 'success'
succ... | from .models import FileImport
from .importers import ImportFailure
from django.db import transaction
import celery
assuming_failure_message = '{0} did not return True. Assuming failure.'
processing_status = 'processing'
processing_description = 'Processing the data in {filename}.'
success_status = 'success'
succ... |
Fix query to exclude objects without relevant pages | from django.db.models import OuterRef, Subquery
from official_documents.models import OfficialDocument
from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand
from sopn_parsing.helpers.extract_tables import extract_ballot_table
from sopn_parsing.helpers.text_helpers import NoTextInDocumentError
class... | from sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand
from sopn_parsing.helpers.extract_tables import extract_ballot_table
from sopn_parsing.helpers.text_helpers import NoTextInDocumentError
class Command(BaseSOPNParsingCommand):
help = """
Parse tables out of PDFs in to ParsedSOPN models fo... |
Send application/json instead of urlencoded for webhooks | <?php
namespace CodeDay\Clear\Models\Application;
use Illuminate\Database\Eloquent;
class Webhook extends \Eloquent {
protected $table = 'applications_webhooks';
public function application()
{
return $this->belongsTo('\CodeDay\Clear\Models\Application', 'application_id', 'public');
}
publ... | <?php
namespace CodeDay\Clear\Models\Application;
use Illuminate\Database\Eloquent;
class Webhook extends \Eloquent {
protected $table = 'applications_webhooks';
public function application()
{
return $this->belongsTo('\CodeDay\Clear\Models\Application', 'application_id', 'public');
}
publ... |
Remove defaultSource for shot image | 'use strict';
var React = require('react-native');
var {
Image,
PixelRatio,
StyleSheet,
Text,
TouchableHighlight,
View
} = React;
var getImage = require('./helpers/getImage'),
screen = require('Dimensions').get('window');
var ShotCell = React.createClass({
render: function() {
return (
<V... | 'use strict';
var React = require('react-native');
var {
Image,
PixelRatio,
StyleSheet,
Text,
TouchableHighlight,
View
} = React;
var getImage = require('./helpers/getImage'),
screen = require('Dimensions').get('window');
var ShotCell = React.createClass({
render: function() {
return (
<V... |
Fix unicode support in ExecEngine | import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwarg... | import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwarg... |
Create cookie on game first run | <?php
include("/home/c0smic/secure/data_db_settings.php");
$body = file_get_contents('php://input');
setcookie('game_first-run', true, 5184000 + time(), '/');
$stime = "";
$etime = "";
$moves = "";
function parseData($body) {
$splitter = substr($body, 0, 1);
global $stim... | <?php
include("/home/c0smic/secure/data_db_settings.php");
$body = file_get_contents('php://input');
$stime = "";
$etime = "";
$moves = "";
function parseData($body) {
$splitter = substr($body, 0, 1);
global $stime, $etime, $moves;
$mark1 = strpos($body, $splitter, 1... |
Use custom font for watermark
Signed-off-by: Michal Čihař <a2df1e659c9fd2578de0a26565357cb273292eeb@cihar.com> | import os.path
from django.conf import settings
from versatileimagefield.datastructures.filteredimage import FilteredImage
from versatileimagefield.registry import versatileimagefield_registry
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
class Watermark(FilteredImage):
def process_image(self... | from django.conf import settings
from versatileimagefield.datastructures.filteredimage import FilteredImage
from versatileimagefield.registry import versatileimagefield_registry
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
class Watermark(FilteredImage):
def process_image(self, image, image_... |
Update the arrows to font-awesome | <?php
namespace LaravelFoundation\Pagination;
trait FoundationFiveNextPreviousButtonRendererTrait
{
/**
* Get the previous page pagination element.
*
* @param string $text
* @return string
*/
public function getPreviousButton($text = '<i class="fa fa-caret-left fa-2x"></i>')
{
... | <?php
namespace LaravelFoundation\Pagination;
trait FoundationFiveNextPreviousButtonRendererTrait
{
/**
* Get the previous page pagination element.
*
* @param string $text
* @return string
*/
public function getPreviousButton($text = '«')
{
// If the current page i... |
Fix collection call in embedCheckins | <?php namespace App\Transformer;
use Place;
use League\Fractal\TransformerAbstract;
class PlaceTransformer extends TransformerAbstract
{
protected $availableEmbeds = [
'checkins'
];
/**
* Turn this item object into a generic array
*
* @return array
*/
public function trans... | <?php namespace App\Transformer;
use Place;
use League\Fractal\TransformerAbstract;
class PlaceTransformer extends TransformerAbstract
{
protected $availableEmbeds = [
'checkins'
];
/**
* Turn this item object into a generic array
*
* @return array
*/
public function trans... |
Fix osf clone test that was asking for a password | """Test `osf clone` command."""
import os
from mock import patch, mock_open, call
from osfclient import OSF
from osfclient.cli import clone
from osfclient.tests.mocks import MockProject
from osfclient.tests.mocks import MockArgs
@patch.object(OSF, 'project', return_value=MockProject('1234'))
def test_clone_projec... | """Test `osf clone` command."""
import os
from mock import patch, mock_open, call
from osfclient import OSF
from osfclient.cli import clone
from osfclient.tests.mocks import MockProject
from osfclient.tests.mocks import MockArgs
@patch.object(OSF, 'project', return_value=MockProject('1234'))
def test_clone_projec... |
Fix FindBugs warnings in Parser Test. | package core;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import static org.junit.Assert.*;
/**
* Created by user on 18-5-2016.
*/
public class ParserTest {
public P... | package core;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import static org.junit.Assert.*;
/**
* Created by user on 18-5-2016.
*/
public class ParserTest {
public Parser p;
/**
* Initialize the Parser before testi... |
Add styleinjector task for live css injection | module.exports = function (grunt) {
grunt.initConfig({
styleinjector: {
files: {
src : 'css/site.css'
},
options: {
watchTask: true
}
},
// watch changes to less files
watch: {
styles: {
... | module.exports = function (grunt) {
grunt.initConfig({
// watch changes to less files
watch: {
styles: {
files: ["less/*"],
tasks: ["less"]
},
options: {
spawn: false,
},
},
// compile s... |
Sort imported properties by order_column. | <?php
namespace Nonoesp\Folio\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class ItemPropertiesImport extends Command
{
protected $signature = 'folio:prop:import {id} {json}';
protected $description = 'Import it... | <?php
namespace Nonoesp\Folio\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
//
class ItemPropertiesImport extends Command
{
protected $signature = 'folio:prop:import {id} {json}';
protected $description = 'Impor... |
Add quiet mode support for Retry | import time
from random import uniform
from typing import Callable, Optional
class Retry:
def __init__(
self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False
) -> None:
self.total = total
self.__backoff_factor = backoff_factor
self.__jitter... | import time
from random import uniform
from typing import Callable, Optional
class Retry:
def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None:
self.total = total
self.__backoff_factor = backoff_factor
self.__jitter = jitter
if self.total <=... |
Fix slash escaping in renderer | var DOM = (function(){
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": '''
};
var entityRegex = /[&<>"']/g;
return {
/*
* Returns a child element by its ID. Parent defaults to the entire document.
*/
id: function(id, parent){
re... | var DOM = (function(){
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": '''
};
var entityRegex = /[&<>"'\/]/g;
return {
/*
* Returns a child element by its ID. Parent defaults to the entire document.
*/
id: function(id, parent){
... |
Rename alpha -> learning_rate and gamma -> discount_factor | from ..learner import Learner
from ..policies import RandomPolicy
from ..util import max_action_value
from ..value_functions import TabularF
from ...utils import check_random_state
class QLearning(Learner):
def __init__(self, env, policy=None, qf=None, learning_rate=0.1,
discount_factor=0.99, n_... | from ..learner import Learner
from ..policies import RandomPolicy
from ..util import max_action_value
from ..value_functions import TabularF
from ...utils import check_random_state
class QLearning(Learner):
def __init__(self, env, policy=None, qf=None, alpha=0.1, gamma=0.99,
n_episodes=1000, ran... |
Make sticky header react to resize events. | (function($) {
// http://stackoverflow.com/a/6625189/199100
// http://css-tricks.com/persistent-headers/
function translate(element, x, y) {
var translation = "translate(" + x + "px," + y + "px)";
element.css({
"transform": translation,
"-ms-transform": translation,
"-webkit-transform":... | (function($) {
// http://stackoverflow.com/a/6625189/199100
// http://css-tricks.com/persistent-headers/
function translate(element, x, y) {
var translation = "translate(" + x + "px," + y + "px)";
element.css({
"transform": translation,
"-ms-transform": translation,
"-webkit-transform":... |
Change download url for release 0.3.6 | from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.6',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = 'hspandher@outlook.c... | from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.5',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = 'hspandher@outlook.c... |
Verify overflow in words array into the learn module | import sys
import os
sys.path.append(os.path.dirname(__file__) + "/../../")
from state import state
from state.stateEnum import StateEnum
from helpers import configHelper
from helpers import processorHelper
class Learn:
current_word = 0
def __init__(self, level_number):
self.number = level_number
... | import sys
import os
sys.path.append(os.path.dirname(__file__) + "/../../")
from state import state
from state.stateEnum import StateEnum
from helpers import configHelper
from helpers import processorHelper
class Learn:
current_word = 0
def __init__(self, level_number):
self.number = level_number
... |
Increment the version to 0.2. | from setuptools import setup
setup(name='tfr',
version='0.2',
description='Time-frequency reassigned spectrograms',
url='http://github.com/bzamecnik/tfr',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
packages=['tfr'],
zip_safe=Fals... | from setuptools import setup
setup(name='tfr',
version='0.1',
description='Time-frequency reassigned spectrograms',
url='http://github.com/bzamecnik/tfr',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
packages=['tfr'],
zip_safe=Fals... |
Make sql validators private static | package com.yahoo.squidb.data;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
/*package*/ class SqlValidatorFactory {
interface SqlValidator {
void compileStatement(SQLiteDatabase db, String sql);
... | package com.yahoo.squidb.data;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import com.yahoo.squidb.data.SqlValidatorFactory.SqlValidator;
/*package*/ class SqlValidatorFactory {
interface SqlValidator {
... |
Set up list of needed pieces on init | import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = ... | import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = ... |
Add new line character after output | /*
* grunt-dredd
* https://github.com/mfgea/grunt-dredd
*
* Copyright (c) 2014 Matias Gea
* Licensed under the MIT license.
*/
'use strict';
var Dredd = require('dredd');
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntj... | /*
* grunt-dredd
* https://github.com/mfgea/grunt-dredd
*
* Copyright (c) 2014 Matias Gea
* Licensed under the MIT license.
*/
'use strict';
var Dredd = require('dredd');
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntj... |
Add Wayland Backend.fake_click and Backend.get_all_windows methods
These work by eval-ing in the test Qtile instance. It might be nicer to
instead make these cmd_s on the `Core` if/when we expose cmd_ methods
from the Core. | import contextlib
import os
import textwrap
from libqtile.backend.wayland.core import Core
from test.helpers import Backend
wlr_env = {
"WLR_BACKENDS": "headless",
"WLR_LIBINPUT_NO_DEVICES": "1",
"WLR_RENDERER_ALLOW_SOFTWARE": "1",
"WLR_RENDERER": "pixman",
}
@contextlib.contextmanager
def wayland_e... | import contextlib
import os
from libqtile.backend.wayland.core import Core
from test.helpers import Backend
wlr_env = {
"WLR_BACKENDS": "headless",
"WLR_LIBINPUT_NO_DEVICES": "1",
"WLR_RENDERER_ALLOW_SOFTWARE": "1",
"WLR_RENDERER": "pixman",
}
@contextlib.contextmanager
def wayland_environment(outpu... |
Update namespaces for beta 8
Refs flarum/core#1235. | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Auth\GitHub\Listener;
use Flarum\Frontend\Event\Rendering;
use Illuminate\Contr... | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Auth\GitHub\Listener;
use Flarum\Event\ConfigureWebApp;
use Illuminate\Contract... |
Fix JavaScript Interaction with Forms | $(document).ready( function () {
$('#signup').click(function(event){
event.preventDefault();
$('#screen_block').show();
$('#signup_modal').show();
});
$('#screen_block').click(function(event){
event.preventDefault();
clear_modals();
});
$('#login').click(function(event){
event.preven... | $(document).ready( function () {
$('#signup').click(function(event){
event.preventDefault();
$('#screen_block').show();
$('#signup_modal').show();
});
$('#screen_block').click(function(event){
event.preventDefault();
clear_modals();
});
$('#login').click(function(event){
event.preven... |
Add test for exec_sql parameters
This is testing the different ways the parameters of `exec_sql` can be
defined. | <?php
require_once("tests/util.php");
class PDOTest extends DatabasePDOTestCase
{
public function testLogin()
{
$username = "track";
$password = "password";
$this->assertGreaterThanOrEqual(0, $this->db->valid_login($username, $password));
$th... | <?php
require_once("tests/util.php");
class PDOTest extends DatabasePDOTestCase
{
public function testLogin()
{
$username = "track";
$password = "password";
$this->assertGreaterThanOrEqual(0, $this->db->valid_login($username, $password));
$th... |
Fix migration issue
Fixed 'Course' object has no attribute 'history' issue in the migration | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-12-04 10:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
def add_created_modified_date(apps, schema_editor):
Course = apps.get_model('courses', 'Course')
Histori... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-12-04 10:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
def add_created_modified_date(apps, schema_editor):
Course = apps.get_model('courses', 'Course')
courses... |
Fix given path order for Google App Engine | import os
import hashlib
from datetime import datetime
VCS_NAMES = ['.svn', '.git', '.bzr', '.hg']
IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo']
def list_directory(path, include_directories=True):
# Skip over any VCS directories.
for root, dirs, files in os.walk(path):
for dir in VCS_NAMES:
... | import os
import hashlib
from datetime import datetime
VCS_NAMES = ['.svn', '.git', '.bzr', '.hg']
IGNORED_EXTENSIONS = ['.swp', '.tmp', '.pyc', '.pyo']
def list_directory(path, include_directories=True):
# Skip over any VCS directories.
for root, dirs, files in os.walk(path):
for dir in VCS_NAMES:
... |
Fix minor issue, no functions in loops | <?php
namespace Stringizer\Transformers;
/**
* SwapCase - Swap the case of each character.
*
* @link https://github.com/jasonlam604/Stringizer
* @copyright Copyright (c) 2016 Jason Lam
* @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE.md (MIT License)
*/
class SwapCase extends Transformer ... | <?php
namespace Stringizer\Transformers;
/**
* SwapCase - Swap the case of each character.
*
* @link https://github.com/jasonlam604/Stringizer
* @copyright Copyright (c) 2016 Jason Lam
* @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE.md (MIT License)
*/
class SwapCase extends Transformer ... |
Add active() method to graph object model | // Copyright 2015, EMC, Inc.
'use strict';
module.exports = GraphModelFactory;
GraphModelFactory.$provide = 'Models.GraphObject';
GraphModelFactory.$inject = [
'Model',
'Constants'
];
function GraphModelFactory (Model, Constants) {
return Model.extend({
connection: 'mongo',
identity: 'gr... | // Copyright 2015, EMC, Inc.
'use strict';
module.exports = GraphModelFactory;
GraphModelFactory.$provide = 'Models.GraphObject';
GraphModelFactory.$inject = [
'Model'
];
function GraphModelFactory (Model) {
return Model.extend({
connection: 'mongo',
identity: 'graphobjects',
attribu... |
Remove route defenitions from controllers | <?php
/**
* @link https://github.com/sydes/framework
* @copyright 2011-2017, ArtyGrand <artygrand.ru>
* @license MIT license; see LICENSE
*/
namespace Sydes\Router;
class Router
{
/**
* Path to fast route cache file.
*/
protected $cacheFile = false;
/** @var \FastRoute\Dispatcher */
... | <?php
/**
* @link https://github.com/sydes/framework
* @copyright 2011-2017, ArtyGrand <artygrand.ru>
* @license MIT license; see LICENSE
*/
namespace Sydes\Router;
class Router
{
/**
* Path to fast route cache file.
*/
protected $cacheFile = false;
/** @var \FastRoute\Dispatcher */
... |
Use facade for firing events | <?php
namespace Adldap\Laravel\Traits;
use Adldap\Models\User;
use Adldap\Laravel\Events\AuthenticatedWithWindows;
use Adldap\Laravel\Events\DiscoveredWithCredentials;
use Adldap\Laravel\Events\AuthenticatedWithCredentials;
use Illuminate\Support\Facades\Event;
use Illuminate\Contracts\Auth\Authenticatable;
trait Di... | <?php
namespace Adldap\Laravel\Traits;
use Adldap\Models\User;
use Adldap\Laravel\Events\AuthenticatedWithWindows;
use Adldap\Laravel\Events\DiscoveredWithCredentials;
use Adldap\Laravel\Events\AuthenticatedWithCredentials;
use Illuminate\Contracts\Auth\Authenticatable;
trait DispatchesAuthEvents
{
/**
* Di... |
Add missing config that caused test to fail | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... |
Test that the event manager is not replaced | <?php
namespace UpCloo\App;
class BootTest extends \PHPUnit_Framework_TestCase
{
public function testGetEmptyServiceManagerOnMissingConfiguration()
{
$boot = new Boot(new Config\ArrayProcessor());
$boot->bootstrap();
$this->assertInstanceOf("Zend\\ServiceManager\\ServiceManager", $boot-... | <?php
namespace UpCloo\App;
class BootTest extends \PHPUnit_Framework_TestCase
{
public function testGetEmptyServiceManagerOnMissingConfiguration()
{
$boot = new Boot(new Config\ArrayProcessor());
$boot->bootstrap();
$this->assertInstanceOf("Zend\\ServiceManager\\ServiceManager", $boot-... |
Fix build issue on OSX.
Our script assumes the quest directory only has subdirectories of quests
but OSX adds DS_STORE files to each directory and these were being
picked up and causing the assemble quests script to fail. | """
Assembles the zone configurations for each quest
into one file. Every quest that is in quest_dir
and every zone that is in each quest will be
included.
Example output:
{
quest1: [
{
zone: A,
...
},
{
zone: B,
... | """
Assembles the zone configurations for each quest
into one file. Every quest that is in quest_dir
and every zone that is in each quest will be
included.
Example output:
{
quest1: [
{
zone: A,
...
},
{
zone: B,
... |
Fix exception test function for python3. | import sys
import unittest
#sys.path.insert(0, os.path.abspath('..'))
import github3
class BaseTest(unittest.TestCase):
api = 'https://api.github.com/'
kr = 'kennethreitz'
sigm = 'sigmavirus24'
todo = 'Todo.txt-python'
gh3py = 'github3py'
def setUp(self):
super(BaseTest, self).setUp()... | import sys
import unittest
#sys.path.insert(0, os.path.abspath('..'))
import github3
class BaseTest(unittest.TestCase):
api = 'https://api.github.com/'
kr = 'kennethreitz'
sigm = 'sigmavirus24'
todo = 'Todo.txt-python'
gh3py = 'github3py'
def setUp(self):
super(BaseTest, self).setUp()... |
Fix editor dirty confirm leave.
Use $window instead of window. Use the jQuery element of $window to
bind listeners. Fix final location after modal confirm while properly
retaining browser history. | 'use strict';
angular.module('bitty')
.directive('editorBox', function ($location, $modal, $window) {
return {
restrict: 'AE',
link: function (scope, element) {
var confirmMsg = 'You will lose any unsaved changes.';
var popping = false;
var win = angular.element($window);
... | 'use strict';
angular.module('bitty').directive('editorBox', function ($location, $modal) {
return {
restrict: 'AE',
link: function (scope, element) {
var confirmMsg = 'You will lose any unsaved changes.';
element.addClass('editor-box');
scope.dirty = false;
scope.aceChanged = func... |
Fix fibonacci sensor so it works under Python 3. | import os
from st2reactor.sensor.base import PollingSensor
class FibonacciSensor(PollingSensor):
def __init__(self, sensor_service, config,
poll_interval=5):
super(FibonacciSensor, self).__init__(
sensor_service=sensor_service,
config=config,
poll_int... | from st2reactor.sensor.base import PollingSensor
from environ import get_environ
class FibonacciSensor(PollingSensor):
def __init__(self, sensor_service, config,
poll_interval=5):
super(FibonacciSensor, self).__init__(
sensor_service=sensor_service,
config=config... |
Correct comma spacing for Giuliano | var cheerio = require('cheerio');
require('./parserUtil');
module.exports.parse = function (html, callback) {
var $ = cheerio.load(html);
var menu = [];
var todayStr = global.todaysDate.format("DD. MM. YYYY");
$('.menublock').each(function () {
var leftCellText = $(this).children("div").firs... | var cheerio = require('cheerio');
require('./parserUtil');
module.exports.parse = function (html, callback) {
var $ = cheerio.load(html);
var menu = [];
var todayStr = global.todaysDate.format("DD. MM. YYYY");
$('.menublock').each(function () {
var leftCellText = $(this).children("div").firs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.