text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Replace AsyncTask with AsyncTaskLoader and do some clean up. | package com.example.android.quakereport;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import java.util.List;
/**
* Created by Lenovo on 7/6/2017.
*/
/*
Loads a list of earthquakes by using an AsyncTaskLoader to perform the
network request to the destination... | package com.example.android.quakereport;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import java.util.List;
/**
* Created by Lenovo on 7/6/2017.
*/
public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>>
{
final static String LOG_TAG = Earthq... |
Revert names to slugs again! SORRY!! | <?php
declare(strict_types=1);
namespace Cortex\Foundation\Transformers;
use Cortex\Foundation\Models\Log;
use Illuminate\Support\Facades\Route;
use League\Fractal\TransformerAbstract;
class LogTransformer extends TransformerAbstract
{
/**
* @return array
*/
public function transform(Log $log): ar... | <?php
declare(strict_types=1);
namespace Cortex\Foundation\Transformers;
use Cortex\Foundation\Models\Log;
use Illuminate\Support\Facades\Route;
use League\Fractal\TransformerAbstract;
class LogTransformer extends TransformerAbstract
{
/**
* @return array
*/
public function transform(Log $log): ar... |
Fix the Class Type Test Cases class name, and enhance the create new | from decimal import Decimal
from django.db import IntegrityError
from django.test import TestCase
from .models import ClassType
class ClassTypeTestCases(TestCase):
"""
Testing Class Type model
"""
def setUp(self):
self.class_type, created = ClassType.objects.get_or_create(name='Class Type... | from decimal import Decimal
from django.db import IntegrityError
from django.test import TestCase
from .models import ClassType
class ClassTypeClassTypeTestCases(TestCase):
"""
Testing Class Type model
"""
def setUp(self):
self.class_type, created = ClassType.objects.get_or_create(name='Class ... |
Change official reference message wording | import React from "react";
import { connect } from "react-redux";
import styled from "styled-components";
import { Box, Button, ExternalLink } from "../../base";
import { checkAdminOrPermission } from "../../utils/utils";
import { remoteReference } from "../actions";
const StyledReferenceOfficial = styled(Box)`
al... | import React from "react";
import { connect } from "react-redux";
import styled from "styled-components";
import { Box, Button, ExternalLink } from "../../base";
import { checkAdminOrPermission } from "../../utils/utils";
import { remoteReference } from "../actions";
const StyledReferenceOfficial = styled(Box)`
al... |
Remove explicit python2 call -- works with Python 3 | #!/bin/env python
"""
moref: more for FASTA files
"""
import sys
import os
from Bio import SeqIO
def main():
"""moref main"""
# Check for input file
if len(sys.argv) < 2:
print("No input file specified")
sys.exit()
filepath = os.path.expanduser(sys.argv[1])
if not os.path.isf... | #!/bin/env python2
"""
moref: more for FASTA files
"""
import sys
import os
from Bio import SeqIO
def main():
"""moref main"""
# Check for input file
if len(sys.argv) < 2:
print("No input file specified")
sys.exit()
filepath = os.path.expanduser(sys.argv[1])
if not os.path.is... |
Work around Python3's byte semantics. | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... |
Fix "covers" annotation in tests | <?php
/**
* @author Sergii Bondarenko, <sb@firstvector.org>
*/
namespace Drupal\Tests\TqExtension\Utils;
use Drupal\TqExtension\Utils\LogicalAssertion;
/**
* Class LogicalAssertionTest.
*
* @package Drupal\Tests\TqExtension\Utils
*
* @coversDefaultClass \Drupal\TqExtension\Utils\LogicalAssertion
*/
class Log... | <?php
/**
* @author Sergii Bondarenko, <sb@firstvector.org>
*/
namespace Drupal\Tests\TqExtension\Utils;
use Drupal\TqExtension\Utils\LogicalAssertion;
/**
* Class LogicalAssertionTest.
*
* @package Drupal\Tests\TqExtension\Utils
*
* @coversDefaultClass \Drupal\TqExtension\Utils\LogicalAssertion
*/
class Log... |
test: Use old-school looping since travis stuck on ancient Chromium:
- See travis-ci/travis-ci#3475
- TODO: switch to full Chrome on travis | describe('ZendeskWidgetProvider', function() {
'use strict';
var subject, mockService, $window;
beforeEach(module('zendeskWidget'));
beforeEach(inject(function(_$window_, _ZendeskWidget_) {
subject = _ZendeskWidget_;
$window = _$window_;
}));
describe('a set of API methods', function() {
... | describe('ZendeskWidgetProvider', function() {
'use strict';
var subject, mockService, $window;
beforeEach(module('zendeskWidget'));
beforeEach(inject(function(_$window_, _ZendeskWidget_) {
subject = _ZendeskWidget_;
$window = _$window_;
}));
describe('a set of API methods', function() {
... |
Comment getList docstring with variable names | <?php
class Services_Twilio_Rest_AvailablePhoneNumbers
extends Services_Twilio_ListResource
{
public function getLocal($country)
{
$curried = new Services_Twilio_PartialApplicationHelper();
$curried->set(
'getList',
array($this, 'getList'),
array($country... | <?php
class Services_Twilio_Rest_AvailablePhoneNumbers
extends Services_Twilio_ListResource
{
public function getLocal($country)
{
$curried = new Services_Twilio_PartialApplicationHelper();
$curried->set(
'getList',
array($this, 'getList'),
array($country... |
Set time to utc time | package ch.squix.esp8266.fontconverter.rest.time;
import java.awt.FontFormatException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.restlet.resource.Post;
import org.restlet.resource... | package ch.squix.esp8266.fontconverter.rest.time;
import java.awt.FontFormatException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.restlet.resource.Post;
import org.restlet.resource... |
Load and test for admin users. | module.exports = function(access) {
'use strict';
let _ = require('lodash');
let projectAccessCache = {};
let adminUsersCache = {};
return {
find: find,
clear: clear,
validateAccess: validateAccess
};
// find looks up a given project in the project cache.
// If ... | module.exports = function(access) {
'use strict';
let _ = require('lodash');
let projectAccessCache = {};
return {
find: find,
clear: clear,
validateAccess: validateAccess
};
// find looks up a given project in the project cache.
// If the projectAccessCache hasn't ... |
Fix to git status info | import os
import subprocess
__version__ = "0.1.0-1"
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _ini... | import os
import subprocess
__version__ = "0.1.0-1"
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _ini... |
Add method to get currently logged in user from http request | package uk.ac.ebi.spot.goci.curation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import uk.... | package uk.ac.ebi.spot.goci.curation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import uk.... |
Use @staff_member_required decorator for the dashboard view as well | from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib import messages
try:
from django.views.decorators.csrf import csrf_exempt
except ImportError:
... | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib import messages
try:
from django.views.decorators.csrf import csrf_exempt
except ImportError:
from django... |
Handle case of zero forms more gracefully for JSON option. | const xml2js = require('xml2js');
const parser = new xml2js.Parser({explicitArray: false, attrkey: "attributes"});
const createFormList = require('openrosa-formlist');
const getFormUrls = require('../helpers/get-form-urls');
/**
* Searches for XForm XML Files on the file system and
* returns valid OpenRosa formList ... | const xml2js = require('xml2js');
const parser = new xml2js.Parser({explicitArray: false, attrkey: "attributes"});
const createFormList = require('openrosa-formlist');
const getFormUrls = require('../helpers/get-form-urls');
/**
* Searches for XForm XML Files on the file system and
* returns valid OpenRosa formList ... |
Fix data source for employees page | define(function(require) {
var BasePageView = require('./BasePageView'),
TimeSelectorView = require('app/ui/views/TimeSelectorView'),
BarChartView = require('app/ui/views/BarChartView'),
revenueByCategoryCollection = require('app/models/RevenueByCategoryCollection'),
SmallRevenueByCategoryVie... | define(function(require) {
var BasePageView = require('./BasePageView'),
TimeSelectorView = require('app/ui/views/TimeSelectorView'),
BarChartView = require('app/ui/views/BarChartView'),
revenueByEmployeeCollection = require('app/models/RevenueByEmployeeCollection'),
SmallRevenueByCategoryVie... |
Remove call to class_basename which only exists when Laravel is used. | <?php namespace Dxi\Commands\Dataset\Contact;
use Dxi\Commands\Command;
class Create extends Command {
/**
* Get the payload for the command
*
* @return array
*/
public function getRequiredParams()
{
return [
'firstname',
'dataset',
[
... | <?php namespace Dxi\Commands\Dataset\Contact;
use Dxi\Commands\Command;
class Create extends Command {
/**
* Get the payload for the command
*
* @return array
*/
public function getRequiredParams()
{
return [
'firstname',
'dataset',
[
... |
Solve RuntimeWarning that arose without knowing why. | from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.01',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='software@creativecommons.org',
url='http://... | from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.01',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='software@creativecommons.org',
url='http://... |
Change the alerts viirs response to unify with the others alerts | 'use strict';
var logger = require('logger');
var imageService = require('services/imageService');
var analysisService = require('services/analysisService');
class VIIRSPresenter {
static * transform(results, layer, subscription, begin, end) {
logger.debug('Obtaining fires');
let alerts = yield a... | 'use strict';
var logger = require('logger');
var imageService = require('services/imageService');
var analysisService = require('services/analysisService');
class VIIRSPresenter {
static * transform(results, layer, subscription, begin, end) {
logger.debug('Obtaining fires');
let alerts = yield a... |
Disable the style checking for now | 'use strict';
var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var styleLintPlugin = require('stylelint-webpack-plugin');
require('es6-promise').polyfill();
module.exports = {
entry: './src/js/m... | 'use strict';
var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var styleLintPlugin = require('stylelint-webpack-plugin');
require('es6-promise').polyfill();
module.exports = {
entry: './src/js/m... |
Update and fix sass gulp path | var gulp = require('gulp'),
browserSync = require('browser-sync'),
sass = require('gulp-sass'),
bower = require('gulp-bower'),
notify = require('gulp-notify'),
reload = browserSync.reload,
bs = require("browser-sync").create(),
Hexo = require('hexo'),
... | var gulp = require('gulp'),
browserSync = require('browser-sync'),
sass = require('gulp-sass'),
bower = require('gulp-bower'),
notify = require('gulp-notify'),
reload = browserSync.reload,
bs = require("browser-sync").create(),
Hexo = require('hexo'),
... |
Clean up some console chatter | var hooks = require('hooks');
var async = require('async');
function Renderable(View) {
this.data = {};
this.mode = 'main';
this.view = {};
if (typeof View === 'function') {
this.view = new View();
}
this.render = function(cb) {
// recursively render any Renderable objects inside this.data
//... | var hooks = require('hooks');
var async = require('async');
function Renderable(View) {
this.data = {};
this.mode = 'main';
this.view = {};
if (typeof View === 'function') {
this.view = new View();
}
this.render = function(cb) {
// recursively render any Renderable objects inside this.data
//... |
Read lib dir, before local dir. | #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------... | #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------... |
Fix high cpu usage through sleep | import thread
import json
import time
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
from game import Game
def client_thread(game, conn, data):
player = game.add_player(conn, data)
while True:
answer_data = game.wait_for_answer(player)
if answer_data:
conn.send... | import thread
import json
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
from game import Game
def client_thread(game, conn, data):
player = game.add_player(conn, data)
while True:
answer_data = game.wait_for_answer(player)
if answer_data:
conn.sendMessage(answ... |
Use tresdb-key in attachment generation | var db = require('tresdb-db');
var keygen = require('tresdb-key');
exports.count = function (callback) {
// Count non-deleted attachments
//
// Parameters:
// callback
// function (err, number)
//
db.collection('attachments').countDocuments({
deleted: false,
})
.then(function (number) {
... | var db = require('tresdb-db');
exports.count = function (callback) {
// Count non-deleted attachments
//
// Parameters:
// callback
// function (err, number)
//
db.collection('attachments').countDocuments({
deleted: false,
})
.then(function (number) {
return callback(null, number);
... |
Set type of the button to submit. | <?php
namespace RKA;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class ExampleForm extends Form implements InputFilterProviderInterface
{
public function init()
{
$this->add([
'name' => 'email',
'options' => [
'label' => 'Email addres... | <?php
namespace RKA;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class ExampleForm extends Form implements InputFilterProviderInterface
{
public function init()
{
$this->add([
'name' => 'email',
'options' => [
'label' => 'Email addres... |
Add page and it's method when displaying 404 response | <?php
class Loader
{
private $instance = array();
public function page($name, $method='index')
{
if ($name==='')
{
$name = 'home';
}
$page = $this->loadClass($name, 'Page');
if ($page === false || method_exis... | <?php
class Loader
{
private $instance = array();
public function page($name, $method='index')
{
if ($name==='')
{
$name = 'home';
}
$page = $this->loadClass($name, 'Page');
if ($page === false || method_exis... |
Make numba the default implementation, as it beats weave in major parts of the benchmarks now | def dummy_no_impl(*args, **kwargs):
raise NotImplementedError("You may need to install another package (numpy, "
"weave, or numba) to access a working implementation.")
from .aggregate_purepy import aggregate as aggregate_py
aggregate = aggregate_py
try:
import numpy as np
except... | def dummy_no_impl(*args, **kwargs):
raise NotImplementedError("You may need to install another package (numpy, "
"weave, or numba) to access a working implementation.")
from .aggregate_purepy import aggregate as aggregate_py
aggregate = aggregate_py
try:
import numpy as np
except... |
Add package data to package. | from setuptools import setup, find_packages
setup(name='facebookinsights',
description='A wrapper and command-line interface for the Facebook Insights API.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='stijn@debrouwere.org',
#url='http://stdbrouw.github.com/... | from setuptools import setup, find_packages
setup(name='facebookinsights',
description='A wrapper and command-line interface for the Facebook Insights API.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='stijn@debrouwere.org',
#url='http://stdbrouw.github.com/... |
Fix check for valid resolver_match | from django.template import Library
from django.template.defaulttags import URLNode, url
from django.utils.html import escape, mark_safe
register = Library()
class MenuLINode(URLNode):
def render(self, context):
# Pull out the match and hijack asvar
# to be used for the link title
match =... | from django.template import Library
from django.template.defaulttags import URLNode, url
from django.utils.html import escape, mark_safe
register = Library()
class MenuLINode(URLNode):
def render(self, context):
# Pull out the match and hijack asvar
# to be used for the link title
request... |
Support extra params on event manager |
;(function(){
var binder = window.addEventListener ? 'addEventListener' : 'attachEvent'
, unbinder = window.removeEventListener ? 'removeEventListener' : 'detachEvent'
, eventPrefix = binder !== 'addEventListener' ? 'on' : '';
function bind(el, type, fn, capture) {
el[binder](eventPrefix + type, fn, c... |
;(function(){
var binder = window.addEventListener ? 'addEventListener' : 'attachEvent'
, unbinder = window.removeEventListener ? 'removeEventListener' : 'detachEvent'
, eventPrefix = binder !== 'addEventListener' ? 'on' : '';
function bind(el, type, fn, capture) {
el[binder](eventPrefix + type, fn, c... |
Make the "check" command available via the Werkzeug extension. | import logging
from webassets.script import CommandLineEnvironment
__all__ = ('make_assets_action',)
def make_assets_action(environment, loaders=[]):
"""Creates a ``werkzeug.script`` action which interfaces
with the webassets command line tools.
Since Werkzeug does not provide a way to have subcommands... | import logging
from webassets.script import CommandLineEnvironment
__all__ = ('make_assets_action',)
def make_assets_action(environment, loaders=[]):
"""Creates a ``werkzeug.script`` action which interfaces
with the webassets command line tools.
Since Werkzeug does not provide a way to have subcommands... |
Add token to perform a full content swap | <?php
namespace Concrete\Core\Backup\ContentImporter\Importer\Routine;
use Concrete\Core\Attribute\Type;
use Concrete\Core\Block\BlockType\BlockType;
use Concrete\Core\Package\Package;
use Concrete\Core\Permission\Category;
use Concrete\Core\Support\Facade\Facade;
use Concrete\Core\Validation\BannedWord\BannedWord;
us... | <?php
namespace Concrete\Core\Backup\ContentImporter\Importer\Routine;
use Concrete\Core\Attribute\Type;
use Concrete\Core\Block\BlockType\BlockType;
use Concrete\Core\Package\Package;
use Concrete\Core\Permission\Category;
use Concrete\Core\Support\Facade\Facade;
use Concrete\Core\Validation\BannedWord\BannedWord;
us... |
Update check update error handler. | (function () {
function showMessage(message, type) {
$('#check-update-info a.close').trigger('click.fndtn.alert');
var alertBox = '<div data-alert id="check-update-info" class="alert-box ' +
type + '">' + message +
'<a href="#" class="close">×</a> ' + '</div>';
... | (function () {
function showMessage(message, type) {
$('#check-update-info a.close').trigger('click.fndtn.alert');
var alertBox = '<div data-alert id="check-update-info" class="alert-box ' +
type + '">' + message +
'<a href="#" class="close">×</a> ' + '</div>';
... |
Extend Broadcast protocol abstraction with a Handler interface for message delivery | from abc import ABCMeta, abstractmethod
import socket, json
class Broadcast(metaclass=ABCMeta):
"""
An interface for defining a broadcast protocol.
The 'propose' and 'decide' methods need to be defined
"""
BUFFER_SIZE = 1024
def __init__(self, peer_list):
self.peers = peer_list
... | from abc import ABCMeta, abstractmethod
import socket, json
class Broadcast(metaclass=ABCMeta):
"""
An interface for defining a broadcast protocol.
The 'propose' and 'decide' methods need to be defined
"""
BUFFER_SIZE = 1024
def __init__(self, peer_list):
self.peers = peer_list
... |
Fix check user is active by email or username | <?php
namespace Passengers\Event;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\Controller\Component\AuthComponent;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\ORM\Association;
use Cake\ORM\Tableregistry;
class SignInEvent implements EventListenerInterface {
public function im... | <?php
namespace Passengers\Event;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\Controller\Component\AuthComponent;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\ORM\Association;
use Cake\ORM\Tableregistry;
class SignInEvent implements EventListenerInterface {
public function im... |
Make sure that all requests for static files are correctly hidden from output | from django.conf import settings
from django.core.servers.basehttp import WSGIRequestHandler
from django.db import connection
from devserver.utils.time import ms_from_timedelta
from datetime import datetime
class SlimWSGIRequestHandler(WSGIRequestHandler):
"""
Hides all requests that originate from either ``... | from django.conf import settings
from django.core.servers.basehttp import WSGIRequestHandler
from django.db import connection
from devserver.utils.time import ms_from_timedelta
from datetime import datetime
class SlimWSGIRequestHandler(WSGIRequestHandler):
"""
Hides all requests that originate from ```MEDIA_... |
Allow to use Promises on `discard` function | import { busy, scheduleRetry } from './actions';
import { JS_ERROR } from './constants';
import type { Config, OfflineAction, ResultAction } from './types';
const complete = (
action: ResultAction,
success: boolean,
payload: {}
): ResultAction => ({
...action,
payload,
meta: { ...action.meta, success, comp... | import { busy, scheduleRetry } from './actions';
import { JS_ERROR } from './constants';
import type { Config, OfflineAction, ResultAction } from './types';
const complete = (
action: ResultAction,
success: boolean,
payload: {}
): ResultAction => ({
...action,
payload,
meta: { ...action.meta, success, comp... |
Test changing tab complete list | package io.github.lasercar.simplemention;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;
import java.util.regex.Matcher;
i... | package io.github.lasercar.simplemention;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;
import java.util.regex.Matcher;
i... |
Reorder keys that were being declared in the wrong place | # -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a... | # -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a... |
Allow ExpressMiddleware without extra prefix | /*
* Return express middleware that measures overall performance.
*/
function factory(parentClient) {
return function (prefix, options) {
var client = parentClient.getChildClient(prefix || '');
options = options || {};
var timeByUrl = options.timeByUrl || false;
var onResponseEnd =... | /*
* Return express middleware that measures overall performance.
*/
function factory(parentClient) {
return function (prefix, options) {
var client = parentClient.getChildClient(prefix);
options = options || {};
var timeByUrl = options.timeByUrl || false;
var onResponseEnd = optio... |
Fix typo in self.propagate_signal call | from celery import task
from django.dispatch.dispatcher import (
_make_id,
Signal,
)
class AsyncSignal(Signal):
def __init__(self, providing_args=None, queue=None):
super(AsyncSignal, self).__init__(providing_args=providing_args)
self.queue = queue
def send(self, sender, **named):
... | from celery import task
from django.dispatch.dispatcher import (
_make_id,
Signal,
)
class AsyncSignal(Signal):
def __init__(self, providing_args=None, queue=None):
super(AsyncSignal, self).__init__(providing_args=providing_args)
self.queue = queue
def send(self, sender, **named):
... |
Connect loading and error events to UI | // Main script
// -----------
var blackbird = blackbird || {};
blackbird.player = {};
$(document).ready(function() {
blackbird.player = new blackbird.Player(blackbird.api_root);
// First play
blackbird.player.next();
// Create seek slider
$("#seek-bar").slider({
min: 0,
max: 10... | // Main script
// -----------
var blackbird = blackbird || {};
blackbird.player = {};
$(document).ready(function() {
blackbird.player = new blackbird.Player(blackbird.api_root);
// First play
blackbird.player.next();
// Create seek slider
$("#seek-bar").slider({
min: 0,
max: 10... |
Use devtool when developing for easier debugging | var path = require('path');
var webpack = require('webpack');
var isProd = (process.env.NODE_ENV === 'production');
module.exports = {
devtool: !isProd && 'eval',
entry: {
app: './app.js'
},
module: {
preLoaders: [
{
test: /\.js$/,
include: /components/,
exclude: /node_mo... | var path = require('path');
var webpack = require('webpack');
var isProd = (process.env.NODE_ENV === 'production');
module.exports = {
entry: {
app: './app.js'
},
module: {
preLoaders: [
{
test: /\.js$/,
include: /components/,
exclude: /node_modules/,
loader: 'eslin... |
Remove min 1 from reporttype | <?php
/**
* Created by PhpStorm.
* User: ylly
* Date: 16/10/15
* Time: 19:01
*/
namespace ESN\PermanenceBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ReportType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder... | <?php
/**
* Created by PhpStorm.
* User: ylly
* Date: 16/10/15
* Time: 19:01
*/
namespace ESN\PermanenceBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ReportType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder... |
Allow "writable" if *any* field is writable
Fixes Internal Issue 598 | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django import template
from treemap.json_field import get_attr_from_json_field
register = template.Library()
def _get_color_from_config(config, name):
color = config.get(name)
if color:
... | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django import template
from treemap.json_field import get_attr_from_json_field
register = template.Library()
def _get_color_from_config(config, name):
color = config.get(name)
if color:
... |
Remove unused option, fix CS | <?php
namespace Gloubster;
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Connection\AMQPSSLConnection;
class RabbitMQFactory
{
public static function createConnection(Configuration $conf)
{
if (isset($conf['server']['ssl']) && $conf['server']['ssl']['enable']) {
$connection = ... | <?php
namespace Gloubster;
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Connection\AMQPSSLConnection;
class RabbitMQFactory
{
public static function createConnection(Configuration $conf, $connected = true)
{
if (isset($conf['server']['ssl']) && $conf['server']['ssl']['enable']) {
... |
Fix a few CS issues | 'use strict';
var NavbarDirective = function ($window, eehNavigation) {
return {
restrict: 'AE',
templateUrl: 'template/eeh-navigation/decoupled/eeh-navigation-navbar.html',
link: function (scope) {
scope._navbarBrand = eehNavigation._navbarBrand;
scope.isNavbarColla... | 'use strict';
var NavbarDirective = function ($window, eehNavigation) {
return {
restrict: 'AE',
templateUrl: 'template/eeh-navigation/decoupled/eeh-navigation-navbar.html',
link: function (scope, element) {
scope._navbarBrand = eehNavigation._navbarBrand;
scope.isNa... |
Use `devtool: 'source-map'` because 'eval' isn't suited for production
(https://webpack.js.org/configuration/devtool/#devtool) | /* eslint-env node */
const webpack = require('webpack');
const packageJson = require('./package.json');
const isProduction = process.env.NODE_ENV === 'production';
function getLicenseComment(version) {
return [
'Likely $version by Ilya Birman (ilyabirman.net)',
'Rewritten sans jQuery by Evgeny S... | /* eslint-env node */
const webpack = require('webpack');
const packageJson = require('./package.json');
const isProduction = process.env.NODE_ENV === 'production';
function getLicenseComment(version) {
return [
'Likely $version by Ilya Birman (ilyabirman.net)',
'Rewritten sans jQuery by Evgeny S... |
Hide StreamAnalyzer and OsGuesser from the API docs. | #!/usr/bin/env python
# Generates the *public* API documentation.
# Remember to hide your private parts, people!
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Gen... | #!/usr/bin/env python
# Generates the *public* API documentation.
# Remember to hide your private parts, people!
import os, re, sys
project = 'Exscript'
base_dir = os.path.join('..', 'src', project)
doc_dir = 'api'
# Create the documentation directory.
if not os.path.exists(doc_dir):
os.makedirs(doc_dir)
# Gen... |
Make core thread pool size unbounded | package forklift.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Forklift cor... | package forklift.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Forklift cor... |
Add a dev mode so that watching rebuilds is quick without minification | const path = require('path')
const babelConfig = require('./babel.config')
const bubleConfig = require('./buble.config')
const BabelMinify = require("babel-minify-webpack-plugin");
let DEV = false
// --watch option means dev mode
if (process.argv.includes('--watch')) {
DEV = true
}
module.exports = {
entry: ... | const path = require('path')
const babelConfig = require('./babel.config')
const bubleConfig = require('./buble.config')
const BabelMinify = require("babel-minify-webpack-plugin");
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: 'global.js',
library: 'in... |
Add timestamp to url to force ng-src reload | spacialistApp.service('analysisService', ['httpGetFactory', function(httpGetFactory) {
var analysis = {};
analysis.entries = [];
analysis.activeAnalysis = {
isActive: false
};
analysis.getStoredQueries = function() {
httpGetFactory('api/analysis/queries/getAll', function(queries) {... | spacialistApp.service('analysisService', ['httpGetFactory', function(httpGetFactory) {
var analysis = {};
analysis.entries = [];
analysis.activeAnalysis = {
isActive: false
};
analysis.getStoredQueries = function() {
httpGetFactory('api/analysis/queries/getAll', function(queries) {... |
Allow plotting two types against one another. | #!/usr/bin/env python
#Go through an OpenXC trace file and plot a time series graph using
#matplotlib
import json
import sys
import argparse
from pylab import *
def main():
#Set up the command line argument parser
parser = argparse.ArgumentParser()
parser.add_argument("input_file",
... | #!/usr/bin/env python
#Go through an OpenXC trace file and plot a time series graph using
#matplotlib
import json
import sys
import argparse
from pylab import *
def main():
#Set up the command line argument parser
parser = argparse.ArgumentParser()
parser.add_argument("input_file",
... |
Fix bug due to refacto | #-*- coding: utf-8 -*-
from src.shell.parser.i_log_parser import ILogParser
class TypeLogParser(ILogParser):
"""
Parser for type log file
"""
def __init__(self, *args, **kwargs):
self.__fn = None
super(TypeLogParser, self).__init__(*args, **kwargs)
def get(self):
if ... | #-*- coding: utf-8 -*-
from src.shell.parser.i_log_parser import ILogParser
class TypeLogParser(ILogParser):
"""
Parser for type log file
"""
def __init__(self, *args, **kwargs):
self.__fn = None
super(TypeLogParser, self).__init__(*args, **kwargs)
def get(self):
if ... |
Convert Flask path variables to OpenAPI path parameters | """OpenAPI core wrappers module"""
import re
from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse
# http://flask.pocoo.org/docs/1.0/quickstart/#variable-rules
PATH_PARAMETER_PATTERN = r'<(?:(?:string|int|float|path|uuid):)?(\w+)>'
class FlaskOpenAPIRequest(BaseOpenAPIRequest):
path_re... | """OpenAPI core wrappers module"""
from openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse
class FlaskOpenAPIRequest(BaseOpenAPIRequest):
def __init__(self, request):
self.request = request
@property
def host_url(self):
return self.request.host_url
@property
... |
Order Aphabetical: Add listeners for at-rules
Viewport was completely missing, but the others were also not reporting
at the end of the rule scope | /*
* Rule: All properties should be in alphabetical order..
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "order-alphabetical",
name: "Alphabetical order",
desc: "Assure properties are in alphabetical order",
browsers: "All",
//initialization
init: function(parser, repor... | /*
* Rule: All properties should be in alphabetical order..
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "order-alphabetical",
name: "Alphabetical order",
desc: "Assure properties are in alphabetical order",
browsers: "All",
//initialization
init: function(parser, repor... |
Load database config depend on application name. | <?php defined('SYSPATH') or die('No direct script access.');
/**
* Arag
*
* @package Arag
* @author Armen Baghumian
* @since Version 0.3
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Model Class
*
* @package Arag
* @subpackage Libr... | <?php defined('SYSPATH') or die('No direct script access.');
/**
* Arag
*
* @package Arag
* @author Armen Baghumian
* @since Version 0.3
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Model Class
*
* @package Arag
* @subpackage Libr... |
Fix limit bug in create Initiative method | Meteor.startup(function() {
Meteor.methods({
addComment: function(initiativeId, input) {
var userId = Meteor.userId();
Meteor.users.update(userId, { $addToSet: { commentedOn: initiativeId } });
Initiatives.update(initiativeId, {$addToSet: {comments: {
createdBy: userId,
message: ... | Meteor.startup(function() {
Meteor.methods({
addComment: function(initiativeId, input) {
var userId = Meteor.userId();
Meteor.users.update(userId, { $addToSet: { commentedOn: initiativeId } });
Initiatives.update(initiativeId, {$addToSet: {comments: {
createdBy: userId,
message: ... |
Return null if not found | "use strict";
var db = require("./db.json"),
strictFormats = [
/^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/,
/^([0-9A-F]{2}[:-]){2}([0-9A-F]{2})$/,
/^([0-9A-F]{4}[.]){2}([0-9A-F]{4})$/,
/^[0-9A-F]{6}$/,
/^[0-9A-F]{12}$/
];
var oui = function oui(input, opts) {
if (typeof i... | "use strict";
var db = require("./db.json"),
strictFormats = [
/^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/,
/^([0-9A-F]{2}[:-]){2}([0-9A-F]{2})$/,
/^([0-9A-F]{4}[.]){2}([0-9A-F]{4})$/,
/^[0-9A-F]{6}$/,
/^[0-9A-F]{12}$/
];
var oui = function oui(input, opts) {
if (typeof i... |
engine: Delete vnic profiles when removing a network
The patch removes vnic profiles when the network is
being deleted from the system.
Change-Id: I6472fb81262d7eb2cf6886a42ba17a637c804b22
Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com> | package org.ovirt.engine.core.bll.network.dc;
import org.ovirt.engine.core.bll.validator.NetworkValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
public class RemoveNetwork... | package org.ovirt.engine.core.bll.network.dc;
import org.ovirt.engine.core.bll.validator.NetworkValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
public class RemoveNetwork... |
Fix fail on javadoc task. | package com.github.kubode.rxproperty;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
/**
* Read-only Observable property.
*
* @param <T> the type of this property.
*/
public class ReadOnlyObservableProperty<T> extends Observable<T> {
/**
* The state of {@link ReadOnlyObservableProperty}... | package com.github.kubode.rxproperty;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
/**
* Read-only Observable property.
*
* @param <T> the type of this property.
*/
public class ReadOnlyObservableProperty<T> extends Observable<T> {
/**
* The state of {@link ReadOnlyObservableProperty}... |
Fix a Paste activate/archive status constant in rendering
Summary: Fixes T11280. I extracted this at the last minute and got the constant flipped.
Test Plan: Archived, then activated a paste. Observed correct timeline stories/icons/etc.
Reviewers: chad
Reviewed By: chad
Maniphest Tasks: T11280
Differential Revisi... | <?php
final class PhabricatorPasteStatusTransaction
extends PhabricatorPasteTransactionType {
const TRANSACTIONTYPE = 'paste.status';
public function generateOldValue($object) {
return $object->getStatus();
}
public function applyInternalEffects($object, $value) {
$object->setStatus($value);
}
... | <?php
final class PhabricatorPasteStatusTransaction
extends PhabricatorPasteTransactionType {
const TRANSACTIONTYPE = 'paste.status';
public function generateOldValue($object) {
return $object->getStatus();
}
public function applyInternalEffects($object, $value) {
$object->setStatus($value);
}
... |
Add date_registered to node serializer
[#OSF-7230] | import json
from website.util.permissions import reduce_permissions
from admin.users.serializers import serialize_simple_node
def serialize_node(node):
embargo = node.embargo
if embargo is not None:
embargo = node.embargo.end_date
return {
'id': node._id,
'title': node.title,
... | import json
from website.util.permissions import reduce_permissions
from admin.users.serializers import serialize_simple_node
def serialize_node(node):
embargo = node.embargo
if embargo is not None:
embargo = node.embargo.end_date
return {
'id': node._id,
'title': node.title,
... |
Fix order of rendering for unit test | import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent( 'sl-calendar-year', 'Unit - component: sl-calendar-year' );
test( 'Default state is not active, new, or old', function( assert ) {
let component = this.subject(),
$component = this.render();
assert... | import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent( 'sl-calendar-year', 'Unit - component: sl-calendar-year' );
test( 'Default state is not active, new, or old', function( assert ) {
let component = this.subject(),
$component = this.render();
assert... |
Add main menu chat entry | <?php
namespace Rooty\DefaultBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware {
public function mainMenuAnonymous(FactoryInterface $factory) {
$menu = $factory->createItem('root');
$menu->setCurrentUri($this-... | <?php
namespace Rooty\DefaultBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware {
public function mainMenuAnonymous(FactoryInterface $factory) {
$menu = $factory->createItem('root');
$menu->setCurrentUri($this-... |
Use threading instead of multiprocessing. | from threading import Thread, Event
try:
from queue import Queue
except ImportError:
from Queue import Queue
class Timer(Thread):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval
self.function = function
sel... | # -*- coding: utf-8
from multiprocessing import Queue, Process, Event
class Timer(Process):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
... |
Simplify default equals function based on immutability | import { ReactiveVar } from 'meteor/reactive-var';
import { Promise } from 'meteor/promise';
function eqls(a, b) {
// Because Apollo client data is immutable, we can simply check equality by using ===
return a === b;
}
export class ReactiveObserver {
constructor(observer, {
defaultValue = {},
eq... | import { ReactiveVar } from 'meteor/reactive-var';
import { Promise } from 'meteor/promise';
function eqls(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
export class ReactiveObserver {
constructor(observer, {
defaultValue = {},
equals = eqls,
} = {}) {
this.observer = observer;... |
Add marginTop on input fields when inside a label | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Input from '../input';
import { TextBody, TextDisplay } from '../typography';
import theme from './theme.css';
import isComponentOfType from '../utils/is-component-of-type';
import cx from 'classnames';
export default class Label ... | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Input from '../input';
import { TextBody, TextDisplay } from '../typography';
import theme from './theme.css';
import isComponentOfType from '../utils/is-component-of-type';
import cx from 'classnames';
export default class Label ... |
Add support for `supported_transfer_countries` on CountrySpec | package stripe
// Country is the list of supported countries
type Country string
// VerificationFieldsList lists the fields needed for an account verification.
// For more details see https://stripe.com/docs/api#country_spec_object-verification_fields.
type VerificationFieldsList struct {
AdditionalFields []string `... | package stripe
// Country is the list of supported countries
type Country string
// VerificationFieldsList lists the fields needed for an account verification.
// For more details see https://stripe.com/docs/api#country_spec_object-verification_fields.
type VerificationFieldsList struct {
AdditionalFields []string `... |
Fix test runner for development Django | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"badgekit_webhooks",
"badgekit_webhooks.tests"
],
DATA... | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"badgekit_webhooks",
"badgekit_webhooks.tests"
],
DATA... |
Declare that cyrtranslit supports Python 3.7 | from distutils.core import setup
setup(
name='cyrtranslit',
packages=['cyrtranslit'],
version='0.4',
description='Bi-directional Cyrillic transliteration. Transliterate Cyrillic script text to Roman alphabet text and vice versa.',
author='Open Data Kosovo',
author_email='dev@opendatakosovo.org',
url='http... | from distutils.core import setup
setup(
name='cyrtranslit',
packages=['cyrtranslit'],
version='0.4',
description='Bi-directional Cyrillic transliteration. Transliterate Cyrillic script text to Roman alphabet text and vice versa.',
author='Open Data Kosovo',
author_email='dev@opendatakosovo.org',
url='http... |
Use any for concise code | import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
Dispatc... | import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
Dispatc... |
Fix ordering on command line | #!/usr/bin/env node
/*eslint-disable no-var */
var path = require('path');
var spawner = require('child_process');
exports.getFullPath = function(script){
return path.join(__dirname, script);
};
// Respawn ensuring proper command switches
exports.respawn = function respawn(script, requiredArgs, hostProcess) {
... | #!/usr/bin/env node
/*eslint-disable no-var */
var path = require('path');
var spawner = require('child_process');
exports.getFullPath = function(script){
return path.join(__dirname, script);
};
// Respawn ensuring proper command switches
exports.respawn = function respawn(script, requiredArgs, hostProcess) {
... |
Remove v3.0 requirement for now | try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
import sys
svem_flag = '--single-version-externally-managed'
if svem_flag in sys.argv:
# Die, setuptools, die.
sys.argv.remove(svem_flag)
with open('jupyter_kernel/__init__.py', 'rb') as fid:
for line in ... | try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
import sys
svem_flag = '--single-version-externally-managed'
if svem_flag in sys.argv:
# Die, setuptools, die.
sys.argv.remove(svem_flag)
with open('jupyter_kernel/__init__.py', 'rb') as fid:
for line in ... |
Use transaction.atomic in batch uploader. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploa... |
Improve local import detection in `BaseParser.process_imports` | import abc
import os
import typing
import urllib.parse
if typing.TYPE_CHECKING:
from ..ontology import Ontology
class BaseParser(abc.ABC):
def __init__(self, ont: 'Ontology'):
self.ont = ont
@classmethod
@abc.abstractmethod
def can_parse(cls, path: str, buffer: bytes):
"""Return... | import abc
import os
import typing
import urllib.parse
if typing.TYPE_CHECKING:
from ..ontology import Ontology
class BaseParser(abc.ABC):
def __init__(self, ont: 'Ontology'):
self.ont = ont
@classmethod
@abc.abstractmethod
def can_parse(cls, path: str, buffer: bytes):
"""Return... |
Add python_requires to help pip | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import restless
setup(
name='restless',
version=restless.VERSION,
description='A lightweight REST miniframework for Python.',
author='Daniel Lindsley',
author_email='daniel@toastdriven.com',
url='http://github.com/toas... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import restless
setup(
name='restless',
version=restless.VERSION,
description='A lightweight REST miniframework for Python.',
author='Daniel Lindsley',
author_email='daniel@toastdriven.com',
url='http://github.com/toas... |
Reduce size of chart with query | 'use strict';
var ChartsController = function($scope, $rootScope) {
$scope.drawChart = function() {
if ($scope.geoAggData && $scope.geoAggData.length > 0) {
var length = $scope.geoAggData.length;
var height = 320;
var width = 370;
var margin = '-40px 10px 0px 0px';
if (length == 1)... | 'use strict';
var ChartsController = function($scope, $rootScope) {
$scope.drawChart = function() {
if ($scope.geoAggData && $scope.geoAggData.length > 0) {
console.log('$scope.geoAggData', $scope.geoAggData, 'length', $scope.geoAggData);
// instantiate d3plus
d3plus.viz()
.container('#... |
Update BuiltIn library reference for RF 2.9 compatibility | # -*- coding: utf-8 -*-
import os
import sys
from robot.libraries.BuiltIn import BuiltIn
from robot.api import logger
from keywordgroup import KeywordGroup
class _LoggingKeywords(KeywordGroup):
# Private
def _debug(self, message):
logger.debug(message)
def _get_log_dir(self):
... | # -*- coding: utf-8 -*-
import os
import sys
from robot.variables import GLOBAL_VARIABLES
from robot.api import logger
from keywordgroup import KeywordGroup
class _LoggingKeywords(KeywordGroup):
# Private
def _debug(self, message):
logger.debug(message)
def _get_log_dir(self):
... |
Create directory, if necessary, before preprocessing files as well | #!/usr/bin/env python
import errno
import os
import ctk_cli
import keras.models as M
from tubetk.vseg.cnn import deploy, utils
script_params = utils.script_params
def main(args):
utils.set_params_path(args.params)
if (args.resampled is None) ^ (script_params['RESAMPLE_SPACING'] is None or args.preprocessed... | #!/usr/bin/env python
import errno
import os
import ctk_cli
import keras.models as M
from tubetk.vseg.cnn import deploy, utils
script_params = utils.script_params
def main(args):
utils.set_params_path(args.params)
if (args.resampled is None) ^ (script_params['RESAMPLE_SPACING'] is None or args.preprocessed... |
Revert 232677 "Revert 232670 "Fix script after r232641""
False alarm, tests we failing due to PDT switch.
> Revert 232670 "Fix script after r232641"
>
> Needs to be out to speculatively revert r232641.
>
> > Fix script after r232641
> >
> > BUG=314253
> > TBR=pfeldman@chromium.org
> >
> > Review URL: https://code... | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave ... | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave ... |
Enable Isosurface class by default | #!/usr/bin/env python
from __future__ import print_function
from setuptools import setup, find_packages
entry_points = """
[glue.plugins]
vispy_volume=glue_vispy_viewers.volume:setup
vispy_scatter=glue_vispy_viewers.scatter:setup
vispy_isosurface=glue_vispy_viewers.isosurface:setup
"""
# Add the following to the ab... | #!/usr/bin/env python
from __future__ import print_function
from setuptools import setup, find_packages
entry_points = """
[glue.plugins]
vispy_volume=glue_vispy_viewers.volume:setup
vispy_scatter=glue_vispy_viewers.scatter:setup
"""
# Add the following to the above entry points to enable the isosurface viewer
# vi... |
Fix params with period not being passed to callback | (function(win){
'use strict';
var paramRe = /:([^\/.\\]+)/g;
function Router(){
if(!(this instanceof Router)){
return new Router();
}
this.routes = [];
}
Router.prototype.route = function(path, fn){
paramRe.lastIndex = 0;
var regexp = path + '',... | (function(win){
'use strict';
var paramRe = /:([^\/.\\]+)/g;
function Router(){
if(!(this instanceof Router)){
return new Router();
}
this.routes = [];
}
Router.prototype.route = function(path, fn){
paramRe.lastIndex = 0;
var regexp = path + '',... |
Add Filter option for order amd order group | from django.contrib import admin
from digikey.models import Components, Orders, Order_Details, Groups
class ComponentInline(admin.TabularInline):
model = Order_Details
extra = 1
class OrderInline(admin.TabularInline):
model = Orders
extra = 1
fieldsets = [
('Payment information', {... | from django.contrib import admin
from digikey.models import Components, Orders, Order_Details, Groups
class ComponentInline(admin.TabularInline):
model = Order_Details
extra = 1
class OrderInline(admin.TabularInline):
model = Orders
extra = 1
fieldsets = [
('Payment information', {... |
Refactor matrix creation to use values slice |
function Matrix(options) {
options = options || {};
var values;
if (options.values) {
values = options.values.slice();
for (var k = 0; k < values.length; k++)
values[k] = values[k].slice();
}
if (options.rows && options.columns && !values) {
... |
function Matrix(options) {
options = options || {};
var values;
if (options.values)
values = options.values;
if (options.rows && options.columns && !values) {
values = [];
for (var k = 0; k < options.rows; k++) {
var row = [];
... |
Exclude missing annotations from coverage | <?php
declare(strict_types=1);
namespace Overblog\GraphQLBundle\Config\Parser;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Overblog\GraphQLBundle\Config\Parser\MetadataParser\MetadataParser;
use ReflectionClass;
use ReflectionMethod;
use ReflectionPropert... | <?php
declare(strict_types=1);
namespace Overblog\GraphQLBundle\Config\Parser;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Overblog\GraphQLBundle\Config\Parser\MetadataParser\MetadataParser;
use ReflectionClass;
use ReflectionMethod;
use ReflectionPropert... |
Check to make sure created file actually exists. | package com.miguelgaeta.media_picker;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@SuppressWarnings("UnusedDeclaration")
public class MediaPickerFile {
/**
* Create a file in the devices external storage.
*
* @param directory Target direc... | package com.miguelgaeta.media_picker;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@SuppressWarnings("UnusedDeclaration")
public class MediaPickerFile {
/**
* Create a file in the devices external storage.
*
* @param directory Target direc... |
Fix checking apikey outside runserver | from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication
from rest_framework import exceptions
from events.models import DataSource
from django.utils.translation import ugettext_lazy as _
class ApiKeyAuthentication(authentication.BaseAuthentication):
def authenticate(self, re... | from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication
from rest_framework import exceptions
from events.models import DataSource
from django.utils.translation import ugettext_lazy as _
class ApiKeyAuthentication(authentication.BaseAuthentication):
def authenticate(self, re... |
Fix serializer test with proper argument to FTLSerializer | 'use strict';
import fs from 'fs';
import path from 'path';
import assert from 'assert';
import FTLParser from '../../../../src/lib/format/ftl/ast/parser';
import FTLSerializer from '../../../../src/lib/format/ftl/ast/serializer';
var parse = FTLParser.parseResource;
function readFile(path) {
return new Promise(f... | 'use strict';
import fs from 'fs';
import path from 'path';
import assert from 'assert';
import FTLParser from '../../../../src/lib/format/ftl/ast/parser';
import FTLSerializer from '../../../../src/lib/format/ftl/ast/serializer';
var parse = FTLParser.parseResource;
function readFile(path) {
return new Promise(f... |
Support debug logging for gocd |
var path = require('path');
var yaml_config = require('node-yaml-config');
var _ = require('lodash');
function ymlHerokuConfigModule() {
var HEROKU_VARS_SUPPORT = [
'user', 'password', 'url', 'pipeline', 'jobs', 'key', 'secret', 'account', 'debug'
];
var create = function (configKey) {
var config;
... |
var path = require('path');
var yaml_config = require('node-yaml-config');
var _ = require('lodash');
function ymlHerokuConfigModule() {
var HEROKU_VARS_SUPPORT = [
'user', 'password', 'url', 'pipeline', 'jobs', 'key', 'secret', 'account'
];
var create = function (configKey) {
var config;
var id ... |
Change host name to ml.jaseg.net | package de.cketti.matelight;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class MateLight {
private static final String HOST = "ml.jaseg.net";
... | package de.cketti.matelight;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class MateLight {
private static final String HOST = "matelight.cbrp3... |
Join template on related content query | <?php
namespace Opifer\CmsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* Template Controller
*/
class TemplateController extends Controller
{
/**
* Remove a template
*
* @param int $id
*
* @return Respon... | <?php
namespace Opifer\CmsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* Template Controller
*/
class TemplateController extends Controller
{
/**
* Remove a template
*
* @param int $id
*
* @return Respon... |
Use the materialize CSS markup | <?php
namespace fieldwork\components;
class TextField extends Field
{
const ON_ENTER_NEXT = 'next';
const ON_ENTER_SUBMIT = 'submit';
private $onEnter = '',
$mask = null;
public function getAttributes ()
{
//$att = array('placeholder' => $this->label);
$att = array();
... | <?php
namespace fieldwork\components;
class TextField extends Field
{
const ON_ENTER_NEXT = 'next';
const ON_ENTER_SUBMIT = 'submit';
private $onEnter = '',
$mask = null;
public function getAttributes ()
{
$att = array('placeholder' => $this->label);
if (!empty($this->... |
Convert user to array on successful login | <?php namespace Lavoaster\LightBlog\User\Controllers;
use Lavoaster\LightBlog\User\Repositories\UserRepositoryInterface;
class UserController extends \BaseController
{
protected $user;
public function __construct(UserRepositoryInterface $user)
{
$this->user = $user;
}
public function lo... | <?php namespace Lavoaster\LightBlog\User\Controllers;
use Lavoaster\LightBlog\User\Repositories\UserRepositoryInterface;
class UserController extends \BaseController
{
protected $user;
public function __construct(UserRepositoryInterface $user)
{
$this->user = $user;
}
public function lo... |
Remove unnecessary middleware for now | <?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware =... | <?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware =... |
Update maxValues for fps anf cps | const series = {
fps: {
label: "FPS",
maxValue: 125,
color: "#F78900"
},
fpsMin: {
label: "FPS Min",
maxValue: 125,
color: "#800000"
},
cps: {
label: "CPS",
maxValue: 125,
... | const series = {
fps: {
label: "FPS",
maxValue: 65,
color: "#F78900"
},
fpsMin: {
label: "FPS Min",
maxValue: 65,
color: "#800000"
},
cps: {
label: "CPS",
maxValue: 65,
col... |
Add a "--force" argument to "bin/config done"
Summary:
Ref T11922. When we deploy on Saturday I need to rebuild all the cluster indexes, but some instances won't have anything indexed so they won't actually trigger the activity.
Add a `--force` flag that just clears an activity even if the activity is not required.
... | <?php
final class PhabricatorConfigManagementDoneWorkflow
extends PhabricatorConfigManagementWorkflow {
protected function didConstruct() {
$this
->setName('done')
->setExamples('**done** __activity__')
->setSynopsis(pht('Mark a manual upgrade activity as complete.'))
->setArguments(
... | <?php
final class PhabricatorConfigManagementDoneWorkflow
extends PhabricatorConfigManagementWorkflow {
protected function didConstruct() {
$this
->setName('done')
->setExamples('**done** __activity__')
->setSynopsis(pht('Mark a manual upgrade activity as complete.'))
->setArguments(
... |
Adjust rasa shell help test to changes. | from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
[--conversation-id CONVERSATION_ID] [-m MODEL]
[--log-file LOG_... | from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN... |
Use destructuring to access this.props.route properties | import React, {Component} from 'react';
import CourseList from './CourseList';
import GpaList from './GpaList';
import { loadSchedule, loadGpa } from '../../data-source';
export default class Schedule extends Component {
constructor(props, context) {
super(props, context);
this.state = {
schedule: nul... | import React, {Component} from 'react';
import CourseList from './CourseList';
import GpaList from './GpaList';
import { loadSchedule, loadGpa } from '../../data-source';
export default class Schedule extends Component {
constructor(props, context) {
super(props, context);
this.state = {
schedule: nul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.