text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update database-uri and tweet-interval to use properties in config.js | var config = require('./config'),
Twit = require('twit'),
mongoose = require('mongoose');
var T = new Twit(config.oauth_creds),
quotes = mongoose.model('quotes', {msg: String, src: String});
var tweet = function () {
var promise = quotes.count().exec();
promise.then(function (cnt) {
var n = Math.f... | var config = require('./config'),
Twit = require('twit'),
mongoose = require('mongoose');
var T = new Twit(config.oauth_creds),
quotes = mongoose.model('quotes', {msg: String, src: String});
var tweet = function () {
var promise = quotes.count().exec();
promise.then(function (cnt) {
var n = Math.f... |
Test for expected and unexpected checks | from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
... | from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
... |
Switch to regexp based matching of date instead of dateutil | import re
from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = "KAL's Cartoon"
language = 'en'
url = 'http://www.economist.com'
start_date = '2006-01-05'
rights = 'Kevin Kallaugher'
class Crawler(CrawlerBase):
hist... | from dateutil.parser import parse
from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = "KAL's Cartoon"
language = 'en'
url = 'http://www.economist.com'
start_date = '2006-01-05'
rights = 'Kevin Kallaugher'
class Crawle... |
Make reverse migration for lot_type run | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations, connection
from lots.models import LotType, Lot
from revenue.models import Fee, Receipt
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", ... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations
from lots.models import LotType, Lot
from revenue.models import Fee, Receipt
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", "LotType")
... |
Normalize module name before processing | <?php
namespace ZF\ApiFirstAdmin\Model;
use ZF\Configuration\ResourceFactory as ConfigResourceFactory;
use ZF\Configuration\ModuleUtils;
class CodeConnectedRpcFactory
{
/**
* @var ConfigResourceFactory
*/
protected $configFactory;
/**
* @var ModuleUtils
*/
protected $modules;
... | <?php
namespace ZF\ApiFirstAdmin\Model;
use ZF\Configuration\ResourceFactory as ConfigResourceFactory;
use ZF\Configuration\ModuleUtils;
class CodeConnectedRpcFactory
{
/**
* @var ConfigResourceFactory
*/
protected $configFactory;
/**
* @var ModuleUtils
*/
protected $modules;
... |
Set analyst default pprof port to 0 | package config
import (
"log"
"github.com/bradylove/envstruct"
)
type Config struct {
Addr string `env:"ADDR,required"`
IntraAddr string `env:"INTRA_ADDR,required"`
TalariaNodeAddr string `env:"TALARIA_NODE_ADDR,required"`
TalariaSchedulerAddr string `env:"TALARIA_SCHEDU... | package config
import (
"log"
"github.com/bradylove/envstruct"
)
type Config struct {
Addr string `env:"ADDR,required"`
IntraAddr string `env:"INTRA_ADDR,required"`
TalariaNodeAddr string `env:"TALARIA_NODE_ADDR,required"`
TalariaSchedulerAddr string `env:"TALARIA_SCHEDU... |
Set light timer 1 hr back, 10pm-12am | import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = contro... | import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = contro... |
Reduce memory consumption by releasing binaries after a class is loaded | package loop;
import loop.runtime.Caller;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
public class LoopClassLoader extends ClassLoader {
final ConcurrentMap<String, byte[]> rawClasses = new ConcurrentHashMap<Stri... | package loop;
import loop.runtime.Caller;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
public class LoopClassLoader extends ClassLoader {
final ConcurrentMap<String, byte[]> rawClasses = new ConcurrentHashMap<Stri... |
Add Development Status :: 7 - Inactive classifier. | import os
import sys
from setuptools import setup, Extension
with open("README.rst") as fp:
long_description = fp.read()
extensions = []
if os.name == 'nt':
ext = Extension(
'trollius._overlapped', ['overlapped.c'], libraries=['ws2_32'],
)
extensions.append(ext)
requirements = ['six']
if sys.... | import os
import sys
from setuptools import setup, Extension
with open("README.rst") as fp:
long_description = fp.read()
extensions = []
if os.name == 'nt':
ext = Extension(
'trollius._overlapped', ['overlapped.c'], libraries=['ws2_32'],
)
extensions.append(ext)
requirements = ['six']
if sys.... |
Modify arguments of post function | michishiki.api = {};
michishiki.api.uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/';
michishiki.api.getPost = function(options) {
var dfd = $.Deferred();
var api_uri = michishiki.api.uri + 'get_post.py';
var query_string = michishiki.api.utils.optionsToQueryString(options);
... | michishiki.api = {};
michishiki.api.uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/';
michishiki.api.getPost = function(options) {
var dfd = $.Deferred();
var api_uri = michishiki.api.uri + 'get_post.py';
var query_string = michishiki.api.utils.optionsToQueryString(options);
... |
Use global classes for easier testing | // Webpack config to serve the JSX component with bundled styles
import path from 'path';
const demoPath = path.join(__dirname, './demo');
const sourcePath = path.join(__dirname, './src');
export default {
entry: {
js: [demoPath.concat('/render.js')],
},
output: {
path: demoPath,
filename: 'bundle.... | // Webpack config to serve the JSX component with bundled styles
import path from 'path';
const demoPath = path.join(__dirname, './demo');
const sourcePath = path.join(__dirname, './src');
export default {
entry: {
js: [demoPath.concat('/render.js')],
},
output: {
path: demoPath,
filename: 'bundle.... |
Increase payload limit to 1.5MB
When editing a model, this allow the user to upload a 1MB file, rather
than something like a 925.3kB file, along with about 500kB of
description text. | import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
... | import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
... |
Fix noqa location, bump version | """
Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon
"""
import logging
# Add NullHandler to prevent logging warnings
logging.getLogger(__name__).addHandler(logging.NullHandler())
from rejected.consumer import ( # noqa: E402
Consumer,
ConsumerException,
MessageException,
Proces... | """
Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon
"""
import logging
# Add NullHandler to prevent logging warnings
logging.getLogger(__name__).addHandler(logging.NullHandler())
from rejected.consumer import (
Consumer,
ConsumerException,
MessageException,
ProcessingException,... |
feat(app): Improve electron template on devtools usage | import { app, BrowserWindow, nativeTheme } from 'electron'
import path from 'path'
try {
if (process.platform === 'win32' && nativeTheme.shouldUseDarkColors === true) {
require('fs').unlinkSync(require('path').join(app.getPath('userData'), 'DevTools Extensions'))
}
} catch (_) { }
let mainWindow
function cre... | import { app, BrowserWindow, nativeTheme } from 'electron'
import path from 'path'
try {
if (process.platform === 'win32' && nativeTheme.shouldUseDarkColors === true) {
require('fs').unlinkSync(require('path').join(app.getPath('userData'), 'DevTools Extensions'))
}
} catch (_) { }
let mainWindow
function cre... |
Create logs directory if not exists | 'use strict';
const fs = require('fs');
const path = require('path');
const bunyan = require('bunyan');
const config = require('config');
const pkg = require('../../package.json');
const level = process.env.LOG_LEVEL || (config.has('logger.level') ? config.get('logger.level') : 'info');
try {
fs.access(config.... | 'use strict';
const path = require('path');
const bunyan = require('bunyan');
const config = require('config');
const pkg = require('../../package.json');
const level = process.env.LOG_LEVEL || (config.has('logger.level') ? config.get('logger.level') : 'info');
module.exports = bunyan.createLogger({
name: pkg.n... |
Add use of Game.character.current_location to example | from vengeance.game import Direction
from vengeance.game import Game
from vengeance.game import Location
go_up = Direction('up')
go_down = Direction('down')
go_up.opposite = go_down
go_in = Direction('in')
go_out = Direction('out')
go_in.opposite = go_out
go_west = Direction('west')
go_east = Direction('east')
go_we... | from vengeance.game import Direction
from vengeance.game import Game
from vengeance.game import Location
go_up = Direction('up')
go_down = Direction('down')
go_up.opposite = go_down
go_in = Direction('in')
go_out = Direction('out')
go_in.opposite = go_out
go_west = Direction('west')
go_east = Direction('east')
go_we... |
Add sessions reducer to main reducer | import { combineReducers } from 'redux';
import audio from '../containers/Audio/reducer';
import midi from '../containers/Midi/reducer';
import login from '../containers/Login/reducer';
import map from '../containers/Map/reducer';
import messagesBox from '../containers/MessagesBox/reducer';
import metronome from '../co... | import { combineReducers } from 'redux';
import audio from '../containers/Audio/reducer';
import midi from '../containers/Midi/reducer';
import login from '../containers/Login/reducer';
import map from '../containers/Map/reducer';
import messagesBox from '../containers/MessagesBox/reducer';
import metronome from '../co... |
Fix for non-existent character folder bug | import os
import json
from serializable import Serializable
class Saves: #Only partially implemembted- only works for PlayerCharacters
#Because we want the user to be able to play on whatever world they want with whatever character
#they want, characters have to be stored independently of everything else
#We nee... | import os
import json
from serializable import Serializable
class Saves: #Only partially implemembted- only works for PlayerCharacters
#Because we want the user to be able to play on whatever world they want with whatever character
#they want, characters have to be stored independently of everything else
#We nee... |
Use local database namespace instead of package. | from flask_sqlalchemy import Model
from __init__ import db
class User(Model):
__tablename__ = "user"
ROLE_ADMIN = 0
ROLE_USER = 1
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(64), index=True)
username = db.Column(db.Unicode(20), index=True)
password_hash = db.Co... | from flask_sqlalchemy import Model
from sqlalchemy import Column, Integer, Unicode, UnicodeText, ForeignKey
from sqlalchemy.orm import relationship
class User(Model):
__tablename__ = "user"
ROLE_ADMIN = 0
ROLE_USER = 1
id = Column(Integer, primary_key=True)
name = Column(Unicode(64), index=True)
... |
Add missing comment and remove another redundant one | <?php
declare (strict_types = 1);
namespace Mihaeu\PhpDependencies;
use PhpParser\Parser as BaseParser;
class Parser
{
/** @var BaseParser */
private $parser;
/**
* @param $parser
*/
public function __construct(BaseParser $parser)
{
$this->parser = $parser;
}
/**
... | <?php
declare (strict_types = 1);
namespace Mihaeu\PhpDependencies;
use PhpParser\Parser as BaseParser;
class Parser
{
/** @var BaseParser */
private $parser;
/**
* Parser constructor.
*
* @param $parser
*/
public function __construct(BaseParser $parser)
{
$this->par... |
[Chaco] Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples | from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_... | from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from drag_zoom import DragZoom
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import... |
Add test for page that redirects | package com.opera.core.systems;
import org.junit.Assert;
import org.junit.Test;
public class NavigationTest extends TestBase
{
@Test
public void testBack()
{
getFixture("javascript.html");
getFixture("test.html");
getFixture("keys.html");
driver.navigate().back();
Assert.assertTrue(driver.getCur... | package com.opera.core.systems;
import org.junit.Assert;
import org.junit.Test;
public class NavigationTest extends TestBase
{
@Test
public void testBack()
{
getFixture("javascript.html");
getFixture("test.html");
getFixture("keys.html");
driver.navigate().back();
Assert.assertTrue(driver.getCur... |
Support for two headers with same name.
I found an example file with two different firmware version header lines. This caused a React error due to duplicate item keys.
Fixed by appending the index to the name. | import React, { PropTypes } from 'react';
import { Table } from 'react-bootstrap';
import { List } from 'immutable';
import moment from 'moment';
import HeaderRow from './HeaderRow';
function HeaderDisplay(props) {
let headers = props.headers;
const rows = headers.map((h, index) => {
const name = h.get('name'... | import React, { PropTypes } from 'react';
import { Table } from 'react-bootstrap';
import { List } from 'immutable';
import moment from 'moment';
import HeaderRow from './HeaderRow';
function HeaderDisplay(props) {
let headers = props.headers;
const rows = headers.map(h => {
const name = h.get('name');
co... |
Add source credit too footer. | import React from 'react';
class Footer extends React.Component {
render() {
// jshint ignore:start
return (
<footer>
<div className="logo" />
<h4>Holder de ord © 2014 - {new Date().getFullYear()}</h4>
<div>Referater fra <a href="htt... | import React from 'react';
class Footer extends React.Component {
render() {
// jshint ignore:start
return (
<footer>
<div className="logo" />
<h4>Holder de ord © 2014 - {new Date().getFullYear()}</h4>
<div>
<a hre... |
Fix failing runtime compiler tests | package org.twig.compiler;
import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigRuntimeException;
import org.twig.template.Template;
public class RuntimeTemplateCompilerTests {
@Test
public void testCompileJavaCode() throws TwigRuntimeException {
R... | package org.twig.compiler;
import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigRuntimeException;
import org.twig.template.Template;
public class RuntimeTemplateCompilerTests {
@Test
public void testCompileJavaCode() throws TwigRuntimeException {
R... |
Check final count of statements. | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations... | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations... |
Transform values in string.Template engine before substitution. | #!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, *... | #!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, ... |
Fix a bug introduced in the last commit | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
def appid():
if have_appserver:
return get_application_id()
else:
try:
from .boot... |
Change transform option to jsx and not ts | module.exports = {
transform: {
"^.+\\.jsx?$": `<rootDir>/jest-preprocess.js`,
},
moduleNameMapper: {
".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`
},
testPathIgno... | module.exports = {
transform: {
"^.+\\.[jt]sx?$": "<rootDir>/jest-preprocess.js",
},
moduleNameMapper: {
".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`
},
testPathI... |
Update Grunt deploy to use bundle | module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
secret: grunt.file.readJSON('secret.json'),
// TODO: This won't rm removed resources automatically!
sftp: {
options: {
path: '<%= secret.path %>',
host: '<%= secret.host %>',
usernam... | module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
secret: grunt.file.readJSON('secret.json'),
// TODO: This won't rm removed resources automatically!
sftp: {
options: {
path: '<%= secret.path %>',
host: '<%= secret.host %>',
usernam... |
Revert "added version for templating"
This reverts commit 57693cd93e51b1ddcedb6be33a8e125c431371e5. | Package.describe({
name: 'ox2:chart',
summary: 'TESTING_DO_NOT_USE Chart components',
version: '2.0.0',
git: ' /* Fill me in! */ '
});
var S = 'server';
var C = 'client';
var CS = [C, S];
Npm.depends({
'chart.js': '2.6.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.4');
// Core
api.use([
... | Package.describe({
name: 'ox2:chart',
summary: 'TESTING_DO_NOT_USE Chart components',
version: '2.0.0',
git: ' /* Fill me in! */ '
});
var S = 'server';
var C = 'client';
var CS = [C, S];
Npm.depends({
'chart.js': '2.6.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.3.1');
// Core
api.use(... |
Add @MappedSuperclass so user information is serialized. | package models;
import java.util.List;
import java.util.UUID;
import javax.persistence.MappedSuperclass;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* The base class for all of the models used by GTFS Data Manager.
* We don't use the Play model object because we're not saving things to a relational da... | package models;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* The base class for all of the models used by GTFS Data Manager.
* We don't use the Play model object because we're not saving things to a relational database.
* @author mattwigway
*/
public abs... |
Set research level in ticker | """Process queues."""
from datetime import datetime
from server.extensions import db
from server.models import QueueEntry
def finished_entries():
"""Process finished entries."""
queue_entries = db.session.query(QueueEntry) \
.filter(QueueEntry.finishes_at <= datetime.now()) \
.all()
for ... | """Process queues."""
from datetime import datetime
from server.extensions import db
from server.models import QueueEntry
def finished_entries():
"""Process finished entries."""
queue_entries = db.session.query(QueueEntry) \
.filter(QueueEntry.finishes_at <= datetime.now()) \
.all()
for ... |
Add hint on improved API in 7.2 | package com.camunda.bpm.demo.extension_attributes_for_user_tasks;
import java.util.Collection;
import java.util.Date;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpm... | package com.camunda.bpm.demo.extension_attributes_for_user_tasks;
import java.util.Collection;
import java.util.Date;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpm... |
Make Nodes use TextLayoutBuilder's LayoutMeasureUtil
Summary:
Make Nodes use TextLayoutBuilder's LayoutMeasureUtil.
This cuts down a dependency.
Reviewed By: ahmedre
Differential Revision: D4151599 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package co... | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package co... |
Add name filter to expert requests [WAL-989] | import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
... | import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
... |
Use compression on server side | const express = require('express');
const compression = require('compression');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
const Metascraper = require('metascraper');
// gzip the static resources before seding to browser, if the browser supports gzip compression
// Ve... | const express = require('express');
const compression = require('compression');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
const Metascraper = require('metascraper');
// gzip the static resources before seding to browser, if the browser supports gzip compression
// Ve... |
Fix Node 10 localstorage in tests | // 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
// distributed un... | // 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
// distributed un... |
Fix: Make source of error clear in the message | /*
* Cordova Device Name Plugin
*
* ZeroConf plugin for Cordova/Phonegap
* by Sylvain Brejeon
*/
var argscheck = require('cordova/argscheck');
var channel = require('cordova/channel');
var utils = require('cordova/utils');
var exec = require('cordova/exec');
var cordova = require('cordova');
channel.createStick... | /*
* Cordova Device Name Plugin
*
* ZeroConf plugin for Cordova/Phonegap
* by Sylvain Brejeon
*/
var argscheck = require('cordova/argscheck');
var channel = require('cordova/channel');
var utils = require('cordova/utils');
var exec = require('cordova/exec');
var cordova = require('cordova');
channel.createStick... |
Fix DiscoveryManager for DI tests | package com.netflix.appinfo.providers;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.archaius.api.Config;
import com.netflix.discovery.DiscoveryManager;
import javax.inject.Inject;
import javax.in... | package com.netflix.appinfo.providers;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.archaius.api.Config;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
... |
Set the Project in code | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
FIX: Remove outdated function from list. | """
This module defines styles redefine matplotlib rc parameters. In addition, you
can override pre-defined styles with "mplstyle" files in the current
directory and your home directory. The priority of style files is:
1. ./mplstyle
2. ~/.mplstyle
3. mpltools/style/
Style names should be specified as sect... | """
This module defines styles redefine matplotlib rc parameters. In addition, you
can override pre-defined styles with "mplstyle" files in the current
directory and your home directory. The priority of style files is:
1. ./mplstyle
2. ~/.mplstyle
3. mpltools/style/
Style names should be specified as sect... |
Fix bad typo (doesn't fix bug) | /*
* Copyright 2016 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | /*
* Copyright 2016 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
Replace function calls with set literals | import hashlib
class Algorithms(object):
NONE = 'none'
HS256 = 'HS256'
HS384 = 'HS384'
HS512 = 'HS512'
RS256 = 'RS256'
RS384 = 'RS384'
RS512 = 'RS512'
ES256 = 'ES256'
ES384 = 'ES384'
ES512 = 'ES512'
HMAC = {HS256, HS384, HS512}
RSA = {RS256, RS384, RS512}
EC = {ES2... | import hashlib
class Algorithms(object):
NONE = 'none'
HS256 = 'HS256'
HS384 = 'HS384'
HS512 = 'HS512'
RS256 = 'RS256'
RS384 = 'RS384'
RS512 = 'RS512'
ES256 = 'ES256'
ES384 = 'ES384'
ES512 = 'ES512'
HMAC = set([HS256, HS384, HS512])
RSA = set([RS256, RS384, RS512])
... |
Fix for reflected XSS security issue. | <?php
// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');
if ($setting->getValue('maintenance') && !$user->isAdmin($user->getUserId($_POST['username']))) {
$_SESSION['POPUP'][] = array('CONTENT' => 'You are not allowed to login during maintenace.', 'TYPE' => 'info');
} else i... | <?php
// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');
if ($setting->getValue('maintenance') && !$user->isAdmin($user->getUserId($_POST['username']))) {
$_SESSION['POPUP'][] = array('CONTENT' => 'You are not allowed to login during maintenace.', 'TYPE' => 'info');
} else i... |
Add URL and long-desc to metadata | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='pytest-relaxed',
version='0.0.1',
description='Relaxed test discovery/organization for pytest',
license='BSD',
url="https://github.com/bitprophet/pytest-relaxed",
author='Jeff Forcier',
author_email='jeff@bitpr... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='pytest-relaxed',
version='0.0.1',
description='Relaxed test discovery/organization for pytest',
license='BSD',
author='Jeff Forcier',
author_email='jeff@bitprophet.org',
packages=find_packages(),
entry_poi... |
Remove ES6 from ws/factor for stupid old browsers | var isNode = typeof window === 'undefined';
var WebSocket = isNode ? require('ws') : window.WebSocket;
/**
* Wraps a DOM socket with EventEmitter-like syntax.
* @param {Socket} socket
* @return {Socket}
*/
function wrapDOM(socket) {
function wrapHandler(event, fn) {
return function(ev) {
i... | var isNode = typeof window === 'undefined';
var WebSocket = isNode ? require('ws') : window.WebSocket;
/**
* Wraps a DOM socket with EventEmitter-like syntax.
* @param {Socket} socket
* @return {Socket}
*/
function wrapDOM(socket) {
function wrapHandler(event, fn) {
return (ev) => {
if (ev... |
Switch to hash-based history, fix redirect to /build on boot | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, Redirect } from 'react-router';
import { syncReduxAndRouter } from 'redux-simple-router';
import createHashHistory from 'history/lib/createHashHistory';
import createStore from './store';
import ... | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, Redirect } from 'react-router';
import { syncReduxAndRouter } from 'redux-simple-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import createStore from './store';
i... |
Add more time to mqtt.test.client | import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalP... | import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalP... |
Fix typo in sg context menu selector | "use strict";
angular.module('arethusa.sg').directive('sgContextMenuSelector', [
'sg',
function(sg) {
return {
restrict: 'A',
scope: {
obj: '='
},
link: function(scope, element, attrs) {
scope.sg = sg;
function ancestorChain(chain) {
return arethusaUti... | "use strict";
angular.module('arethusa.sg').directive('sgContextMenuSelector', [
'sg',
function(sg) {
return {
restrict: 'A',
scope: {
obj: '='
},
link: function(scope, element, attrs) {
scope.sg = sg;
function ancestorChain(chain) {
arethusaUtil.map(c... |
Fix undefined in homepage, bugs and repo url | 'use strict';
/**
* Ask for Github account info.
*/
module.exports = function () {
const done = this.async();
let suggestedGithubUsername;
if (this.authorName && 'string' === typeof this.authorName) {
suggestedGithubUsername = this.authorName.toLowerCase().replace(/\s/g, '');
}
this.prompt([
{
... | 'use strict';
/**
* Ask for Github account info.
*/
module.exports = function () {
const done = this.async();
let suggestedGithubUsername;
if (this.authorName && 'string' === typeof this.authorName) {
suggestedGithubUsername = this.authorName.toLowerCase().replace(/\s/g, '');
}
this.prompt([
{
... |
Add check around splashscreen object
Minor cleanup.
From: https://gist.github.com/jperl/60d02a5d4301c1e29eec | // Hook into the hot-reload to
// 1) wait until the application has resumed to reload the app
// 2) show the splashscreen while the app is reloading
var hasResumed = false;
var retryReloadFunc = null;
var retryReloadOnResume = function () {
// Set hasResumed to true so _onMigrate performs the reload
hasResumed = ... | // Hook into the hot-reload to
// 1) wait until the application has resumed to reload the app
// 2) show the splashscreen while the app is reloading
var hasResumed = false;
var retryReloadFunc = null;
var retryReloadOnResume = function () {
// Set resumed to true so _onMigrate performs the reload
hasResumed = tru... |
Fix value assigned when marking interface as having no properties
See #142. Thanks @angrybrad | <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\models;
/**
* Represents API documentation information for an `interface`.
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class In... | <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\models;
/**
* Represents API documentation information for an `interface`.
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class In... |
Change version because of an important bugfix | #!/usr/bin/env python
"""Package setup script; requires setuptools (or Python >=3.4 which
bundles it)."""
from setuptools import setup
setup(name='Treepace',
version='0.3',
description='Tree Transformation Language',
author='Matúš Sulír',
url='https://github.com/sulir/treepace',
package... | #!/usr/bin/env python
"""Package setup script; requires setuptools (or Python >=3.4 which
bundles it)."""
from setuptools import setup
setup(name='Treepace',
version='0.2',
description='Tree Transformation Language',
author='Matúš Sulír',
url='https://github.com/sulir/treepace',
package... |
Add CORS headers to main studio Flask application, to allow initial API version request
Remove before_request from main application | import webbrowser
from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer
from qiime_studio.api.security import make_url
from qiime_studio.api.cors import add_cors_headers
from qiime_studio.api.v1 import v1
from qiime_studio.static import static_files
studio = Flask('qiime_studio')
studio.register_blue... | import webbrowser
from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer
from qiime_studio.api.security import make_url
from qiime_studio.api.v1 import v1
from qiime_studio.static import static_files
studio = Flask('qiime_studio')
studio.register_blueprint(v1, url_prefix='/api/0.0.1')
studio.debug = T... |
Change ping trigger to need exclaimation point | const Discord = require('discord.io');
const bot = new Discord.Client({
token: process.env.DISCORD_TOKEN,
autorun: true,
});
const previousMessages = [];
bot.on('ready', () => {
console.log('Logged in as %s - %s\n', bot.username, bot.id);
});
bot.on('disconnect', () => {
bot.connect();
});
bot.on('message'... | const Discord = require('discord.io');
const bot = new Discord.Client({
token: process.env.DISCORD_TOKEN,
autorun: true,
});
const previousMessages = [];
bot.on('ready', () => {
console.log('Logged in as %s - %s\n', bot.username, bot.id);
});
bot.on('disconnect', () => {
bot.connect();
});
bot.on('message'... |
Move NumPy dependency to optional rastertoolz dependency | import os.path
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.... | import os.path
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.... |
Fix tests. Add SSL test. | package irc
import (
// "github.com/thoj/go-ircevent"
"testing"
)
func TestConnection(t *testing.T) {
irccon := IRC("go-eventirc", "go-eventirc")
irccon.VerboseCallbackHandler = true
err := irccon.Connect("irc.freenode.net:6667")
if err != nil {
t.Fatal("Can't connect to freenode.")
}
irccon.AddCallback("00... | package irc
import (
// irc "github.com/thoj/Go-IRC-Client-Library"
"fmt"
"testing"
)
func TestConnection(t *testing.T) {
irccon := IRC("invisible", "invisible")
fmt.Printf("Testing connection\n")
err := irccon.Connect("irc.freenode.net:6667")
fmt.Printf("Connecting...")
if err != nil {
t.Fatal("Can't ... |
Build vehicle with motor hat. | from Adafruit_MotorHAT import Adafruit_MotorHAT
class Vehicle:
def __init__(self, motor_hat=Adafruit_MotorHAT()):
self.motor_hat = motor_hat
self.motors = []
def release(self):
self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(2).run(Adafruit_Mo... | from Adafruit_MotorHAT import Adafruit_MotorHAT
class Vehicle:
def __init__(self, motor_hat=None):
self.motor_hat = motor_hat
self.motors = []
def release(self):
self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)... |
Fix test after changing array structure | from __future__ import print_function
from numba.ctypes_support import *
import numpy
import numba.unittest_support as unittest
from numba._numpyadapt import get_ndarray_adaptor
class ArrayStruct3D(Structure):
_fields_ = [
("data", c_void_p),
("shape", (c_ssize_t * 3)),
("strides", (c_ssiz... | from __future__ import print_function
from numba.ctypes_support import *
import numpy
import numba.unittest_support as unittest
from numba._numpyadapt import get_ndarray_adaptor
class ArrayStruct3D(Structure):
_fields_ = [
("data", c_void_p),
("shape", (c_ssize_t * 3)),
("strides", (c_ssiz... |
Change constant variables to fit new template | import string
ROWS = 12
COLUMNS = 14
TMPL_OPTIONS = {
'page-size': 'Letter'
}
PERCENTAGE_TO_CROP_SCAN_IMG = 0.005
PERCENTAGE_TO_CROP_CHAR_IMG = 0.1
CROPPED_IMG_NAME = "cropped_picture.bmp"
CUT_CHAR_IMGS_DIR = "cutting_output_images"
MAX_COLUMNS_PER_PAGE = 14
MAX_ROWS_PER_PAEG = 12
RELA_PIXELS_CHARACTER_BAR_HEIG... | import string
ROWS = 12
COLUMNS = 14
TMPL_OPTIONS = {
'page-size': 'Letter'
}
PERCENTAGE_TO_CROP_SCAN_IMG = 0.005
PERCENTAGE_TO_CROP_CHAR_IMG = 0.1
CROPPED_IMG_NAME = "cropped_picture.bmp"
CUT_CHAR_IMGS_DIR = "cutting_output_images"
MAX_COLUMNS_PER_PAGE = 14
MAX_ROWS_PER_PAEG = 12
RELA_PIXELS_CHARACTER_BAR_HEIG... |
Adjust doc to be more google like | package cfgfile
import (
"flag"
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
// Command line flags
var configfile *string
var testConfig *bool
func CmdLineFlags(flags *flag.FlagSet, name string) {
configfile = flags.String("c", fmt.Sprintf("/etc/%s/%s.yml", name, name), "Configuration file")
testConfig = flags.Bool... | package cfgfile
import (
"flag"
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
// Command line flags
var configfile *string
var testConfig *bool
func CmdLineFlags(flags *flag.FlagSet, name string) {
configfile = flags.String("c", fmt.Sprintf("/etc/%s/%s.yml", name, name), "Configuration file")
testConfig = flags.Bool... |
Make _CustomAnalyzer a private class | from hoomd.python_action import _PythonAction, _InternalPythonAction
from hoomd.custom_action import _CustomAction, _InternalCustomAction
class _CustomAnalyzer(_CustomAction):
def analyze(self, timestep):
return self.act(timestep)
class _InternalCustomAnayzer(_InternalCustomAction):
def analyze(self... | from hoomd.python_action import _PythonAction, _InternalPythonAction
from hoomd.custom_action import _CustomAction, _InternalCustomAction
class CustomAnalyzer(_CustomAction):
def analyze(self, timestep):
return self.act(timestep)
class _InternalCustomAnayzer(_InternalCustomAction):
def analyze(self,... |
Update plugin information (name, description, version, author) | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import OctoPrintOutputDevicePlugin
from . import DiscoverOctoPrintAction
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "extension",
"plugin": {
... | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import OctoPrintOutputDevicePlugin
from . import DiscoverOctoPrintAction
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "extension",
"plugin": {
... |
Enable users management in SQU mode (SAAS-787) | 'use strict';
angular.module('ncsaas')
.constant('MODE', {
modeName: 'modeSquStudentCloud',
toBeFeatures: [
'monitoring',
'backups',
'password',
'services',
'providers',
'premiumSupport',
'servicesadd',
'import',
'templates',
'monitoring',
'pr... | 'use strict';
angular.module('ncsaas')
.constant('MODE', {
modeName: 'modeSquStudentCloud',
toBeFeatures: [
'monitoring',
'backups',
'password',
'services',
'providers',
'premiumSupport',
'users',
'people',
'servicesadd',
'import',
'templates'... |
Set "public static void" for "main" :thumbsup: | public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
... | public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
... |
Add comment to domain stripping regular experssion
For all of those who don't speak Kleene star | var WebFont = require("webfont"),
stripDomain = new RegExp("^(.*://[^/]*/)?(.*)$");
// scheme^ domain^ font^
exports.locate = function(load) {
return decodeURI(load.name.match(stripDomain)[2]);
}
exports.fetch = function(load) {
return new Promise(function(resolve, reject) {
var fo... | var WebFont = require("webfont"),
stripDomain = new RegExp("^(.*://[^/]*/)?(.*)$");
exports.locate = function(load) {
return decodeURI(load.name.match(stripDomain)[2]);
}
exports.fetch = function(load) {
return new Promise(function(resolve, reject) {
var fontName = load.address.split(" ")[0],
para... |
Make local variable name more concise. | // Copyright © 2011 - 2013 Forerunner Games
package com.forerunnergames.tools;
/**
*
* @author Aaron Mahan
*/
public class Point2D
{
public Point2D (final int x, final int y)
{
x_ = x;
y_ = y;
}
@Override
public boolean equals (Object object)
{
if (this == object)
{
return true;
... | // Copyright © 2011 - 2013 Forerunner Games
package com.forerunnergames.tools;
/**
*
* @author Aaron Mahan
*/
public class Point2D
{
public Point2D (final int x, final int y)
{
x_ = x;
y_ = y;
}
@Override
public boolean equals (Object object)
{
if (this == object)
{
return true;
... |
Correct the version number in LiSE too | # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools i... | # This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools i... |
Handle that Path can be none | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s... | import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s... |
Fix JS validation. No idea why it doesn't work the other way. Bleh. | (function($) {
$(document).ready(function() {
$('.player-link').click(function(e) {
$.get($(this).attr('href'));
e.preventDefault();
});
$('#uploader input').change(validateUploadForm);
$('#uploader input[type="text"]').on('keyup', validateUploadForm);
$('#uploader input[type="text"]').on('blur', va... | (function($) {
$(document).ready(function() {
$('.player-link').click(function(e) {
$.get($(this).attr('href'));
e.preventDefault();
});
$('#uploader input').change(validateUploadForm);
$('#uploader input[type="text"]').on('keyup', validateUploadForm);
$('#uploader input[type="text"]').on('blur', va... |
Update the django path to flatatt module | from django import forms
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.forms.utils import flatatt
from django.utils.encoding import force_text
from taggit.utils import parse_tags, edit_string_for_tags
from django.utils import six
class TagsInput(forms.Te... | from django import forms
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.forms.util import flatatt
from django.utils.encoding import force_text
from taggit.utils import parse_tags, edit_string_for_tags
from django.utils import six
class TagsInput(forms.Tex... |
Allow scheme/protocol to be passed to script
Googles GTM now seems to redirect any http request to https, this now causes an extra redirect which seems wasteful.
This proposal is to allow someone to pass in the scheme they desire so someone can always call https if they want.
The alternative would be to always use h... | function convertToKeyValueString(obj) {
return JSON.stringify(obj).slice(1, -1);
}
function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {}, scheme = '' }) {
if (id === undefined) {
throw new Error('No GTM id provided');
}
const iframe = `
<iframe src="${scheme}//ww... | function convertToKeyValueString(obj) {
return JSON.stringify(obj).slice(1, -1);
}
function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {} }) {
if (id === undefined) {
throw new Error('No GTM id provided');
}
const iframe = `
<iframe src="//www.googletagmanager.com... |
controller: Fix break scope in StreamFormations
Signed-off-by: Jonathan Rudenberg <3692bfa45759a67d83aedf0045f6cb635a966abf@titanous.com> | package main
import (
"net/http"
"time"
ct "github.com/flynn/flynn/controller/types"
"github.com/flynn/flynn/pkg/rpcplus"
rpc "github.com/flynn/flynn/pkg/rpcplus/comborpc"
)
func rpcHandler(repo *FormationRepo) http.Handler {
rpcplus.RegisterName("Controller", &ControllerRPC{formations: repo})
return rpc.New(... | package main
import (
"net/http"
"time"
ct "github.com/flynn/flynn/controller/types"
"github.com/flynn/flynn/pkg/rpcplus"
rpc "github.com/flynn/flynn/pkg/rpcplus/comborpc"
)
func rpcHandler(repo *FormationRepo) http.Handler {
rpcplus.RegisterName("Controller", &ControllerRPC{formations: repo})
return rpc.New(... |
Remove unecessary code in cache backend _set | # -*- coding: utf-8 -*-
class BaseCacheBackend(object):
def get(self, thumbnail_name):
if isinstance(thumbnail_name, list):
thumbnail_name = ''.join(thumbnail_name)
return self._get(thumbnail_name)
def set(self, thumbnail):
return self._set(thumbnail.name, thumbnail)
... | # -*- coding: utf-8 -*-
class BaseCacheBackend(object):
def get(self, thumbnail_name):
if isinstance(thumbnail_name, list):
thumbnail_name = ''.join(thumbnail_name)
return self._get(thumbnail_name)
def set(self, thumbnail):
thumbnail_name = thumbnail.name
if isins... |
Document self-usage of public methods per `Effective Java` | /*
* #%L
* Simmetrics Core
* %%
* Copyright (C) 2014 - 2016 Simmetrics Authors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.... | /*
* #%L
* Simmetrics Core
* %%
* Copyright (C) 2014 - 2016 Simmetrics Authors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.... |
ENH: Add diagnose to f2py package. This makes the tests a bit easier to fix. | #!/usr/bin/env python
__all__ = ['run_main','compile','f2py_testing']
import os
import sys
import commands
import f2py2e
import f2py_testing
import diagnose
from info import __doc__
run_main = f2py2e.run_main
main = f2py2e.main
def compile(source,
modulename = 'untitled',
extra_args = '',
... | #!/usr/bin/env python
__all__ = ['run_main','compile','f2py_testing']
import os
import sys
import commands
from info import __doc__
import f2py2e
run_main = f2py2e.run_main
main = f2py2e.main
import f2py_testing
def compile(source,
modulename = 'untitled',
extra_args = '',
verbo... |
Add serial id to seat | package data.trainnetwork;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* A class representing a Seat within section
* @author Balazs Pete
*
*/
public class Seat implements Serializable {
/**
*
*/
private static final long serialVersionUID = 31972027429... | package data.trainnetwork;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* A class representing a Seat within section
* @author Balazs Pete
*
*/
public class Seat implements Serializable {
private String id, sectionId = null;
/**
* Create a new Seat
* @... |
Simplify and improve -v/-q handling. | """Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, ... | """Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, ... |
Add tests to confirm message retrieval | var chai = require('chai');
var expect = chai.expect;
var db = require('../server/db/config');
var models = require('../server/db/models');
describe('database storage', function() {
var testData = {
x: 37.783599,
y: -122.408974,
z: 69,
message: 'Brooks was here'
};
var invalidTestData = {
x: ... | var chai = require('chai');
var expect = chai.expect;
var db = require('../server/db/config');
var models = require('../server/db/models');
describe('database storage', function() {
var testData = {
x: 37.783599,
y: -122.408974,
z: 69,
message: 'Brooks was here'
};
var invalidTestData = {
x: ... |
Switch from go-flags to flag | package main
import (
"flag"
)
type Option struct {
Delimiter string
UseRegexp bool
Count int
Margin string
Justify string
IsHelp bool
IsVersion bool
Files []string
}
func ParseOption(args []string) (*Option, error) {
opt := &Option{}
f := flag.NewFlagSet("alita", flag.ContinueOnError)
f... | package main
import (
"github.com/jessevdk/go-flags"
)
type Option struct {
Delimiter string `short:"d" long:"delimiter" default:""`
UseRegexp bool `short:"r" long:"regexp" default:"false"`
Count int `short:"c" long:"count" default:"-1"`
Margin string `short:"m" long:"margin" default:"1:1"`... |
Convert to ArrayBuffer for when fs gives back Node buffers. | export const build = false
export function fetch (load) {
if (load.address.substr(0, 8) === 'file:///') {
return System.import('fs').then(function (fs) {
return new Promise(function (resolve, reject) {
fs.readFile(load.address.substr(7), function (err, data) {
if (err) {
rejec... | export const build = false
export function fetch (load) {
if (load.address.substr(0, 8) === 'file:///') {
return System.import('fs').then(function (fs) {
return new Promise(function (resolve, reject) {
fs.readFile(load.address.substr(7), function (err, data) {
if (err) {
rejec... |
Change virtual prop to an instance method | 'use strict';
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// export a mongoose model
var userSchema = new Schema({
userName : String,
passwordDigest : String
});
userSchema.methods.setPassword = function(password) {
var self = this;
var saltPromise = new Pro... | 'use strict';
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// export a mongoose model
var userSchema = new Schema({
userName : String,
passwordDigest : String
});
userSchema.virtual('password').set(function(password) {
var self = this;
var saltPromise = new P... |
Remove unnecessary line from detect | ######################## BEGIN LICENSE BLOCK ########################
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ve... | ######################## BEGIN LICENSE BLOCK ########################
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ve... |
Add empty default implementations for notification service | package net.brutus5000.bireus.service;
import org.jgrapht.GraphPath;
import org.jgrapht.graph.DefaultEdge;
import java.net.URL;
import java.nio.file.Path;
public interface NotificationService {
default void error(String message) {
}
default void beginCheckoutVersion(String version) {
}
default ... | package net.brutus5000.bireus.service;
import org.jgrapht.GraphPath;
import org.jgrapht.graph.DefaultEdge;
import java.net.URL;
import java.nio.file.Path;
public interface NotificationService {
void error(String message);
void beginCheckoutVersion(String version);
void finishCheckoutVersion(String vers... |
Add non undefinded check to team names on GameCard | import React from 'react'
import GameCard from './GameCard'
export default (props) => {
const userId = props.userId
const teams = props.teams
const games = []
const gamesObj = props.games
console.log('teams', teams)
for (let key in gamesObj) {
const game = gamesObj[key]
game.gameKey = key
game... | import React from 'react'
import GameCard from './GameCard'
export default (props) => {
const userId = props.userId
const teams = props.teams
const games = []
const gamesObj = props.games
console.log('teams', teams)
for (let key in gamesObj) {
const game = gamesObj[key]
game.gameKey = key
game... |
Fix script to pass pep8 | #!/usr/bin/env python3
import argparse
import random
import sys
DESCRIPTION = '''Shuffle the arguments received, if called without arguments
the lines read from stdin will be shuffled and printed to
stdout'''
def get_list():
return sys.stdin.readlines()
def print_list(list_):... | #!/usr/bin/env python3
import argparse
import random
import sys
DESCRIPTION = '''Shuffle the arguments received, if called without arguments
the lines read from stdin will be shuffled and printed to
stdout'''
def get_list():
return sys.stdin.readlines()
def print_list(list_):
... |
Update script to include name | // ==UserScript==
// @name WT_Integration
// @namespace https://wholetale.org/
// @version 0.1.1
// @description Mock WT integration
// @author Xarthisius
// @match https://dataverse.harvard.edu/dataset.xhtml*
// @grant none
// ==/UserScript==
$(document).ready(function() {
var ... | // ==UserScript==
// @name WT_Integration
// @namespace https://wholetale.org/
// @version 0.1.0
// @description Mock WT integration
// @author Xarthisius
// @match https://dataverse.harvard.edu/dataset.xhtml*
// @grant none
// ==/UserScript==
$(document).ready(function() {
var ... |
Correct the Message in `skipIfPhp5`
Which said something non-sensical before. | <?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue;
abstract class UnitTestCase extends... | <?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue;
abstract class UnitTestCase extends... |
Fix undefined images when there is file index out of range of available files | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { assetClick } from '../../actions/assets';
import map from 'lodash/map';
import ColorPicker from './colorpicker';
const getImage = (asset, profile, assets) => {
if ( ! assets.data) return;
const color = profile[asset.id].color... | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { assetClick } from '../../actions/assets';
import map from 'lodash/map';
import ColorPicker from './colorpicker';
const getImage = (asset, profile, assets) => {
if ( ! assets.data) return;
const color = profile[asset.id].color... |
Revert "ativation by adress mail"
This reverts commit 16724a7f849b1110103b05f6d964a79dc2af344d. | <?php
require_once(__DIR__. '/class/DatabaseManager.php');
$hostname = "localhost";
$database = "aen";
$username = "root";
$password = "";
try{
$connect = new PDO('mysql:host='.$hostname.';dbname='.$database, $username, $password);
}catch (PDOException $e){
... | <?php
require_once(__DIR__. '/class/DatabaseManager.php');
$hostname = "localhost";
$database = "aen";
$username = "root";
$password = "";
try{
$connect = new PDO('mysql:host='.$hostname.';dbname='.$database, $username, $password);
}catch (PDOException $e){
... |
Add a further path inside /sys to test
On (at least) a Debian "stretch" system, the charliecloud image contains
none of the tested paths inside /sys. This patch adds one that does
exist there.
Signed-off-by: Matthew Vernon <d2337109245c21c6e400ba5f0470cfb01956d9f2@sanger.ac.uk> | #!/usr/bin/env python3
import os.path
import sys
# File in /sys seem to vary between Linux systems. Thus, try a few candidates
# and use the first one that exists. What we want is any file under /sys with
# permissions root:root -rw-------.
sys_file = None
for f in ("/sys/devices/cpu/rdpmc",
"/sys/kernel/mm... | #!/usr/bin/env python3
import os.path
import sys
# File in /sys seem to vary between Linux systems. Thus, try a few candidates
# and use the first one that exists. What we want is any file under /sys with
# permissions root:root -rw-------.
sys_file = None
for f in ("/sys/devices/cpu/rdpmc",
"/sys/kernel/mm... |
Check for null value before appending | package com.hubspot.jinjava.util;
import com.hubspot.jinjava.interpret.OutputTooBigException;
import java.io.Serializable;
import java.util.stream.IntStream;
public class LengthLimitingStringBuilder implements Serializable, CharSequence {
private static final long serialVersionUID = -1891922886257965755L;
privat... | package com.hubspot.jinjava.util;
import com.hubspot.jinjava.interpret.OutputTooBigException;
import java.io.Serializable;
import java.util.stream.IntStream;
public class LengthLimitingStringBuilder implements Serializable, CharSequence {
private static final long serialVersionUID = -1891922886257965755L;
privat... |
Add missing whitespace in license header | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.types;
import java.util.Objects;
/**
* <h1>6 ECMAScript Data Types and Values</h1><br>
* ... | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.types;
import java.util.Objects;
/**
* <h1>6 ECMAScript Data Types and Values</h1><br>
* <... |
Add delete old sessions command | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... p... | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... p... |
Reduce padding for address-list to make it fit on mobile displays | // @flow
import type { AddressMap, KnxAddress } from '../types';
import React from 'react';
import createStore from '../lib/create-store';
import withRedux from 'next-redux-wrapper';
import App from '../components/App';
import WithBusSubsribe from '../components/WithBusSubribe';
import AddressList from '../components... | // @flow
import type { AddressMap, KnxAddress } from '../types';
import React from 'react';
import createStore from '../lib/create-store';
import withRedux from 'next-redux-wrapper';
import App from '../components/App';
import WithBusSubsribe from '../components/WithBusSubribe';
import AddressList from '../components... |
Fix & W3 Validation Fail in a Links | <?php
/**
* Url.php
* Contains the Thinker\Http\Url class
*
* @author Cory Gehr
*/
namespace Thinker\Http;
class Url {
/**
* __construct()
* Constructor for the Thinker\Http\Url class
* This is intentionally private, so that it cannot be
* instantiated
*
* @author Cory Gehr
* @access priv... | <?php
/**
* Url.php
* Contains the Thinker\Http\Url class
*
* @author Cory Gehr
*/
namespace Thinker\Http;
class Url {
/**
* __construct()
* Constructor for the Thinker\Http\Url class
* This is intentionally private, so that it cannot be
* instantiated
*
* @author Cory Gehr
* @access priv... |
Fix a bug in browser detection | // FeatureDetection
// IE 9 or older
const isIE9OrOlder = () => {
return (navigator.appVersion.indexOf('MSIE') !== -1) &&
(parseFloat(navigator.appVersion.split('MSIE')[1]) < 10);
};
// IE 10
const isIE10 = () => {
if (Function('/*@cc_on return document.documentMode===10@*/')()) {
return true;
}
return ... | // FeatureDetection
// IE 9 or older
const isIE9OrOlder = () => {
return (navigator.appVersion.indexOf('MSIE') !== -1) &&
(parseFloat(navigator.appVersion.split('MSIE')[1]) < 10);
};
// IE 10
const isIE10 = () => {
if (Function('/*@cc_on return document.documentMode===10@*/')()) {
return true;
}
return ... |
Allow for ranged enemies to define what exactly they do when they shoot | package com.ezardlabs.lostsector.ai;
import com.ezardlabs.dethsquare.Transform;
import com.ezardlabs.lostsector.ai.RangedBehaviour.Builder.ShootAction;
public class RangedBehaviour extends Behaviour {
private final float range;
private final ShootAction shootAction;
RangedBehaviour(float moveSpeed, boolean willPa... | package com.ezardlabs.lostsector.ai;
import com.ezardlabs.dethsquare.Transform;
public class RangedBehaviour extends Behaviour {
private final float range;
RangedBehaviour(float moveSpeed, boolean willPatrol, float visionRange, float range) {
super(moveSpeed, willPatrol, visionRange);
this.range = range;
}
... |
Fix neutron server crash introduced by trunk code
When running pre-stable/ocata neutron code the networking_cisco trunk
code was crashing due to incorrect backwards_compatibility implementation.
Change-Id: I8188f8d16313166418d207c99124e2763eb669a1 | # Copyright (c) 2017 Cisco Systems, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | # Copyright (c) 2017 Cisco Systems, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.