text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Implement unregistration of configuration plug-ins
Perhaps we should not give a warning, but instead an exception, when registering or unregistering fails? | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... |
Fix query. Has to use java.util.Date | package ch.rasc.eds.starter.schedule;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.mongodb.clie... | package ch.rasc.eds.starter.schedule;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.mongodb.client.model.Filters;
impor... |
Use a static field for tracking wifi connected state | package nl.rmokveld.castnotifications;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
public class WifiStateReceiver extends BroadcastReceiver {
private static final String TAG = "WifiSt... | package nl.rmokveld.castnotifications;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
public class WifiStateReceiver extends BroadcastReceiver {
private static final String TAG = "WifiStateReceiver";
private Boolea... |
Add rating field to User model | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... |
Fix null response issue with sitemap | package burp;
public class BHttpRequestResponseFactory {
public static BHttpRequestResponse create(IHttpRequestResponse requestResponse,
IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers) {
BHttpRequestResponse bHttpRequestResponse = new BHttpReques... | package burp;
public class BHttpRequestResponseFactory {
public static BHttpRequestResponse create(IHttpRequestResponse requestResponse,
IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers) {
BHttpRequestResponse bHttpRequestResponse = new BHttpReques... |
Use two values in the state for editor & frameList
This reduces confusion between what is currently rendering.
This will avoid duck type checks in the view and allow the
rendering wrapper to have a slightly different container
for each type of widget. | var mercury = require("mercury")
var FrameList = require("./views/frame-list")
var FrameEditor = require("./views/frame-editor")
var FrameData = require("./data/frames")
// Load the data
var initialFrameData = FrameData.load()
// Create the default view using the frame set
var frameList = FrameList(frames)
var stat... | var mercury = require("mercury")
var FrameList = require("./views/frame-list")
var FrameEditor = require("./views/frame-editor")
var FrameData = require("./data/frames")
// Load the data
var initialFrameData = FrameData.load()
// Create the default view using the frame set
var frameList = FrameList(frames)
var stat... |
Update to reflect the move of all goa middlewares to the goa-middleware repo | // +build !appengine
package main
import (
"github.com/raphael/goa"
"github.com/raphael/goa-cellar/app"
"github.com/raphael/goa-cellar/controllers"
"github.com/raphael/goa-cellar/js"
"github.com/raphael/goa-cellar/schema"
"github.com/raphael/goa-cellar/swagger"
"github.com/raphael/goa-middleware/middleware"
)
... | // +build !appengine
package main
import (
"github.com/raphael/goa"
"github.com/raphael/goa-cellar/app"
"github.com/raphael/goa-cellar/controllers"
"github.com/raphael/goa-cellar/js"
"github.com/raphael/goa-cellar/schema"
"github.com/raphael/goa-cellar/swagger"
)
func main() {
// Create goa service
service :... |
Remove auto include of numpy namespace. | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... |
Return empty array when findAll returns undefined from DB | 'use strict';
var SQliteAdapter = require('services/sqlite_adapter');
var Container = function() {
SQliteAdapter.call(this, 'containers');
this.schemaAttrs = ['id', 'container_name'];
};
Container.prototype = Object.create(SQliteAdapter.prototype);
Container.prototype.find = function(attrs) {
attrs = attrs ||... | 'use strict';
var SQliteAdapter = require('services/sqlite_adapter');
var Container = function() {
SQliteAdapter.call(this, 'containers');
this.schemaAttrs = ['id', 'container_name'];
};
Container.prototype = Object.create(SQliteAdapter.prototype);
Container.prototype.find = function(attrs) {
attrs = attrs ||... |
Add 'images' object to the client. | var apiUrls = require('./lib/utils/apis.js');
exports.createClient = function(options) {
var options = {
accessToken: options.accessToken,
apiUrls: apiUrls
};
return {
constants : require('./lib/utils/constants.js'),
contacts : require('./lib/contacts/').create(options),
favorites : requi... | var apiUrls = require('./lib/utils/apis.js');
exports.createClient = function(options) {
var options = {
accessToken: options.accessToken,
apiUrls: apiUrls
};
return {
constants : require('./lib/utils/constants.js'),
contacts : require('./lib/contacts/').create(options),
favorites : requi... |
Add filter to replace multiple spaces with only one space in textual attributes | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "course".
*
* @property integer $id
* @property string $name
*/
class Course extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'course';
}
/**
... | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "course".
*
* @property integer $id
* @property string $name
*/
class Course extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'course';
}
/**
... |
Change prod url to https | import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'https://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.trunc... | import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'http://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.trunca... |
Check the token before returning the profiles export template | <?php
namespace Backend\Modules\Profiles\Actions;
use Backend\Core\Engine\Base\ActionAdd as BackendBaseActionAdd;
/**
* This is the add-action, it will display a form to add a new profile.
*/
class ExportTemplate extends BackendBaseActionAdd
{
public function execute(): void
{
$this->checkToken();
... | <?php
namespace Backend\Modules\Profiles\Actions;
use Backend\Core\Engine\Base\ActionAdd as BackendBaseActionAdd;
/**
* This is the add-action, it will display a form to add a new profile.
*/
class ExportTemplate extends BackendBaseActionAdd
{
public function execute(): void
{
// define path
... |
Change pause hotkey to P | 'use strict';
Darwinator.Boot = function() {};
Darwinator.Boot.prototype = {
preload: function () {
this.load.image('preloader', 'assets/preloader.gif');
},
create: function () {
this.game.input.maxPointers = 1;
// Toggle pause with space
var key = this.game.input.keyboard.addKey(Phaser.Key... | 'use strict';
Darwinator.Boot = function() {};
Darwinator.Boot.prototype = {
preload: function () {
this.load.image('preloader', 'assets/preloader.gif');
},
create: function () {
this.game.input.maxPointers = 1;
// Toggle pause with space
var key = this.game.input.keyboard.addKey(Phaser.Key... |
Add entries for SRP key exchange algorithms | package org.bouncycastle.crypto.tls;
import java.io.IOException;
/**
* A generic class for ciphersuites in TLS 1.0.
*/
public abstract class TlsCipherSuite
{
protected static final short KE_RSA = 1;
protected static final short KE_RSA_EXPORT = 2;
protected static final short KE_DHE_DSS = 3;
protect... | package org.bouncycastle.crypto.tls;
import java.io.IOException;
/**
* A generic class for ciphersuites in TLS 1.0.
*/
public abstract class TlsCipherSuite
{
protected static final short KE_RSA = 1;
protected static final short KE_RSA_EXPORT = 2;
protected static final short KE_DHE_DSS = 3;
protect... |
Change port from 7700 to 80 | import express from "express"
import graphqlHTTP from "express-graphql"
import { graphqlExpress, graphiqlExpress } from "graphql-server-express"
import bodyParser from "body-parser"
import mongoose, { Schema } from "mongoose"
import schema from "./graphql"
import Item from "./db/item"
// Constants
const HTTP_PORT = 80... | import express from "express"
import graphqlHTTP from "express-graphql"
import { graphqlExpress, graphiqlExpress } from "graphql-server-express"
import bodyParser from "body-parser"
import mongoose, { Schema } from "mongoose"
import schema from "./graphql"
import Item from "./db/item"
// Constants
const HTTP_PORT = 77... |
Remove unneeded `pass` in except block. | from setuptools import setup, find_packages
try:
from pyqt_distutils.build_ui import build_ui
cmdclass={'build_ui': build_ui}
except ImportError:
cmdclass={}
setup(
name='gauges',
version='0.1',
description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo',
url='http://github.com/... | from setuptools import setup, find_packages
try:
from pyqt_distutils.build_ui import build_ui
cmdclass={'build_ui': build_ui}
except ImportError:
cmdclass={}
pass
setup(
name='gauges',
version='0.1',
description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo',
url='http://gi... |
Fix error redirect login page | 'use strict'
const Hash = use('Hash');
const Admin = use('App/Model/Admin');
class AdminLoginController {
* index (request, response) {
const admin = yield request.session.get('admin');
if (null !=admin){
return response.redirect('/ninja/user');
}
const view = yield response.view... | 'use strict'
const Hash = use('Hash');
const Admin = use('App/Model/Admin');
class AdminLoginController {
* index (request, response) {
const view = yield response.view('backend/Login.html');
return response.send(view)
}
* login (request, response) {
const all = request.all();
con... |
Add new channel name for test. | import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/e... | import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/e... |
Fix - run all tests, not only those for saving status directive. | describe('Saving status indicator directive', function() {
var $rootScope, $scope, el, $compile;
var statusClasses = ['pending', 'success', 'failed'];
beforeEach(module('codebrag.common.directives'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$compile = _$compile_;
$root... | ddescribe('Dynamic favicon directive', function() {
var $rootScope, $scope, el, $compile;
var statusClasses = ['pending', 'success', 'failed'];
beforeEach(module('codebrag.common.directives'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$compile = _$compile_;
$rootScope =... |
Fix a bug in getScript utility.
- Should not extract script from deploy section. | import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
const scriptCache = {};
function getCacheOrFile(key, fn) {
if (scriptCache[key]) {
return scriptCache[key];
}
const value = fn();
scriptCache[key] = value;
return value;
}
const travisCommands = [
// Reference: http://docs.tr... | import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
const scriptCache = {};
function getCacheOrFile(key, fn) {
if (scriptCache[key]) {
return scriptCache[key];
}
const value = fn();
scriptCache[key] = value;
return value;
}
const travisCommands = [
// Reference: http://docs.tr... |
Refactor ciscospark Migrate Avatar to packages
use default SparkMock
issue #62 Migrate Avatar | /**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/
import {assert} from '@ciscospark/test-helper-chai';
import Avatar from '../../';
import MockSpark from '@ciscospark/test-helper-mock-spark';
describe(`Services`, () => {
describe(`Avatar`, () => {
describe(`AvatarUrlBatcher`, () => {
... | /**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/
import {assert} from '@ciscospark/test-helper-chai';
import Avatar, {config} from '../../';
// import '@ciscospark/test-helper-sinon';
import {MockSpark} from '@ciscospark/test-helper-mock-spark';
describe(`Services`, () => {
describe(`Avat... |
Add ref to ligiermirror CLU | #!/usr/bin/env python
# coding=utf-8
# vim: ts=4 sw=4 et
"""
=============
Ligier Mirror
=============
Subscribes to given tag(s) and sends them to another Ligier.
This script is also available as a command line utility in km3pipe, which can
be accessed by the command ``ligiermirror``.
"""
# Author: Tamas Gal <tgal@k... | #!/usr/bin/env python
# coding=utf-8
# vim: ts=4 sw=4 et
"""
=============
Ligier Mirror
=============
Subscribes to given tag(s) and sends them to another Ligier.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: MIT
from __future__ import division
import socket
from km3pipe import Pipeline, Module
from km3pipe.... |
Fix small bug in EvenOdd counter flowlet | package DependencyRandomNumber;
import com.continuuity.api.data.*;
import com.continuuity.api.flow.flowlet.*;
import com.continuuity.api.flow.flowlet.builders.*;
public class EvenOddCounter extends AbstractComputeFlowlet {
@Override
public void configure(StreamsConfigurator configurator) {
TupleSchema in = n... | package DependencyRandomNumber;
import com.continuuity.api.data.*;
import com.continuuity.api.flow.flowlet.*;
import com.continuuity.api.flow.flowlet.builders.*;
public class EvenOddCounter extends AbstractComputeFlowlet {
@Override
public void configure(StreamsConfigurator configurator) {
TupleSchema in = n... |
[feedback] Save overlay node to global scope | let optionsOverlayNode = document.getElementById('overlay');
let optionsSaveBtn = document.getElementById('save');
let optionsStatus = document.getElementById('status');
// Saves options to chrome.storage
function save_options() {
chrome.storage.sync.set({
enableOverlay: optionsOverlayNode.checked
}, ... | // Saves options to chrome.storage
function save_options() {
chrome.storage.sync.set({
enableOverlay: document.getElementById('overlay').checked
}, () => {
// Update status to let user know options were saved.
const status = document.getElementById('status');
status.textContent =... |
Update userId validation message to say 'userId' instead of 'feedSlug' | var errors = require('./errors');
var validRe = /^[\w-]+$/;
function validateFeedId(feedId) {
/*
* Validate that the feedId matches the spec user:1
*/
var parts = feedId.split(':');
if (parts.length !== 2) {
throw new errors.FeedError('Invalid feedId, expected something like user:1 got ' + feedId);
... | var errors = require('./errors');
var validRe = /^[\w-]+$/;
function validateFeedId(feedId) {
/*
* Validate that the feedId matches the spec user:1
*/
var parts = feedId.split(':');
if (parts.length !== 2) {
throw new errors.FeedError('Invalid feedId, expected something like user:1 got ' + feedId);
... |
Rename the python package to barn. | from setuptools import setup, find_packages
setup(
name='barn',
version='0.0.1',
description="Store a set of files and metadata in an organized way",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Operating System ::... | import os
from setuptools import setup, find_packages
setup(
name='docstash',
version='0.2.2',
description="Store a set of documents and metadata in an organized way",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"O... |
Add test of async compare | const {assert} = require('./common');
const Passwords = require('../passwords');
describe('Passwords', () => {
it('should be able to generate and compare hashes', async () => {
const pass = 'apple';
const passFake = 'orange';
const passHash = await Passwords.hash(pass);
const passHashSync = Password... | const {assert} = require('./common');
const Passwords = require('../passwords');
describe('Passwords', () => {
it('should be able to generate and compare hashes', async () => {
const pass = 'apple';
const passFake = 'orange';
const passHash = await Passwords.hash(pass);
const passHashSync = Password... |
Change mob menu icon when auto-closing nav menu from a selected nav item | var bindEvents = function() {
smoothScroll.init();
document.querySelector('.mobile-menu-toggle').addEventListener('click', function(event) {
event.preventDefault();
document.getElementById('nav-list').classList.toggle('show');
this.classList.toggle('close'); // toggle icons of mobile icon (.mobile-menu-toggle)... | var bindEvents = function() {
smoothScroll.init();
document.querySelector('.mobile-menu-toggle').addEventListener('click', function(event) {
event.preventDefault();
document.getElementById('nav-list').classList.toggle('show');
this.classList.toggle('close'); // toggle icons of mobile icon (.mobile-menu-toggle)... |
Call RelaxNgWriter as a temporary hack. | package com.thaiopensource.xml.dtd.app;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdP... | package com.thaiopensource.xml.dtd.app;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdP... |
Fix computed value in demo | Bureaucracy.start.cols = [
{
_id: 'name',
name: "Name",
type: String
},
{
_id: 'date',
name: "Travel Date",
type: Date
},
{
_id: 'age',
name: "Age",
type: Number
},
{
_id: 'things',
name: "Things",
type: Array,
value: function(row, col) {
var xs = row[col._id];
return xs.length;
... | Bureaucracy.start.cols = [
{
_id: 'name',
name: "Name",
type: String
},
{
_id: 'date',
name: "Travel Date",
type: Date
},
{
_id: 'age',
name: "Age",
type: Number
},
{
_id: 'things',
name: "Things",
type: Array,
value: function(xs) {
return xs.length;
}
},
{
_id: 'location',
n... |
Allow double return to execute query
If there’s a double return the text will end with “\n”. Closes #5. | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
text = self.document.text
return not self.user_wants_out(text)
super(self.__class_... | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
text = self.document.text
return not self.user_wants_out(text)
super(self.__class_... |
Return MediaObject class instead of string
__toString method on object returns embed URL as before so no usage
changes required | <?php
namespace Joe1992w\LaravelMediaEmbed\Services;
use MediaEmbed\MediaEmbed;
class LaravelMediaEmbed
{
public function parse($url = null, $whitelist = [], $params = [], $attributes = []) {
$MediaEmbed = new MediaEmbed();
$MediaObject = $MediaEmbed->parseUrl($url);
if ($MediaObject)
{
i... | <?php
namespace Joe1992w\LaravelMediaEmbed\Services;
use MediaEmbed\MediaEmbed;
class LaravelMediaEmbed
{
public function parse($url = null, $whitelist = [], $params = [], $attributes = []) {
$MediaEmbed = new MediaEmbed();
$MediaObject = $MediaEmbed->parseUrl($url);
if ($MediaObject)
{
i... |
Fix up the dump options for Control.Zoom | /*
Control.Zoom.debug.js
This is wrapping the L.Control.Zoom class with .debug
(c) 2013, Aaron Racicot, Z-Pulley Inc.
*/
'use strict';
var ControlZoomDebug = L.Class.extend({
// The name of the class being wrapped with a debug
_className: "L.Control.Zoom",
_controlZoom: null,
_map: null,
init... | /*
Control.Zoom.debug.js
This is wrapping the L.Control.Zoom class with .debug
(c) 2013, Aaron Racicot, Z-Pulley Inc.
*/
'use strict';
var ControlZoomDebug = L.Class.extend({
// The name of the class being wrapped with a debug
_className: "L.Control.Zoom",
_controlZoom: null,
_map: null,
init... |
Fix null reference in figure referencing. | define(["showdown/showdown", "showdown/extensions/table"], function() {
return ["$parse", "$compile", function($parse, $compile) {
return {
restrict: 'A',
priority: 0,
link: function(scope, element, attrs) {
var pageId = scope.page ? scope.page.id : "";
Showdown.extensions.refs = function(co... | define(["showdown/showdown", "showdown/extensions/table"], function() {
return ["$parse", "$compile", function($parse, $compile) {
return {
restrict: 'A',
priority: 0,
link: function(scope, element, attrs) {
Showdown.extensions.refs = function(converter) {
return [{
type: "lang",
... |
Add PyPI classifiers and additional metadata. | #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
from version import VERSION
assert sys.version_info >= (2, 6), 'We only support Python 2.6+'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'asana'))
setup(
name='asana',
version=VERSION,
description='Asa... | #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
assert sys.version_info >= (2, 6), 'We only support Python 2.6+'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'asana'))
from version import VERSION
setup(name='asana',
version=VERSION,
description='Asana... |
Add check for no tasks | import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
... | import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
... |
Fix crashing bug: Compare Libya | import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOvervie... | import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import {
parseSelectedLocations,
getSelectedLocationsFilter,
addSelectedNameToLocations
} from 'selectors/compare';
// values from search
const getSelectedLocations = state => state.selectedLocations || null;
const getContentOvervie... |
FIx broken links in Javadoc | package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(OnMap... | package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(MapVi... |
Use importlib instead of exec (exec was pretty ugly) | #!/usr/bin/python3
import argparse
import sys
from mawslib.manager import Manager
import importlib
configfile="cloudconfig.yaml"
parser = argparse.ArgumentParser(
#add_help=False,
description='AWS Manager',
usage='''maws [<options>] <command> <subcommand> [<args>]
For help:
maws help
maws <command... | #!/usr/bin/python3
import argparse
import sys
from mawslib.manager import Manager
configfile="cloudconfig.yaml"
parser = argparse.ArgumentParser(
#add_help=False,
description='AWS Manager',
usage='''maws [<options>] <command> <subcommand> [<args>]
For help:
maws help
maws <command> help
maws <c... |
IFS-9490: Complete project setup header updated | package org.innovateuk.ifs.project.internal;
public enum ProjectSetupStage {
PROJECT_DETAILS("Project details", 1),
PROJECT_TEAM("Project team", 2),
DOCUMENTS("Documents", 3),
MONITORING_OFFICER("MO", 4),
BANK_DETAILS("Bank details", 5),
FINANCE_CHECKS("Finance checks", 6),
SPEND_PROFILE("S... | package org.innovateuk.ifs.project.internal;
public enum ProjectSetupStage {
PROJECT_DETAILS("Project details", 1),
PROJECT_TEAM("Project team", 2),
DOCUMENTS("Documents", 3),
MONITORING_OFFICER("MO", 4),
BANK_DETAILS("Bank details", 5),
FINANCE_CHECKS("Finance checks", 6),
SPEND_PROFILE("S... |
Fix path to global node_modules on Windows | /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
va... | /*!
* global-prefix <https://github.com/jonschlinkert/global-prefix>
*
* Copyright (c) 2015 Jon Schlinkert.
* Licensed under the MIT license.
*/
'use strict';
/**
* This is the code used internally by npm to
* resolve the global prefix.
*/
var isWindows = require('is-windows');
var path = require('path');
va... |
Update test to assert metric | import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 p... | import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 p... |
Add "Ok" button to about dialog | package de.cketti.holocolorpicker.demo;
import com.actionbarsherlock.app.SherlockDialogFragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Lay... | package de.cketti.holocolorpicker.demo;
import com.actionbarsherlock.app.SherlockDialogFragment;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
im... |
Set component callbacks to null to prevent unexpected method invocations. | package eu.luminis.devcon.rest;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.osgi.framework.BundleContext;
import eu.luminis.devcon.RocketLauncher;
public class Activator extends DependencyActivatorBase {
@Override
public void init(BundleContext arg0... | package eu.luminis.devcon.rest;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.osgi.framework.BundleContext;
import eu.luminis.devcon.RocketLauncher;
public class Activator extends DependencyActivatorBase {
@Override
public void init(BundleContext arg0... |
Create session if one doesn't exist | from lightning import Lightning
def viztype(VizType):
def plotter(self, *args, **kwargs):
if not hasattr(self, 'session'):
self.create_session()
viz = VizType.baseplot(self.session, VizType._name, *args, **kwargs)
self.session.visualizations.append(viz)
return viz
... | from lightning import Lightning
def viztype(VizType):
def plotter(self, *args, **kwargs):
viz = VizType.baseplot(self.session, VizType._name, *args, **kwargs)
self.session.visualizations.append(viz)
return viz
if not hasattr(VizType,'_func'):
func = VizType._name
else:
... |
Use production settings by default; Display settings version in use | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... |
Remove long description as causing pip error | from setuptools import setup, find_packages
setup(
name = "django-disposable-email-checker",
version = "0.1.1",
packages = find_packages(),
author = "Aaron Bassett",
author_email = "me@aaronbassett.com",
description = "Python class for use with Django to detect Disposable Emails",
license ... | from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
setup(
name = "django-disposable-email-checker",
version = "0.1.1",
packages = find_packages(),
package_data = {
# If any package contains *.txt or *.rst files, include them:
'': ['*.txt', '... |
Patch for using DB Rider with MS SQL Server
Added IDENTITY_INSERT SeedStrategy to avoid following error:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert explicit value for identity column in table 'xxxxx' when IDENTITY_INSERT is set to OFF. | package com.github.database.rider.core.api.dataset;
/**
* Created by pestano on 23/07/15.
*/
import org.dbunit.operation.*;
/**
Same as arquillian persistence: https://docs.jboss.org/author/display/ARQ/Persistence
Data insert strategies
DBUnit, and hence Arquillian Persistence Extension, provides following stra... | package com.github.database.rider.core.api.dataset;
/**
* Created by pestano on 23/07/15.
*/
import org.dbunit.operation.*;
/**
Same as arquillian persistence: https://docs.jboss.org/author/display/ARQ/Persistence
Data insert strategies
DBUnit, and hence Arquillian Persistence Extension, provides following stra... |
Change sybase skip test to check for more restrictive vv creds
This should let the report-writing test that uses the axafvv query
run as jeanconn user, but skip for other users. | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='jeanconn', database='axafvv') as db:
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACC... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_AC... |
Correct position of comment :) | import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
storage =... | import re
from redis import Redis
import json
from datetime import datetime
def is_valid_chatroom(chatroom):
return re.match('[A-Za-z_\\d]+$', chatroom) is not None
def get_redis():
return Redis()
def get_conversation(chatroom):
if chatroom is None or len(chatroom) == 0:
return None
# if chat... |
Revert "Review ex11 and ex12"
This reverts commit e5fe21acd40e9ebeae548e906747702783058d06. | # Upper is ex11, lower part is ex 12
# Both print out are same, but ex11 needs 8 lines,
# ex 12 just need it for 4 lines.
print "How old are you?", #Becasue can't use print and value in same line
age = raw_input() # That's why need two lines to do so.
print "How tall are you?",
height = raw_input()
print "Ho... | # Upper is ex11, lower part is ex 12
# Both print out are same, but ex11 needs 8 lines,
# ex 12 just need it for 4 lines.
print "How old are you?", # Becasue can't use print and value in same line
age = raw_input() # That's why need two lines to do so.
print "How tall are you?",
height = raw_input()
print "Ho... |
Add @NonNull to message parameter of overridden method log | /*
* Copyright 2017 Martin Kamp Jensen
*
* 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 agr... | /*
* Copyright 2017 Martin Kamp Jensen
*
* 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 agr... |
Make AccessibilityTextView inherit from AppCompatTextView | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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 app... | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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 app... |
Add runc to usable executor options!
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us> | package executordispatch
import (
"path/filepath"
"polydawn.net/repeatr/def"
"polydawn.net/repeatr/executor"
"polydawn.net/repeatr/executor/chroot"
"polydawn.net/repeatr/executor/nsinit"
"polydawn.net/repeatr/executor/null"
"polydawn.net/repeatr/executor/runc"
)
// TODO: This should not require a global strin... | package executordispatch
import (
"path/filepath"
"polydawn.net/repeatr/def"
"polydawn.net/repeatr/executor"
"polydawn.net/repeatr/executor/chroot"
"polydawn.net/repeatr/executor/nsinit"
"polydawn.net/repeatr/executor/null"
)
// TODO: This should not require a global string -> class map :|
// Should attempt to... |
Hide the fact that we're using a ctor for side effects | package rxbroadcast;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
@SuppressWarnings({"checkstyle:MagicNumber"})
public final class VectorTimestampTest {
@Test
public final void equalsContract() {
EqualsVerifier.forClass... | package rxbroadcast;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;
@SuppressWarnings({"checkstyle:MagicNumber"})
public final class VectorTimestampTest {
@Test
public final void equalsContract() {
EqualsVerifier.forClass(VectorTimestamp.class)
.withCachedHashCode("ha... |
Use print as a function and tweak output text | import numpy as np
from Chandra.Time import DateTime
import plot_aimpoint
# Get 99th percential absolute pointing radius
plot_aimpoint.opt = plot_aimpoint.get_opt()
asols = plot_aimpoint.get_asol()
# Last six months of data
asols = asols[asols['time'] > DateTime(-183).secs]
# center of box of range of data
mid_dy = (... | import numpy as np
from Chandra.Time import DateTime
import plot_aimpoint
# Get 99th percential absolute pointing radius
plot_aimpoint.opt = plot_aimpoint.get_opt()
asols = plot_aimpoint.get_asol()
# Last six months of data
asols = asols[asols['time'] > DateTime(-183).secs]
# center of box of range of data
mid_dy = (... |
Increment minor version after ArcGIS fix and improved tests and docs | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.te... | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.te... |
Add setup and teardown code | package com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers;
import org.jsoup.parser.Tag;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static o... | package com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers;
import org.jsoup.parser.Tag;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
/**
* Created by beng on 22/12/2... |
FIX ember docs generation if the component parameter is missing (for whatever reason) | /* eslint-disable no-underscore-dangle */
/* global window */
export const setJSONDoc = jsondoc => {
window.__EMBER_GENERATED_DOC_JSON__ = jsondoc;
};
export const getJSONDoc = () => {
return window.__EMBER_GENERATED_DOC_JSON__;
};
export const extractProps = componentName => {
const json = getJSONDoc();
cons... | /* eslint-disable no-underscore-dangle */
/* global window */
export const setJSONDoc = jsondoc => {
window.__EMBER_GENERATED_DOC_JSON__ = jsondoc;
};
export const getJSONDoc = () => {
return window.__EMBER_GENERATED_DOC_JSON__;
};
export const extractProps = componentName => {
const json = getJSONDoc();
cons... |
Add `export` to emitted lines | #!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
... | #!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
... |
Update a version number from trunk r9016 | # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,... | # -*- coding: utf-8 -*-
__version__ = '$Id$'
import family
# The Wikia Search family
# user-config.py: usernames['wikia']['wikia'] = 'User name'
class Family(family.Family):
def __init__(self):
family.Family.__init__(self)
self.name = u'wikia'
self.langs = {
u'wikia': None,... |
REmove unused imports and fields. | package com.openxc.remote.sources;
import com.openxc.remote.sources.SourceCallback;
/**
* The BaseVehicleDataSource contains functions common to all vehicle data
* sources.
*/
public class BaseVehicleDataSource implements VehicleDataSource {
private SourceCallback mCallback;
public BaseVehicleDataSource()... | package com.openxc.remote.sources;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.util.Log;
import com.openxc.remote.sources.SourceCallback;
/**
* The BaseVehicleDataSource contains functions common to all vehicle data
* sources.
*/
public class BaseVehicleDat... |
Change dname of key test | from ev3.ev3dev import Key
import unittest
from util import get_input
class TestKey(unittest.TestCase):
def test_key(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input('Test keyboard... | from ev3.ev3dev import Key
import unittest
from util import get_input
import time
class TestTone(unittest.TestCase):
def test_tone(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input(... |
[Polymer] Change browserSync to use port 4200 | var gulp = require('gulp');
var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
gulp.task('copy', function () {
return gulp.src('./app/index.html', {base: './app/'})
.pipe(gulp.dest('./dist/'));
});
gulp.... | var gulp = require('gulp');
var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
gulp.task('copy', function () {
return gulp.src('./app/index.html', {base: './app/'})
.pipe(gulp.dest('./dist/'));
});
gulp.... |
Remove sleep from page retrieval | <?php
class GalleryController extends BaseController {
public $return_data = [
'per_page' => 10
];
public function getIndex()
{
$this->return_data['entries'] = Entry::where('approved', true)->take($this->return_data['per_page'])->get();
return View::make('gallery', $this->ret... | <?php
class GalleryController extends BaseController {
public $return_data = [
'per_page' => 10
];
public function getIndex()
{
$this->return_data['entries'] = Entry::where('approved', true)->take($this->return_data['per_page'])->get();
return View::make('gallery', $this->ret... |
Cover more font extensions for CORS from static media
We were missing woff2, but this should just future proof us if more are
added. | """
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers imp... | """
sentry.web.frontend.generic
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.views.generic import TemplateView as BaseTemplateView
from sentry.web.helpers imp... |
Test: Call loadConfig method in beforeEach so test can check if called | import {Configure} from '../src/configure';
class HttpStub {
get(url) {
}
}
class EventStub {
}
describe('the main configure.js singleton', () => {
var config;
var mockedHttp;
var mockedEvent;
beforeEach(() => {
mockedHttp = new HttpStub();
mockedEvent = new EventStub();
... | import {Configure} from '../src/configure';
class HttpStub {
get(url) {
}
}
class EventStub {
}
describe('the main configure.js singleton', () => {
var config;
var mockedHttp;
var mockedEvent;
beforeEach(() => {
mockedHttp = new HttpStub();
mockedEvent = new EventStub();
... |
Purge harvestjobs older than retention policy before cleanup | /**
* Delete references to deleted datasets
*/
var updated = 0;
var nbDays = config.HARVEST_JOBS_RETENTION_DAYS;
var minDate = new Date(ISODate().getTime() - 1000 * 60 * 60 * 24 * nbDays);
// Delete jobs older then minDate
var result = db.harvest_job.deleteMany({'created': {'$lt': minDate}});
print(`Deleted ${resul... | /**
* Delete references to deleted datasets
*/
var updated = 0;
// Match all HarvestJob.items.dataset not found in dataset collection
const pipeline = [
{$unwind: '$items'}, // One row by item
{$group: {_id: null, datasetId: {$addToSet: '$items.dataset'}}}, // Distinct Dataset IDs
{$unwind: '$datasetId... |
Add 'npm bin' to uglifyjs command. | #!/usr/bin/env node
var colors = require('colors'),
exec = require('child_process').exec,
pkg = require('../package.json'),
preamble = '/*!\n' +
' * RadioRadio ' + pkg.version + '\n' +
' *\n' +
' * ' + pkg.description + '\n' +
' *\n' +
' * Source code available at: ' + pkg.homepage + '\n' +
' *\n' +
... | #!/usr/bin/env node
var colors = require('colors'),
exec = require('child_process').exec,
pkg = require('../package.json'),
preamble = '/*!\n' +
' * RadioRadio ' + pkg.version + '\n' +
' *\n' +
' * ' + pkg.description + '\n' +
' *\n' +
' * Source code available at: ' + pkg.homepage + '\n' +
' *\n' +
... |
Change order of initial app render and router activation. | "use strict";
var View = require("./view");
var Router = require("./router");
var util = require("substance-util");
var _ = require("underscore");
// Substance.Application
// ==========================================================================
//
// Application abstraction suggesting strict MVC
var Application... | "use strict";
var View = require("./view");
var Router = require("./router");
var util = require("substance-util");
var _ = require("underscore");
// Substance.Application
// ==========================================================================
//
// Application abstraction suggesting strict MVC
var Application... |
Fix test to cater for packages leaked into venv | import json
import os
from pathlib import Path
from venv import EnvBuilder
from tests.lib import PipTestEnvironment, TestData
def test_python_interpreter(
script: PipTestEnvironment,
tmpdir: Path,
shared_data: TestData,
) -> None:
env_path = os.fspath(tmpdir / "venv")
env = EnvBuilder(with_pip=Fa... | import json
import os
from pathlib import Path
from venv import EnvBuilder
from tests.lib import PipTestEnvironment, TestData
def test_python_interpreter(
script: PipTestEnvironment,
tmpdir: Path,
shared_data: TestData,
) -> None:
env_path = os.fsdecode(tmpdir / "venv")
env = EnvBuilder(with_pip=... |
Add variables for easy configiration and customisation. | var upnp = require("peer-upnp");
var http = require("http");
var server = http.createServer();
var PORT = 8080;
var name="IOT-DEVICE";
var model="IoT Device";
var modelUrl="";
var version="1.00";
var serial="12345678";
var address="";
// Start server on port 8080.
server.listen(PORT);
// Create a UPnP Peer.
var pee... | var upnp = require("peer-upnp");
var http = require("http");
var server = http.createServer();
var PORT = 8080;
// start server on port 8080.
server.listen(PORT);
// Create a UPnP Peer.
var peer = upnp.createPeer({
prefix: "/upnp",
server: server
}).on("ready",function(peer){
console.log("ready");
//... |
Make http request with a default timeout
If no timeout specified a connection can hang forever | package collector
import (
"fullerite/metric"
"time"
"net/http"
)
type errorHandler func(error)
type responseHandler func(*http.Response) []metric.Metric
type baseHTTPCollector struct {
baseCollector
rspHandler responseHandler
errHandler errorHandler
endpoint string
}
// Collect first queries the config'd... | package collector
import (
"fullerite/metric"
"net/http"
)
type errorHandler func(error)
type responseHandler func(*http.Response) []metric.Metric
type baseHTTPCollector struct {
baseCollector
rspHandler responseHandler
errHandler errorHandler
endpoint string
}
// Collect first queries the config'd endpoin... |
Add dot for the list of allowed group names. r=jonasfj
MacOSX indeed has group names with dots. The particular case I found was
com.apple.sharepoint.group.1. | package nativeengine
import schematypes "github.com/taskcluster/go-schematypes"
type config struct {
Groups []string `json:"groups,omitempty"`
}
var configSchema = schematypes.Object{
MetaData: schematypes.MetaData{
Title: "Native Engine Config",
Description: "Configuration for the native engine, this engines ... | package nativeengine
import schematypes "github.com/taskcluster/go-schematypes"
type config struct {
Groups []string `json:"groups,omitempty"`
}
var configSchema = schematypes.Object{
MetaData: schematypes.MetaData{
Title: "Native Engine Config",
Description: "Configuration for the native engine, this engines ... |
Add the required group when creating the token. Clarify the description text.
git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@4019 653ae4dd-d31e-0410-96ef-6bf7bf53c507 | <?php
class SimplePrivatePosts extends Plugin
{
public function action_plugin_activation()
{
ACL::create_token('private', 'Permission to read posts marked as "private"', 'Private Posts');
// Deny the anonymous group access to the private token, if the group hasn't been removed (why would you remove it ??)
$a... | <?php
class SimplePrivatePosts extends Plugin
{
public function action_plugin_activation()
{
ACL::create_token('private', 'Permissions on posts marked as "private"');
// Deny the anonymous group access to the private token, if the group hasn't been removed (why would you remove it ??)
$anon = UserGroup::get(... |
Put the script loading in test in a try/catch because it was causing an error in certain cases with Opera. | var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
try {
testOk = js_files[index].test();
... | var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
if (js_files[index].test()){
// console.log('... |
Fix indention error - thought that was fixed before my last push | import subprocess
def _eintr_retry_call(func, *args):
while True:
try:
return func(*args)
except OSError, e:
if e.errno == errno.EINTR:
continue
raise
def ct_query(filename):
cmd = 'ctags -n -u --fields=+K -f -'
args = cmd.split()
args.append(filename)
proc = subprocess.Popen(args, stdout=subpro... | import subprocess
def _eintr_retry_call(func, *args):
while True:
try:
return func(*args)
except OSError, e:
if e.errno == errno.EINTR:
continue
raise
def ct_query(filename):
cmd = 'ctags -n -u --fields=+K -f -'
args = cmd.split()
args.append(filename)
proc = subprocess.Popen(args, stdout=subprocess... |
Raise error upon dataflow cycle detection. | import {error} from 'vega-util';
/**
* Assigns a rank to an operator. Ranks are assigned in increasing order
* by incrementing an internal rank counter.
* @param {Operator} op - The operator to assign a rank.
*/
export function rank(op) {
op.rank = ++this._rank;
}
/**
* Re-ranks an operator and all downstream ... | /**
* Assigns a rank to an operator. Ranks are assigned in increasing order
* by incrementing an internal rank counter.
* @param {Operator} op - The operator to assign a rank.
*/
export function rank(op) {
op.rank = ++this._rank;
}
/**
* Re-ranks an operator and all downstream target dependencies. This
* is ne... |
Implement meta by using the bconf package (separate repository). | package index
import (
"bconf"
)
type Index struct {
br *blob_reader
Docs map[uint32][]byte
Attrs map[string][]IbDoc
Meta bconf.Bconf
header string
}
func Open(name string) (*Index, error) {
var in Index
var err error
in.br, err = open_blob_reader(name)
if err != nil {
return nil, err
}
in.Docs =... | package index
type Index struct {
br *blob_reader
Docs map[uint32][]byte
Attrs map[string][]IbDoc
}
func Open(name string) (*Index, error) {
var in Index
var err error
in.br, err = open_blob_reader(name)
if err != nil {
return nil, err
}
in.Docs = make(map[uint32][]byte)
for _, d := range in.br.get_... |
Change permissions for user search | <?php
namespace App\Policies;
use App\User;
use App\APIUser;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;
class APIUserPolicy
{
use HandlesAuthorization;
public function view_in_admin(User $user) {
if ($user->site_admin) {
return true;
}
}
... | <?php
namespace App\Policies;
use App\User;
use App\APIUser;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;
class APIUserPolicy
{
use HandlesAuthorization;
public function view_in_admin(User $user) {
if ($user->site_admin) {
return true;
}
}
... |
Print number of terms loaded to Airtable. | import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
... | import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
... |
Remove the param to filter inactive advisers | const { get } = require('lodash')
const config = require('../../../config')
const { authorisedRequest } = require('../../lib/authorised-request')
function getAdvisers (token) {
return authorisedRequest(token, `${config.apiRoot}/adviser/?limit=100000&offset=0`)
.then(response => {
const results = response.r... | const { get } = require('lodash')
const config = require('../../../config')
const { authorisedRequest } = require('../../lib/authorised-request')
function getAdvisers (token) {
return authorisedRequest(token, `${config.apiRoot}/adviser/?limit=100000&offset=0`)
.then(response => {
const results = response.r... |
Test content type for JSON API | import json
from unittest import TestCase
from usb import create_application
from usb.models import db
class APITestCase(TestCase):
def setUp(self):
self.app = create_application('config/test.py')
self.client = self.app.test_client()
db.app = self.app
db.create_all()
def te... | import json
from unittest import TestCase
from usb import create_application
from usb.models import db
class APITestCase(TestCase):
def setUp(self):
self.app = create_application('config/test.py')
self.client = self.app.test_client()
db.app = self.app
db.create_all()
def te... |
Fix method signature and wrong class import | <?php
/**
* This file is part of prooph/proophessor-do.
* (c) 2014-2016 prooph software GmbH <contact@prooph.de>
* (c) 2015-2016 Sascha-Oliver Prolic <saschaprolic@googlemail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
de... | <?php
/**
* This file is part of prooph/proophessor-do.
* (c) 2014-2016 prooph software GmbH <contact@prooph.de>
* (c) 2015-2016 Sascha-Oliver Prolic <saschaprolic@googlemail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
de... |
Allow func validation to throw custom errors | <?php
/*
* Copyright 2019 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Validator\Rule;
use Coast\Validator\Rule;
class Func extends Rule
{
protected $_func;
public function __construct(callable... | <?php
/*
* Copyright 2019 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Validator\Rule;
use Coast\Validator\Rule;
class Func extends Rule
{
protected $_func;
public function __construct(callable... |
Fix first time execution of sample:data command test. | <?php
/**
* This file is part of The OBMS project: https://github.com/obms/obms
*
* Copyright (c) Jaime Niñoles-Manzanera Jimeno.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AdministrationBundle\Tests;
/**
* Clas... | <?php
/**
* This file is part of The OBMS project: https://github.com/obms/obms
*
* Copyright (c) Jaime Niñoles-Manzanera Jimeno.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AdministrationBundle\Tests;
/**
* Clas... |
Use the utility module's extract_publication_date logic. | """Populate the `publication_date` column.
Revision ID: 17c1af634026
Revises: 3c4c29f0a791
Create Date: 2012-12-13 21:03:03.445346
"""
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
fro... | """Populate the `publication_date` column.
Revision ID: 17c1af634026
Revises: 3c4c29f0a791
Create Date: 2012-12-13 21:03:03.445346
"""
# revision identifiers, used by Alembic.
revision = '17c1af634026'
down_revision = '3c4c29f0a791'
import html5lib
from dateutil.parser import parse as parse_date
import pytips
fro... |
Switch to ruamel_yaml from conda by default | import sys
from setuptools import setup
# See https://stackoverflow.com/questions/19534896/enforcing-python-version-in-setup-py
if sys.version_info < (3,6):
sys.exit("Sorry, Python < 3.6 is not supported by Auspex.")
setup(
name='auspex',
version='0.1',
author='auspex Developers',
package_dir={'':... | import sys
from setuptools import setup
# See https://stackoverflow.com/questions/19534896/enforcing-python-version-in-setup-py
if sys.version_info < (3,6):
sys.exit("Sorry, Python < 3.6 is not supported by Auspex.")
setup(
name='auspex',
version='0.1',
author='auspex Developers',
package_dir={'':... |
Fix bug that meant rendering debug info was v slow. | import copy
from ckan.plugins import toolkit as tk
def qa_openness_stars_resource_html(resource):
qa = resource.get('qa')
if not qa:
return '<!-- No qa info for this resource -->'
# Take a copy of the qa dict, because weirdly the renderer appears to add
# keys to it like _ and app_globals. Thi... | from ckan.plugins import toolkit as tk
def qa_openness_stars_resource_html(resource):
qa = resource.get('qa')
if not qa:
return '<!-- No qa info for this resource -->'
extra_vars = qa
return tk.literal(
tk.render('qa/openness_stars.html',
extra_vars=extra_vars))
def... |
Fix reordering due to removal of Other | '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which us... | '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which us... |
[Pool] Allow retrieval of a model manager with only a class name rather than a class instance | <?php
namespace HCLabs\ModelManagerBundle\Pool;
use HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException;
use HCLabs\ModelManagerBundle\Model\Contract\ModelInterface;
use HCLabs\ModelManagerBundle\Model\Contract\ModelManagerInterface;
class ModelManagerPool
{
/** @var ModelManagerInterface[] */
... | <?php
namespace HCLabs\ModelManagerBundle\Pool;
use HCLabs\ModelManagerBundle\Exception\ModelManagerNotFoundException;
use HCLabs\ModelManagerBundle\Model\Contract\ModelInterface;
use HCLabs\ModelManagerBundle\Model\Contract\ModelManagerInterface;
class ModelManagerPool
{
/** @var ModelManagerInterface[] */
... |
Fix db_downgrade for "System editable object state" |
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '512c71e4d93b'
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from alembic import op
from ... |
"""System editable object state
Revision ID: 5254f4f31427
Revises: 512c71e4d93b
Create Date: 2015-02-05 02:05:09.351265
"""
# revision identifiers, used by Alembic.
revision = '5254f4f31427'
down_revision = '512c71e4d93b'
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from alembic import op
from ... |
Fix get_pypi_packages for new requirements-parser | """Core pep438 utility functions"""
from __future__ import unicode_literals
import requests
try:
import xmlrpclib
except:
import xmlrpc.client as xmlrpclib # noqa
from xml.etree import ElementTree
from requirements import parse
def valid_package(package_name):
"""Return bool if package_name is a valid p... | """Core pep438 utility functions"""
from __future__ import unicode_literals
import requests
try:
import xmlrpclib
except:
import xmlrpc.client as xmlrpclib # noqa
from xml.etree import ElementTree
from requirements import parse
def valid_package(package_name):
"""Return bool if package_name is a valid p... |
Remove an extra anonymous function | var expect = require('expect.js');
var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
before(seeds);
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document');
});
describe('.search()'... | var expect = require('expect.js');
var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
before(function (done) {
seeds(done);
});
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document... |
Update to handle users with no final grade | '''
This module will retrieve info about students registered in the course
Usage:
python user_info.py
'''
from base_edx import EdXConnection
from generate_csv_report import CSV
connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile')
collection = connection.get_access_to_collection()
d... | '''
This module will retrieve info about students registered in the course
Usage:
python user_info.py
'''
from collections import defaultdict
from base_edx import EdXConnection
from generate_csv_report import CSV
connection = EdXConnection('certificates_generatedcertificate', 'auth_userprofile')
collection = con... |
Fix load of compiled lz4 module | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lz4", "build") )
if not os.path.isdir(build_dir):
... | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lz4", "build") )
if not os.path.isdir(build_dir):
... |
Call 'lower()' on the input | """
instabot example
Whitelist generator: generates a list of users which
will not be unfollowed.
"""
import sys
import os
import random
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
bot = Bot()
bot.login()
print("This script will generate whitelist.txt file with users"
... | """
instabot example
Whitelist generator: generates a list of users which
will not be unfollowed.
"""
import sys
import os
import random
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
bot = Bot()
bot.login()
print("This script will generate whitelist.txt file with users"
... |
Remove redundant import of tkinter. | from test import support
# Skip test if _tkinter wasn't built.
support.import_module('_tkinter')
import tkinter
from tkinter.test import runtktests
import unittest
try:
tkinter.Button()
except tkinter.TclError as msg:
# assuming tk is not available
raise unittest.SkipTest("tk not available: %s" % msg)
de... | from test import support
# Skip test if _tkinter wasn't built.
support.import_module('_tkinter')
import tkinter
from tkinter.test import runtktests
import unittest
import tkinter
try:
tkinter.Button()
except tkinter.TclError as msg:
# assuming tk is not available
raise unittest.SkipTest("tk not availabl... |
Set API to Heroku address. | angular
.module('zibble', ['angular-jwt', 'ngResource', 'ui.router'])
.constant('API', 'https://zibble-back-end.herokuapp.com')
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthInterceptor');
})
.config(MainRouter);
function MainRouter($stateProvider, $urlRouterProvider, $locationPro... | angular
.module('zibble', ['angular-jwt', 'ngResource', 'ui.router'])
.constant('API', 'http://localhost:3000')
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthInterceptor');
})
.config(MainRouter);
function MainRouter($stateProvider, $urlRouterProvider, $locationProvider){
$state... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.