text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use a map of persons instead of new ops every time | // Mailin List - Entry point
const Person = require('./person.js');
const Group = require('./group.js');
const MailList = require('./maillist.js');
const people = new Map();
people.set('akata', new Person('Katzuro Akata', 'katzuro@stringcraft.org'));
people.set('tateke', new Person('Makimoro Tateke', 'maki.tate@pebbl... | // Mailin List - Entry point
const Person = require('./person.js');
const Group = require('./group.js');
const MailList = require('./maillist.js');
function test01() {
const g1 = new Group('list-developers');
g1.add(new Person('Katzuro Akata', 'katzuro@stringcraft.org'));
g1.add(new Person('Makimoro Tateke', 'm... |
Add random jitter to the exponential backoff function | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
import random
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurab... | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurable, ThreadPool... |
Exit with non-zero if Whiskey exists with non-zero. | #!/usr/bin/env node
var assert = require('../lib/assert').getAssertModule();
var exec = require('child_process').exec;
var sprintf = require('sprintf').sprintf;
var cwd = process.cwd();
exec(sprintf('NODE_PATH=lib-cov %s/bin/whiskey --tests %s/example/test-success-with-coverage.js --timeout 6000 --coverage --covera... | #!/usr/bin/env node
var assert = require('../lib/assert').getAssertModule();
var exec = require('child_process').exec;
var sprintf = require('sprintf').sprintf;
var cwd = process.cwd();
exec(sprintf('NODE_PATH=lib-cov %s/bin/whiskey --tests %s/example/test-success-with-coverage.js --timeout 6000 --coverage --covera... |
Fix background for chrome dark mode | // TODO: This should be replaced with a styled-components theme
import { createGlobalStyle } from 'styled-components'
import Cookies from 'cookies-js'
export const toggle = mode => {
const { theme } = document.documentElement.dataset
const nextTheme = { dark: 'default', default: 'dark' }[theme]
document.documen... | // TODO: This should be replaced with a styled-components theme
import { createGlobalStyle } from 'styled-components'
import Cookies from 'cookies-js'
export const toggle = mode => {
const { theme } = document.documentElement.dataset
const nextTheme = { dark: 'default', default: 'dark' }[theme]
document.documen... |
Add closing brace and paren lost in merge | var child_process = require('child_process');
describe('Fixture that needs a stub dataservice as a child process', function() {
before(function(done) {
myUnkillableChild =
child_process.exec('node ./child_root/child.js',
{},
function(err, stdout, stderr) {
... | var child_process = require('child_process');
describe('Fixture that needs a stub dataservice as a child process', function() {
before(function(done) {
myUnkillableChild =
child_process.exec('node ./child_root/child.js',
{},
function(err, stdout, stderr) {
... |
Bring back echo to ensure stability | <?php
/*
* Layout functions
*/
// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
return true;
}
}
// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
fu... | <?php
/*
* Layout functions
*/
// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
return true;
}
}
// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
fu... |
Reduce SQLite connection pool size from 5 to 1
(hopefully fixes #1309) | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
/* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database... | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
/* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database... |
Add alt names for 7th chords | const chordRegex = require('../src/chord-regex')
const tape = require('tape')
tape('Regex against valid chords', function (test) {
let chords = [
'C', 'D', 'E', 'F', 'G', 'A', 'B', // white keys
'C#', 'Eb', 'F#', 'Ab', 'G#', 'Bb', // sharps and flats
'Db', 'D#', 'Gb', 'A#', // for those who like to use n... | const chordRegex = require('../src/chord-regex')
const tape = require('tape')
tape('Regex against valid chords', function (test) {
let chords = [
'C', 'D', 'E', 'F', 'G', 'A', 'B', // white keys
'C#', 'Eb', 'F#', 'Ab', 'G#', 'Bb', // sharps and flats
'Db', 'D#', 'Gb', 'A#', // for those who like to use n... |
Use sentence faker for email subjects | import factory
from adhocracy4.follows import models as follow_models
from adhocracy4.test import factories as a4_factories
from meinberlin.apps.newsletters import models
from tests import factories
# FIXME: copied from core
class FollowFactory(factory.django.DjangoModelFactory):
class Meta:
model = fol... | import factory
from adhocracy4.follows import models as follow_models
from adhocracy4.test import factories as a4_factories
from meinberlin.apps.newsletters import models
from tests import factories
# FIXME: copied from core
class FollowFactory(factory.django.DjangoModelFactory):
class Meta:
model = fol... |
UPDATE - Forgot password . . . again | <?php
global $project;
$project = 'mysite';
global $databaseConfig;
$databaseConfig = array(
"type" => 'MySQLDatabase',
"server" => 'localhost',
"username" => 'root',
"password" => 'Redrooster8',
"database" => 'sitesprocket24',
"path" => '',
);
MySQLDatabase::set_connection_charset('utf8');
// This line se... | <?php
global $project;
$project = 'mysite';
global $databaseConfig;
$databaseConfig = array(
"type" => 'MySQLDatabase',
"server" => 'localhost',
"username" => 'root',
"password" => 'root',
"database" => 'sitesprocket24',
"path" => '',
);
MySQLDatabase::set_connection_charset('utf8');
// This line set's the... |
Exclude chamber workflow from targets tested by j2 testall
PiperOrigin-RevId: 384424406 | # Copyright 2021 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | # Copyright 2021 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
Use item.config to access config.
Fixes #1. | # -*- coding: utf-8 -*-
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.build... | # -*- coding: utf-8 -*-
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
_config = None
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
... |
Add comments to merge sort. | package algoholic
// Merge Sort, O(n lg n) worst-case. Very beautiful.
func MergeSort(ns []int) []int {
// Base case - an empty or length 1 slice is trivially sorted.
if len(ns) < 2 {
// We need not allocate memory here as the at most 1 element will only be referenced
// once.
return ns
}
half := len(ns) / ... | package algoholic
// Merge Sort, O(n lg n) worst-case. Very beautiful.
func MergeSort(ns []int) []int {
if len(ns) < 2 {
return ns
}
half := len(ns) / 2
ns1 := MergeSort(ns[:half])
ns2 := MergeSort(ns[half:])
return Merge(ns1, ns2)
}
func Merge(ns1, ns2 []int) []int {
length := len(ns1) + len(ns2)
ret :=... |
Allow compression and whitespace trimming. | var os = require('os')
, path = require('path')
, express = require('express')
, less = require('less-middleware')
, tmp = path.join(os.tmpDir(), 'TesselKey')
, root = __dirname
, pub = path.join(root, 'public')
, images = path.join(pub, 'images')
, scripts = path.join(pub, 'scrip... | var os = require('os')
, path = require('path')
, express = require('express')
, less = require('less-middleware')
, tmp = path.join(os.tmpDir(), 'TesselKey')
, root = __dirname
, pub = path.join(root, 'public')
, images = path.join(pub, 'images')
, scripts = path.join(pub, 'scrip... |
Adjust Settings UI for Chrome Now's Geolocation Source
BUG=164227
Review URL: https://codereview.chromium.org/26315007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@228326 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright 2013 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.
cr.define('options', function() {
var OptionsPage = options.OptionsPage;
/**
* GeolocationOptions class
* Handles initialization of the geoloca... | // Copyright 2013 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.
cr.define('options', function() {
var OptionsPage = options.OptionsPage;
/**
* GeolocationOptions class
* Handles initialization of the geoloca... |
Use range instead of xrange as it is also available in python 3 | from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.... | from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.... |
Use a better unique strings. | import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
... | import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
... |
Make stats quieter in logs. | import bunyan from 'bunyan';
import Promise from 'bluebird';
import SDC from 'statsd-client';
const logger = bunyan.createLogger({name: 'Stats'});
export default class Stats {
constructor(config) {
const stats = config.statsd;
logger.info('Starting StatsD client.');
this._statsd = new SDC({
host: ... | import bunyan from 'bunyan';
import Promise from 'bluebird';
import SDC from 'statsd-client';
const logger = bunyan.createLogger({name: 'Stats'});
export default class Stats {
constructor(config) {
const stats = config.statsd;
logger.info('Starting StatsD client.');
this._statsd = new SDC({
host: ... |
[change] Change the time of loading external CSS | 'use strict';
module.exports = {
input: 'src/*.css',
dir: 'dist',
use: [
'postcss-import',
'postcss-custom-properties',
'postcss-normalize-charset',
'autoprefixer',
'postcss-reporter'
],
'postcss-import': {
plugins: [
require('postcss-import-url'),
require('postcss-... | 'use strict';
module.exports = {
input: 'src/*.css',
dir: 'dist',
use: [
'postcss-import',
'postcss-import-url',
'postcss-custom-properties',
'postcss-normalize-charset',
'autoprefixer',
'postcss-reporter'
],
'postcss-import': {
plugins: [
require('postcss-copy')({
... |
Add null check in TaskCache | package com.bastienleonard.tomate.models;
import android.support.annotation.Nullable;
import android.support.v4.util.SimpleArrayMap;
import java.util.List;
public final class TasksCache {
private SimpleArrayMap<String, Task> mTasks;
public TasksCache() {
}
// FIXME: directly parse the tasks JSON as... | package com.bastienleonard.tomate.models;
import android.support.annotation.Nullable;
import android.support.v4.util.SimpleArrayMap;
import java.util.List;
public final class TasksCache {
private SimpleArrayMap<String, Task> mTasks;
public TasksCache() {
}
// FIXME: directly parse the tasks JSON as... |
Add support for directories in CLI | #!/usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
var globby = require('globby');
var meow = require('meow');
var updateNotifier = require('update-notifier');
var cli = meow({
help: [
'Usage',
' ava <file> [<file> ...]',
'',
'Example',
' ava test.js test2.js'
].join('\... | #!/usr/bin/env node
'use strict';
var path = require('path');
var globby = require('globby');
var meow = require('meow');
var updateNotifier = require('update-notifier');
var cli = meow({
help: [
'Usage',
' ava <file> [<file> ...]',
'',
'Example',
' ava test.js test2.js'
].join('\n')
}, {
string: ['_']
... |
Add missing javadoc and block constructors | /*
* Copyright 2017 Daniel Pedraza-Arcega
*
* 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... | /*
* Copyright 2017 Daniel Pedraza-Arcega
*
* 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... |
Revert to old version of Backbone
Sync doesn't work properly in the latest release. (Though it does work in the
current master...) | require.config({
baseUrl: "/static/scripts/src",
paths: {
// Dependencies:
"underscore": "lib/underscore-min",
"backbone": "lib/backbone",
"jquery": "lib/jquery-3.1.1.min",
"chartjs": "lib/Chart.min"
},
moduleDefaults: {
"build/templates": {}
},
... | require.config({
baseUrl: "/static/scripts/src",
paths: {
// Dependencies:
"underscore": "lib/underscore-min",
"backbone": "lib/backbone-min",
"jquery": "lib/jquery-3.1.1.min",
"chartjs": "lib/Chart.min"
},
moduleDefaults: {
"build/templates": {}
},
... |
Correct check if assertion verification failed. | """Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
clas... | """Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
clas... |
Enable cache for 'get' API call to /cards | export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.path = path;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {... | export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {
this.$log.info('a... |
Remove unused part of code
Change-Id: I2cc8c4b4ef6e4a5b3889edb1dd2fa1a9fc09bd94 | //= require diamond/thesis_menu
$(document).ready(function() {
$(".link-export").click(function() {
$(this).attr("href", $.clear_query_params($(this).attr("href"))+window.location.search);
});
$("button.select-all").click(function() {
$("button.button-checkbox", "div.theses-list").trigger("checkbox-cha... | //= require diamond/thesis_menu
$(document).ready(function() {
$(".link-export").click(function() {
$(this).attr("href", $.clear_query_params($(this).attr("href"))+window.location.search);
});
$("button.select-all").click(function() {
$("button.button-checkbox", "div.theses-list").trigger("checkbox-cha... |
Fix doc for non-existing parameter | <?php
namespace Brick\Money\Context;
use Brick\Money\Context;
use Brick\Money\Currency;
use Brick\Math\BigNumber;
/**
* Adjusts the scale & step of the result to custom values.
*/
class PrecisionContext implements Context
{
/**
* @var int
*/
private $scale;
/**
* @var int
*/
p... | <?php
namespace Brick\Money\Context;
use Brick\Money\Context;
use Brick\Money\Currency;
use Brick\Math\BigNumber;
/**
* Adjusts the scale & step of the result to custom values.
*/
class PrecisionContext implements Context
{
/**
* @var int
*/
private $scale;
/**
* @var int
*/
p... |
Migrate to PlaceholderExpansion from PlaceholderAPI | package com.github.games647.fastlogin.bukkit;
import java.util.stream.Collectors;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
public class PremiumPlaceholder extends PlaceholderExpansion {
private static final Stri... | package com.github.games647.fastlogin.bukkit;
import java.util.List;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderHook;
import org.bukkit.entity.Player;
import org.bukkit.metadata.MetadataValue;
public class PremiumPlaceholder extends PlaceholderHook {
private final Fa... |
Convert numpy int to native int for JSON serialization | from analyses.mimp import glycosylation_sub_types, run_mimp
from helpers.plots import stacked_bar_plot
from ..store import counter
@counter
@stacked_bar_plot
def gains_and_losses_for_glycosylation_subtypes():
results = {}
effects = 'loss', 'gain'
for source_name in ['mc3', 'clinvar']:
for site_ty... | from analyses.mimp import glycosylation_sub_types, run_mimp
from helpers.plots import stacked_bar_plot
from ..store import counter
@counter
@stacked_bar_plot
def gains_and_losses_for_glycosylation_subtypes():
results = {}
effects = 'loss', 'gain'
for source_name in ['mc3', 'clinvar']:
for site_ty... |
Set group as read only when inviting students | from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)... | from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)... |
Fix errors showing up because 'email' is not set | <?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$beginning = '<div class="container"><nav class="navbar navbar-default "><div class="navbar-header">
<a class="navbar-brand">Navigation Bar </a>
</div><ul class="nav navbar-nav justified">';
$front... | <?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$beginning = '<div class="container"><nav class="navbar navbar-default "><div class="navbar-header">
<a class="navbar-brand">Navigation Bar </a>
</div><ul class="nav navbar-nav justified">';
$front... |
Fix telescope-search route for iron:router 1.0
The ``onBeforeAction`` in ``PostsSearchController`` isn't calling ``this.next()``, and so is never dispatching. | adminNav.push({
route: 'searchLogs',
label: 'Search Logs'
});
Meteor.startup(function () {
PostsSearchController = PostsListController.extend({
view: 'search',
onBeforeAction: function() {
if ("q" in this.params) {
Session.set("searchQuery", this.params.q);
}
this.next();
... | adminNav.push({
route: 'searchLogs',
label: 'Search Logs'
});
Meteor.startup(function () {
PostsSearchController = PostsListController.extend({
view: 'search',
onBeforeAction: function() {
if ("q" in this.params) {
Session.set("searchQuery", this.params.q);
}
}
});
Router.o... |
Add example points for InfluxDB | import serial
import schedule
import time
import json
from flask import Flask, request
from threading import Thread
from influxdb import InfluxDBClient
COM_PORT = 2
BAUDRATE = 9600
READ_SENSORS_TIMER = 1
DB_HOST = '192.168.1.73'
DB_PORT = 8086
DB_NAME = 'awarehouse'
DB_PASS = 'admin'
DB_USER = 'admin'
influxdb = Infl... | import serial
import schedule
import time
from flask import Flask, request
from threading import Thread
from influxdb import InfluxDBClient
COM_PORT = 2
BAUDRATE = 9600
READ_THREAD = 10
DB_HOST = 'localhost'
DB_HOST_PORT = 8086
DB_NAME = 'awarehouse'
DB_PASS = 'admin'
DB_USER = 'admin'
influxdb = InfluxDBClient(DB_HO... |
Fix $.wrap for null
This also fixes $ for when no element is found | const flatten = require('flatten')
const Set = require('es6-set')
function normalizeRoot(root) {
if(!root) return document
if(typeof(root) == 'string') return $(root)
return root
}
function $(selector, root) {
root = normalizeRoot(root)
return wrapNode(root.querySelector(selector))
}
$.all = function $$(sel... | const flatten = require('flatten')
const Set = require('es6-set')
function normalizeRoot(root) {
if(!root) return document
if(typeof(root) == 'string') return $(root)
return root
}
function $(selector, root) {
root = normalizeRoot(root)
return wrapNode(root.querySelector(selector))
}
$.all = function $$(sel... |
Add additional jquery expose-loader to global $ | // Common webpack configuration used by webpack.hot.config and webpack.rails.config.
const path = require('path');
module.exports = {
// the project dir
context: __dirname,
entry: ['jquery', 'jquery-ujs', './assets/javascripts/App'],
resolve: {
root: [
path.join(__dirname, 'scripts'),
path.j... | // Common webpack configuration used by webpack.hot.config and webpack.rails.config.
const path = require('path');
module.exports = {
// the project dir
context: __dirname,
entry: ['jquery', 'jquery-ujs', './assets/javascripts/App'],
resolve: {
root: [
path.join(__dirname, 'scripts'),
path.j... |
Add comment about setting unfriendly_mode. | package uk.ac.cam.gpe21.droidssl.analysis;
import soot.PackManager;
import soot.Transform;
import soot.options.Options;
import java.util.Arrays;
public final class StaticAnalyser {
public static void main(String[] args) {
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_output_format(Options.outp... | package uk.ac.cam.gpe21.droidssl.analysis;
import soot.PackManager;
import soot.Transform;
import soot.options.Options;
import java.util.Arrays;
public final class StaticAnalyser {
public static void main(String[] args) {
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_output_format(Options.outp... |
Adjust to scalar types introduced in Locale component & bundle | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\Context;
use Sylius\Component\Core\Mode... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\Context;
use Sylius\Component\Core\Mode... |
Add a 'type()' function to resources for policy engines to lookup policies | from abc import ABCMeta, abstractmethod
from googleapiclienthelpers.discovery import build_subresource
class ResourceBase(metaclass=ABCMeta):
@abstractmethod
def get(self):
pass
@abstractmethod
def update(self):
pass
class GoogleAPIResourceBase(ResourceBase, metaclass=ABCMeta):
... | from abc import ABCMeta, abstractmethod
from googleapiclienthelpers.discovery import build_subresource
class ResourceBase(metaclass=ABCMeta):
@abstractmethod
def get(self):
pass
@abstractmethod
def update(self):
pass
class GoogleAPIResourceBase(ResourceBase, metaclass=ABCMeta):
... |
Remove unused custom http client | package skin
import (
"errors"
"fmt"
"image/png"
"net/http"
)
const (
skinURL = "http://skins.minecraft.net/MinecraftSkins/%s.png"
)
func Download(player string) (skin *Skin, err error) {
resp, err := http.Get(fmt.Sprintf(skinURL, player))
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
... | package skin
import (
"errors"
"fmt"
"image/png"
"net/http"
)
const (
skinURL = "http://skins.minecraft.net/MinecraftSkins/%s.png"
)
// Follow all redirects
var skinClient = &http.Client{
CheckRedirect: func(*http.Request, []*http.Request) error {
return nil
},
}
func Download(player string) (skin *Skin, e... |
Add a key/value pairs parameter type | from collections import OrderedDict
from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label... | from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label
class Integer(Parameter):
def... |
Update docker-images to version 45 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribut... | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribut... |
Allow PasswordFun to return an error | package ssh
import "os"
type C struct {
User string
Host string
HostKeyFun func([]byte)os.Error
PasswordFun func()(string,os.Error)
}
func New(C C) (*Client,os.Error) {
c,e := connect(C.Host)
if e != nil { return nil,e }
writeKexInit(c)
b,e := readPacket(c)
c.skex = make([]byte, len(b))
copy(c.skex, b)
i... | package ssh
import "os"
type C struct {
User string
Host string
HostKeyFun func([]byte)os.Error
PasswordFun func()string
}
func New(C C) (*Client,os.Error) {
c,e := connect(C.Host)
if e != nil { return nil,e }
writeKexInit(c)
b,e := readPacket(c)
c.skex = make([]byte, len(b))
copy(c.skex, b)
if e!=nil { ... |
Create Error instances when errors happen | var config = require("config")
, crypto = require("crypto")
, request = require("request")
, github = require("./github")
module.exports.generateNonce = function (length) {
return crypto.randomBytes(length * 2).toString("hex").slice(0, length)
}
module.exports.requestAccessToken = function (code, cb) {
var ... | var config = require("config")
, crypto = require("crypto")
, request = require("request")
, github = require("./github")
module.exports.generateNonce = function (length) {
return crypto.randomBytes(length * 2).toString("hex").slice(0, length)
}
module.exports.requestAccessToken = function (code, cb) {
var ... |
Make the link to the ES6 katas at the bottom of the page work (with a hack). | import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
... | import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
... |
feat: Change the default value for format | const path = require('path')
const pkgConf = require('pkg-conf')
const { validate } = require('jest-validate')
function replaceRootDir (conf, rootDir) {
const replace = s => s.replace('<rootDir>', rootDir)
;['srcPathDirs', 'srcPathIgnorePatterns', 'localeDir']
.forEach(key => {
const value = conf[key]
... | const path = require('path')
const pkgConf = require('pkg-conf')
const { validate } = require('jest-validate')
function replaceRootDir (conf, rootDir) {
const replace = s => s.replace('<rootDir>', rootDir)
;['srcPathDirs', 'srcPathIgnorePatterns', 'localeDir']
.forEach(key => {
const value = conf[key]
... |
Change class name in tests | # Licensed under an MIT open source license - see LICENSE
'''
Test function for Wavelet
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Wavelet, Wavelet_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class ... | # Licensed under an MIT open source license - see LICENSE
'''
Test function for Wavelet
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import wt2D, Wavelet_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class tes... |
Fix type of EventIndex fields | from haystack import indexes
from .models import Event, Place, PublicationStatus
from django.utils.html import strip_tags
class EventIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
start_time ... | from haystack import indexes
from .models import Event, Place, PublicationStatus
from django.utils.html import strip_tags
class EventIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
start_time ... |
Add error ident for easier catching | #!/usr/bin/env node
const crypto = require("crypto");
const _sss = require("./build/Release/shamirsecretsharing");
exports.createShares = function createShares(data, n, k) {
return new Promise((resolve) => {
// Use node.js native random source for a key
crypto.randomBytes(32, (err, random) => {
if (e... | #!/usr/bin/env node
const crypto = require("crypto");
const _sss = require("./build/Release/shamirsecretsharing");
exports.createShares = function createShares(data, n, k) {
return new Promise((resolve) => {
// Use node.js native random source for a key
crypto.randomBytes(32, (err, random) => {
if (e... |
Add another file type to the AcceptTypes | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
public static $AcceptTypes = array(
'text/plain',
'text/x-asm', // some css
'text/x-php',
'text/x-Algol68'
);
public static $InvalidFileNames = array(
'nbproject/', // netbeans project f... | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
public static $AcceptTypes = array(
'text/plain',
'text/x-asm', // some css
'text/x-php',
);
public static $InvalidFileNames = array(
'nbproject/', // netbeans project files
... |
Use the same logic to format message and asctime than the standard library.
This way we producte better message text on some circumstances when not logging
a string and use the date formater from the base class that uses the date format
configured from a file or a dict. | import logging
import json
import re
class JsonFormatter(logging.Formatter):
"""A custom formatter to format logging records as json objects"""
def parse(self):
standard_formatters = re.compile(r'\((.*?)\)', re.IGNORECASE)
return standard_formatters.findall(self._fmt)
def format(self, re... | import logging
import json
import re
from datetime import datetime
class JsonFormatter(logging.Formatter):
"""A custom formatter to format logging records as json objects"""
def parse(self):
standard_formatters = re.compile(r'\((.*?)\)', re.IGNORECASE)
return standard_formatters.findall(self._... |
Fix typo in require statement of is-binary-string | 'use strict';
// MODULES //
var isString = require( '@stdlib/utils/is-string' )[ 'primitive' ];
// BINARY STRING //
/**
* FUNCTION: isBinaryString( value )
* Tests if a value is a binary string.
*
* @param {*} value - value to test
* @returns {Boolean} boolean indicating if an input value is a binary string
*/
fun... | 'use strict';
// MODULES //
var isString = require( '@stlib/utils/is-string' )[ 'primitive' ];
// BINARY STRING //
/**
* FUNCTION: isBinaryString( value )
* Tests if a value is a binary string.
*
* @param {*} value - value to test
* @returns {Boolean} boolean indicating if an input value is a binary string
*/
func... |
Use Python 3 style for super | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
query... | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
query... |
Handle situation when kwargs is None | from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
if reverse_kwargs!=None:
locale = utils.supported_language(reverse_kwargs.pop('locale',
... | from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
locale = utils.supported_language(reverse_kwargs.pop('locale',
translation.get_language()))
... |
Revert a debugging change that slipped in. | from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
... | from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
... |
UglifyJs: Change the ecma option from 8 to 5 | 'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
... | 'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
... |
Add all modules to package |
package com.reactlibrary;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook... |
package com.reactlibrary;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook... |
Fix JavaScript bug with arguments. |
/**
* @param {Object}
* @param {Array.<String>}
*/
module.exports = function(_class, _instance, mixined) {
_instance.mixined = {};
(mixined||[]).forEach(function(name) {
_instance.mixined[name] = [];
});
_instance.mixins = function(mixins)
{
var args = [].slice.call(arguments);
if (typeof args[0] ===... |
/**
* @param {Object}
* @param {Array.<String>}
*/
module.exports = function(_class, _instance, mixined) {
_instance.mixined = {};
(mixined||[]).forEach(function(name) {
_instance.mixined[name] = [];
});
_instance.mixins = function(mixins)
{
if (typeof arguments[0] === 'string') {
mixins = [{}];
m... |
Use html string instead of temp html file | const fs = require('fs')
const path = require('path')
const showdown = require('showdown')
exports.reloadMarkdownFile = function (mainWindow, markdownFileName) {
fs.readFile(markdownFileName, 'utf8', function (err, markdown) {
if (err) throw err
var converter = new showdown.Converter()
var html = conver... | const fs = require('fs')
const path = require('path')
const showdown = require('showdown')
const temp = require('temp')
const url = require('url')
exports.reloadMarkdownFile = function (mainWindow, markdownFileName) {
fs.readFile(markdownFileName, 'utf8', function (err, markdown) {
if (err) throw err
var co... |
Add version constraint for underscore-deep | Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default ... | Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default ... |
Append new individual batch operation data to the end of the batch data array.
array_merge() is *slow* as the number of operations gets larger. | <?php
namespace Everyman\Neo4j\Command\Batch;
use Everyman\Neo4j\Client,
Everyman\Neo4j\Batch;
/**
* Commit a batch operation
* @todo: Handle the case of empty body or body\data needing to be objects not arrays
*/
class Commit extends Command
{
protected $batch = null;
/**
* Set the batch to drive the command... | <?php
namespace Everyman\Neo4j\Command\Batch;
use Everyman\Neo4j\Client,
Everyman\Neo4j\Batch;
/**
* Commit a batch operation
* @todo: Handle the case of empty body or body\data needing to be objects not arrays
*/
class Commit extends Command
{
protected $batch = null;
/**
* Set the batch to drive the command... |
Improve time generation for logging | const moment = require("moment");
let ctx;
try {
const chalk = require("chalk");
ctx = new chalk.constructor({enabled:true});
} catch (err) {
// silent
}
function getTime() {
return (" " + moment().format("LTS")).slice(-11);
}
module.exports = {
log(...args) {
if (ctx) console.log(getTi... | const moment = require("moment");
let ctx;
try {
const chalk = require("chalk");
ctx = new chalk.constructor({enabled:true});
} catch (err) {
// silent
}
function getTime() {
const curHour = new Date().getHours() % 12 || 12;
return (curHour < 10 ? " " : "") + moment().format("LTS");
}
module.e... |
Add job label description equal to service label description | const Labels = {
type: 'object',
title: 'Labels',
description: 'Attach metadata to jobs to expose additional information to other jobs.',
properties: {
items: {
type: 'array',
duplicable: true,
addLabel: 'Add Label',
getter(job) {
let labels = job.getLabels() || {};
... | const Labels = {
type: 'object',
title: 'Labels',
properties: {
items: {
type: 'array',
duplicable: true,
addLabel: 'Add Label',
getter(job) {
let labels = job.getLabels() || {};
return Object.keys(labels).map(function (key) {
return {
key,
... |
Make the Sifter issue matching more specific.
Now it matches:
* 3-5 digit numbers
* Preceded by a #, whitespace, or beginning-of-line.
* Followed by a comma, period, question mark, exclamation point,
whitespace, or end-of-line. | from base import BaseMatcher
import os
import requests
import re
import json
NUM_REGEX = r'(?:[\s#]|^)(\d\d\d\d?\d?)(?:[\s\.,\?!]|$)'
API_KEY = os.environ.get('SIFTER')
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues... | from base import BaseMatcher
import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ.get('SIFTER')
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url... |
Use proper package name for pbr | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... |
Return 0 as an int rather than a string.
This was causing an ocassional crash in bumblebee/engine.py threshold_state
when checkupdates fails, perhaps due to wifi not being up yet.
For me this showed up regularly on login. | """Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine,... | """Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine,... |
Add a recipe for making the parent item from the created currency item | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.content.registry.item.currency;
import com.skelril.nitro.registry.item.CraftableIte... | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.content.registry.item.currency;
import com.skelril.nitro.registry.item.CraftableIte... |
Add array return for the rest controller | <?php
namespace MainBundle\Controller;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use MainBundle\Entity\Logo;
use MainBundle\Entity\Section;
use MainBundle\Repository\LogoRepository;
use MainBundle\Repository\SectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Contro... | <?php
namespace MainBundle\Controller;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use MainBundle\Entity\Logo;
use MainBundle\Entity\Section;
use MainBundle\Repository\LogoRepository;
use MainBundle\Repository\SectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Contro... |
Read env variables with dotenv | import argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args ... | import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.env... |
Return a fallback "version" if dosage is not installed
Additionally, inform the user on how to fix the problem. Thanks to twb
for noticing this. | # -*- coding: utf-8 -*-
# Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs
# Copyright (C) 2012-2014 Bastian Kleineidam
# Copyright (C) 2015-2019 Tobias Gruetzmacher
"""
Automated comic downloader. Dosage traverses comic websites in
order to download each strip of the comic. The intended use is for
mirrori... | # -*- coding: utf-8 -*-
# Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs
# Copyright (C) 2012-2014 Bastian Kleineidam
# Copyright (C) 2015-2019 Tobias Gruetzmacher
"""
Automated comic downloader. Dosage traverses comic websites in
order to download each strip of the comic. The intended use is for
mirrori... |
Fix KeyError when accessing non-existing header | from flask import Request, Response
class RqRequest(Request):
def rq_headers(self):
headers = {}
if 'Authorization' in self.headers:
headers['Authorization'] = self.headers['Authorization']
if self.headers.get('Accept') == 'application/xml':
headers['Accept'] = 'appli... | from flask import Request, Response
class RqRequest(Request):
def rq_headers(self):
headers = {}
if 'Authorization' in self.headers:
headers['Authorization'] = self.headers['Authorization']
if self.headers['Accept'] == 'application/xml':
headers['Accept'] = 'applicati... |
Change redirect URI to github project page | var browser = require('openurl');
var config = require('./config');
var REDIRECT_URI = 'https://rogeriopvl.github.io/downstagram';
console.log('\n********** DOWNSTAGRAM OAUTH SETUP **********');
console.log('\n To use downstagram you need to authorize it to access your instagram account.');
console.log('Your browser... | var browser = require('openurl');
var config = require('./config');
var REDIRECT_URI = '';
console.log('\n********** DOWNSTAGRAM OAUTH SETUP **********');
console.log('\n To use downstagram you need to authorize it to access your instagram account.');
console.log('Your browser will open for you to authorize the app.... |
Add tests for parse CLI with pos_kind | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom'])
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix, sample):
runner = CliRunner()
with tempfile.NamedTempor... |
Use jquery instead of ext in Directory-ViewMap component | var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var formRegistry = require('kwf/frontend-form/form-registry');
var gmapLoader = require('kwf/google-map/loader');
var gmapMap = require('kwf/google-map/map');
var renderedMaps = [];
var renderMap = function(map) {
if (renderedMaps.indexOf(map) != -... | var onReady = require('kwf/on-ready-ext2');
var formRegistry = require('kwf/frontend-form/form-registry');
var gmapLoader = require('kwf/google-map/loader');
var gmapMap = require('kwf/google-map/map');
var renderedMaps = [];
var renderMap = function(map) {
if (renderedMaps.indexOf(map) != -1) return;
rendere... |
Fix case sensitive email login | /* eslint-disable func-names, prefer-arrow-callback */
import local from 'passport-local';
import * as objection from 'objection';
import bcrypt from 'bcrypt';
import { User } from './models';
export default (passport) => {
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deseria... | /* eslint-disable func-names, prefer-arrow-callback */
import local from 'passport-local';
import * as objection from 'objection';
import bcrypt from 'bcrypt';
import { User } from './models';
export default (passport) => {
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deseria... |
Mark compatibility table test as slow (temporary)
Prevent Travis from running test test until models repo is published | # coding: utf-8
from __future__ import unicode_literals
from ..download import download, get_compatibility, get_version, check_error_depr
import pytest
@pytest.mark.slow
def test_download_fetch_compatibility():
compatibility = get_compatibility()
assert type(compatibility) == dict
@pytest.mark.slow
@pytest... | # coding: utf-8
from __future__ import unicode_literals
from ..download import download, get_compatibility, get_version, check_error_depr
import pytest
def test_download_fetch_compatibility():
compatibility = get_compatibility()
assert type(compatibility) == dict
@pytest.mark.slow
@pytest.mark.parametrize(... |
Remove obsolete call to debugComponentTrees | package ch.difty.scipamato.publ.web.paper.browse;
import org.apache.wicket.model.Model;
import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter;
import ch.difty.scipamato.publ.web.common.PanelTest;
public class SimpleFilterPanelTest extends PanelTest<SimpleFilterPanel> {
private static final String PANEL... | package ch.difty.scipamato.publ.web.paper.browse;
import org.apache.wicket.model.Model;
import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter;
import ch.difty.scipamato.publ.web.common.PanelTest;
public class SimpleFilterPanelTest extends PanelTest<SimpleFilterPanel> {
private static final String PANEL... |
Remove event start field from form | # -*- coding: utf-8 -*-
from django import forms
from apps.posters.models import Poster
class AddPosterForm(forms.ModelForm):
display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'}))
display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(a... | # -*- coding: utf-8 -*-
from django import forms
from apps.posters.models import Poster
class AddPosterForm(forms.ModelForm):
when = forms.CharField(label=u"Event start", widget=forms.TextInput(attrs={'type': 'datetime-local'}))
display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(... |
Use Sentry Laravel object as client. | <?php
namespace Timetorock\LaravelMonologSentry\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RavenHandler;
use Raven_Client;
use Log;
class MonologSentryServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
... | <?php
namespace Timetorock\LaravelMonologSentry\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RavenHandler;
use Raven_Client;
use Log;
class MonologSentryServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
... |
Add check to customer context
| Q | A
| ------------- | ---
| Bug fix? | no
| New feature? | no
| BC breaks? | no
| Deprecations? | no
| Fixed tickets |
| License | MIT
| Doc PR |
In one part of our site we don't need sylius autentication, just basic http with a generic username and ... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\UserBundle\Context;
use Sylius\Component\User\Context\CustomerContextInterfac... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\UserBundle\Context;
use Sylius\Component\User\Context\CustomerContextInterfac... |
Declare return type on exists() | <?php
namespace Amp\Parallel\Worker;
interface Environment extends \ArrayAccess
{
/**
* @param string $key
*
* @return bool
*/
public function exists(string $key): bool;
/**
* @param string $key
*
* @return mixed|null Returns null if the key does not exist.
*/
... | <?php
namespace Amp\Parallel\Worker;
interface Environment extends \ArrayAccess
{
/**
* @param string $key
*
* @return bool
*/
public function exists(string $key);
/**
* @param string $key
*
* @return mixed|null Returns null if the key does not exist.
*/
public... |
Fix piwik by using window._paq
Fix #636 | if (document.head.dataset.piwikHost) {
window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
window._paq.push(['trackPageView']);
window._paq.push(['enableLinkTracking']);
(function() {
var u=document.head.dataset.piwikHost;
window._pa... | if (document.head.dataset.piwikHost) {
var _paq = _paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u=document.head.dataset.piwikHost;
_paq.push(['setTrackerUrl', u+'piw... |
Allow layout and theme opt-out | import React from 'react'
import styles from './PreviewTools.styl'
export default ({ href, layout, theme, onLayoutChanged, onThemeChanged }) =>
<div className={styles.container}>
<div>
Layout:
<select value={layout} onChange={onLayoutChanged}>
<option value="none">None</option>
<opti... | import React from 'react'
import styles from './PreviewTools.styl'
export default ({ href, layout, theme, onLayoutChanged, onThemeChanged }) =>
<div className={styles.container}>
<div>
Layout:
<select value={layout} onChange={onLayoutChanged}>
<option value="blog">Blog</option>
<opti... |
Update cli help to say milliseconds | #!/usr/bin/env node
var program = require('commander')
var command
var env
program
.usage('[options]')
.option('-f, --file [file]', 'config file - defaults to testem.json or testem.yml')
.option('-p, --port [num]', 'server port - defaults to 7357', Number)
.option('-l, --launch [list]', 'list of launch... | #!/usr/bin/env node
var program = require('commander')
var command
var env
program
.usage('[options]')
.option('-f, --file [file]', 'config file - defaults to testem.json or testem.yml')
.option('-p, --port [num]', 'server port - defaults to 7357', Number)
.option('-l, --launch [list]', 'list of launch... |
Fix parsing of item strings in first position | import CodeMirror from 'codemirror';
import 'codemirror/addon/mode/simple';
var VAR_REGEX = /(\?|\$)[A-Za-z_][A-Za-z0-9\-_]*/;
var STRING_REGEX = /\"(\\.|[^\"])*\"/;
var PROPERTY_ID_REGEX = /:P[0-9]*/;
var ITEM_ID_REGEX = /:Q[0-9]*/;
CodeMirror.defineSimpleMode('qwery', {
start: [
{regex: STRING_REGEX, token: '... | import CodeMirror from 'codemirror';
import 'codemirror/addon/mode/simple';
var VAR_REGEX = /(\?|\$)[A-Za-z_][A-Za-z0-9\-_]*/;
var STRING_REGEX = /\"(\\.|[^\"])*\"/;
var PROPERTY_ID_REGEX = /:P[0-9]*/;
var ITEM_ID_REGEX = /:Q[0-9]*/;
CodeMirror.defineSimpleMode('qwery', {
start: [
{regex: STRING_REGEX, token: '... |
Refactor and add new Events unit tests | var path = require('path');
module.exports = function() {
var Events = require(path.resolve(process.cwd(), 'lib/base/events'));
describe('Events', function() {
var events;
beforeEach(function() {
events = new Events();
});
describe('#off()', function() {
it('should deregister multipl... | var assert = require('assert');
var equal = assert.equal;
var path = require('path');
var basePath = process.cwd();
module.exports = function() {
var Events = require(path.resolve(basePath + '/lib/base/events'));
describe('Events', function() {
var events;
var handlersRun;
beforeEach(function() {
... |
Adjust server test message welcome page | // request-promise is just like the HTTP client 'Request', except Promises-compliant.
// See https://www.npmjs.com/package/request-promise.
var requestPromise = require('request-promise');
var request = require('request');
var expect = require('chai').expect;
require('./setup.js');
var db = require('./../../server/con... | // request-promise is just like the HTTP client 'Request', except Promises-compliant.
// See https://www.npmjs.com/package/request-promise.
var requestPromise = require('request-promise');
var request = require('request');
var expect = require('chai').expect;
require('./setup.js');
var db = require('./../../server/con... |
Fix unit test for JDK 1.3. | package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
static class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.... | package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp()... |
Fix typo in error message
[#115369351] | import React, { Component } from 'react'
import pureRender from 'pure-render-decorator'
import '../../css/data-fetch-error.less'
@pureRender
export default class DataFetchError extends Component {
renderUnauthorized() {
return <div>
You are not authorized to access report data. Your access token might have... | import React, { Component } from 'react'
import pureRender from 'pure-render-decorator'
import '../../css/data-fetch-error.less'
@pureRender
export default class DataFetchError extends Component {
renderUnauthorized() {
return <div>
Your are not authorized to access report data. Your access token might hav... |
Use native Promise instead of $q | /* global require */
import platformInfo from './platform-info.js';
let StellarLedger;
if (platformInfo.isElectron) {
const electron = require('electron');
StellarLedger = electron.remote.require('stellar-ledger-api');
}
const bip32Path = (index) => `44'/148'/${index}'`;
const wrapper = (func, field) => new Promi... | /* global angular, require */
import 'ionic-sdk/release/js/ionic.bundle';
import platformInfo from './platform-info.js';
angular.module('app.service.ledger-nano', [])
.factory('LedgerNano', function ($q) {
'use strict';
let StellarLedger;
if (platformInfo.isElectron) {
const electron = require('electron');
St... |
Add int() wrapper to prevent floats | import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1... | import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1... |
Fix profile creation. (Need tests badly). | from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
... | from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
... |
Fix crash due to missing uses | <?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use App;
use View;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addit... | <?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as th... |
Make fields on model have defaults value
Like who cares for their default value | from django.db import models
from django.test import TestCase
from django.utils.baseconv import base64
from django_base64field.fields import Base64Field
class Planet(models.Model):
ek = Base64Field()
name = models.CharField(
default='Fucker',
max_length=103
)
class Continent(models.Model)... | from django.db import models
from django.test import TestCase
from django.utils.baseconv import base64
from django_base64field.fields import Base64Field
class Planet(models.Model):
ek = Base64Field()
name = models.CharField(max_length=13)
class Continent(models.Model):
ek = Base64Field()
name = model... |
Add error logging to aid tracking down future issues. | """
Scan through the Samples table for oldish entries and remove them.
"""
import logging
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
def purge_item(item, batch):
response = batch.delete_item(
... | """
Scan through the Samples table for oldish entries and remove them.
"""
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def purge_item(item, batch):
response = batch.delete_item(
Key={
'event' : item['event'],
'id': item['id']
... |
Add scale to list of unitless CSS properties | // Taken from:
// https://github.com/necolas/react-native-web/blob/master/src/apis/StyleSheet/normalizeValue.js
const unitlessNumbers = {
boxFlex: true,
boxFlexGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
fontWeight: true,
line... | // Taken from:
// https://github.com/necolas/react-native-web/blob/master/src/apis/StyleSheet/normalizeValue.js
const unitlessNumbers = {
boxFlex: true,
boxFlexGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
fontWeight: true,
line... |
Add Salmon Run (co-op mode) data | require('dotenv').config();
const axios = require('axios');
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const dataPath = path.resolve('public/data');
// SplatNet2 API
const api = axios.create({
baseURL: 'https://app.splatoon2.nintendo.net/api/',
headers: {'Cookie'... | require('dotenv').config();
const axios = require('axios');
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const dataPath = path.resolve('public/data');
// SplatNet2 API
const api = axios.create({
baseURL: 'https://app.splatoon2.nintendo.net/api/',
headers: {'Cookie'... |
Use Router.TestLocation instead of bare string when testing. | import React from 'react';
import Router from 'react-router';
import routes from './routes';
// import SettingsActions from '../../actions/settings';
// import UserActions from '../actions/user';
// var Route = Router.Route;
// describe('Logged in', function () {
// he... | import React from 'react';
import Router from 'react-router';
import routes from './routes';
// import SettingsActions from '../../actions/settings';
// import UserActions from '../actions/user';
// var Route = Router.Route;
// describe('Logged in', function () {
// he... |
Use six to improve python 3 compatibility.
* StringIO
Change-Id: I8471e525566a0353d9276529be4b0d0e0cbf6cd6 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
Use real mail address to make PyPi happy | from setuptools import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451@laposte.net',
maintainer='montag451',
maintainer_email='montag451@laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Python',
... | from setuptools import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451 at laposte.net',
maintainer='montag451',
maintainer_email='montag451 at laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Pytho... |
Address PR comments on unit test for confirm delete | import Ember from "ember";
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:gist', {
needs: ['service:ember-cli'],
beforeEach() {
this._originalConfirm = window.confirm;
},
afterEach() {
window.confirm = this._originalConfirm;
}
});
test('deleting a gist requires confirmation',... | import Ember from "ember";
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:gist', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
needs: ['service:ember-cli']
});
// Replace this with your real tests.
test('it exists', function(assert) {
var cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.