text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add staticmethod annotation + docstrings to module, class, and all public methods | """Module with class representing common API."""
import requests
import os
class Api:
"""Class representing common API."""
_API_ENDPOINT = 'api/v1'
def __init__(self, url, token=None):
"""Set the API endpoint and store the authorization token if provided."""
self.url = Api.add_slash(url)... | import requests
import os
class Api:
_API_ENDPOINT = 'api/v1'
def __init__(self, url, token=None):
self.url = Api.add_slash(url)
self.token = token
def is_api_running(self):
try:
res = requests.get(self.url)
if res.status_code in {200, 401}:
... |
Use absolute url path for css asset | <?php defined('THISPATH') or die('Can\'t access directly!');
class Controller_home extends Panada {
public function __construct(){
parent::__construct();
}
public function index(){
$views['doc_type'] = $this->html->doctype('xhtml1-strict');
$views['css_file'] ... | <?php defined('THISPATH') or die('Can\'t access directly!');
class Controller_home extends Panada {
public function __construct(){
parent::__construct();
}
public function index(){
$views['doc_type'] = $this->html->doctype('xhtml1-strict');
$views['css_file'] ... |
Add argument handling for path and project name | import argparse
import sys
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.db.utils import DatabaseError
from django.db.transaction import rollback_unless_managed
from django.db import models
def get_model_info():
'''
Dump all models and their row counts... | import sys
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.db.utils import DatabaseError
from django.db.transaction import rollback_unless_managed
from django.db import models
def get_model_info():
'''
Dump all models and their row counts to the screen
... |
Return the authorization url when `authorize` fails
s.t. the user can manually authorize and set the token in `config.js` | /**
* The authorization token with which calls to the API are made.
* @type {String}
*/
let token = '';
const AUTHORIZE_ENDPOINT = 'https://www.dropbox.com/oauth2/authorize';
const getAuthorizationUrl = (clientId) => {
return AUTHORIZE_ENDPOINT + '?' +
'response_type=token' +
'client_id=' + clientId;
};
... | /**
* The authorization token with which calls to the API are made.
* @type {String}
*/
let token = '';
/**
* Authorize via OAuth 2.0 for Dropbox API calls.
*
* @parameter {string} clientId your app's key
* @parameter {string} redirectUri the uri where the user should be redirected
* to, after authorization ha... |
Make imports work when in .sublime-package | import os
import sys
try: # ST3
from .Lib.sublime_lib.path import get_package_name
PLUGIN_NAME = get_package_name()
path = os.path.dirname(__file__)
libpath = os.path.join(path, "Lib")
except ValueError: # ST2
# For some reason the import does only work when RELOADING the plugin, not
... | import os
import sys
try: # ST3
from .Lib.sublime_lib.path import get_package_name, get_package_path
PLUGIN_NAME = get_package_name()
libpath = os.path.join(get_package_path(), "Lib")
except ValueError: # ST2
# For some reason the import does only work when RELOADING the plugin, not
# ... |
Reset fields after document create | import Ember from 'ember';
export default Ember.Controller.extend({
previewVisible: false,
actions: {
togglePreview: function() {
this.toggleProperty('previewVisible');
},
saveDocument: function() {
var self = this;
var doc = this.store.createRecord('document', {
name: this.... | import Ember from 'ember';
export default Ember.Controller.extend({
previewVisible: false,
actions: {
togglePreview: function() {
this.toggleProperty('previewVisible');
},
saveDocument: function() {
var self = this;
var doc = this.store.createRecord('document', {
name: this.... |
Make configuration overrideable from /etc | <?php
require_once('IP2Country.php');
define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'dnscheckng');
define('DB_USER', 'dnscheckng');
define('DB_PASS', 'dnscheckng');
define('STATUS_OK', 'OK');
define('STATUS_WARN', 'WARNING');
define('STATUS_ERROR', 'ERROR');
define... | <?php
require_once('IP2Country.php');
define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'dnscheckng');
define('DB_USER', 'dnscheckng');
define('DB_PASS', 'dnscheckng');
define('STATUS_OK', 'OK');
define('STATUS_WARN', 'WARNING');
define('STATUS_ERROR', 'ERROR');
define... |
Make export button only export jpegs | export default {
standard: {
credits: { enabled: false },
chart: {
spacingBottom: 20,
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' ",
paddingTop: '20px' // Make room for buttons
}
},
exporting: {
buttons: {
contextButton: {
onclic... | export default {
standard: {
credits: { enabled: false },
chart: {
spacingBottom: 20,
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' ",
paddingTop: '20px' // Make room for buttons
}
},
exporting: {
buttons: {
contextButton: {
symbol... |
Improve trainer logging and print every logged message to console | from sft.sim.PathWorldGenerator import PathWorldGenerator
class SimplePathWorldGenerator(PathWorldGenerator):
def __init__(self, logger, view_size, world_size, sampler, path_in_init_view=False,
target_not_in_init_view=False):
# enforce simple paths consisting of one step, i.e. straight lines
super(SimplePa... | from sim.PathWorldGenerator import PathWorldGenerator
class SimplePathWorldGenerator(PathWorldGenerator):
def __init__(self, logger, view_size, world_size, sampler, path_in_init_view=False,
target_not_in_init_view=False):
# enforce simple paths consisting of one step, i.e. straight lines
super(SimplePathWo... |
Move variable declaration out of loop. | 'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
att... | 'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
att... |
Update author to Blanc Ltd | #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name='blanc-basic-events',
version='0.3.2',
description='Blanc Basic Events for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/blanc-basic-events',
maintainer='Blanc Ltd',
mainta... | #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name='blanc-basic-events',
version='0.3.2',
description='Blanc Basic Events for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/blanc-basic-events',
maintainer='Alex Tomkins',
mai... |
Revert "Need a check for an emtpy hash"
This reverts commit 07100389c363710260f4c0f5799da548672ad06a. | package ca.corefacility.bioinformatics.irida.model.sample;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
/**
* Stores unstructured metadata for ... | package ca.corefacility.bioinformatics.irida.model.sample;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
/**
* Stores unstructured metadata for ... |
Use new obit config to lookup sources and strategies | import { getOwner } from '@ember/application';
import Coordinator from '@orbit/coordinator';
import modulesOfType from '../system/modules-of-type';
export default {
create(injections = {}) {
const app = getOwner(injections);
let orbitConfig = app.lookup('ember-orbit:config');
let sourceNames;
if (in... | import { getOwner } from '@ember/application';
import Coordinator from '@orbit/coordinator';
import modulesOfType from '../system/modules-of-type';
export default {
create(injections = {}) {
const owner = getOwner(injections);
let sourceNames;
if (injections.sourceNames) {
sourceNames = injections... |
Change slider scroll count to 3 instead of 5 | $(function() {
//tabs
$('ul.tabs li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
})
//retina
retinajs();
//sticky navigation
$("#stick... | $(function() {
//tabs
$('ul.tabs li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
})
//retina
retinajs();
//sticky navigation
$("#stick... |
Make pip log world writable | """
Python Blueprint
================
Does not install python itself, only develop and setup tools.
Contains pip helper for other blueprints to use.
**Fabric environment:**
.. code-block:: yaml
blueprints:
- blues.python
"""
from fabric.decorators import task
from refabric.api import run, info
from refa... | """
Python Blueprint
================
Does not install python itself, only develop and setup tools.
Contains pip helper for other blueprints to use.
**Fabric environment:**
.. code-block:: yaml
blueprints:
- blues.python
"""
from fabric.decorators import task
from refabric.api import run, info
from refa... |
Add testStyles and prefixed to the depedencies. | define(['Modernizr', 'createElement', 'docElement', 'prefixed', 'testStyles'], function( Modernizr, createElement, docElement, prefixed, testStyles ) {
// http://www.w3.org/TR/css3-exclusions
// http://www.w3.org/TR/css3-exclusions/#shapes
// Examples: http://html.adobe.com/webstandards/cssexclusions
//... | define(['Modernizr', 'createElement', 'docElement'], function( Modernizr, createElement, docElement ) {
// http://www.w3.org/TR/css3-exclusions
// http://www.w3.org/TR/css3-exclusions/#shapes
// Examples: http://html.adobe.com/webstandards/cssexclusions
// Separate test for CSS shapes as WebKit has just... |
Disable cleaning of staged participants when retain interval specified is 0 days. | package com.krishagni.catissueplus.core.biospecimen.services.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import com.krishagni.catissueplus.core.administrative.domain.ScheduledJobRun;
import com.krishagni.catissueplus.core.admin... | package com.krishagni.catissueplus.core.biospecimen.services.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import com.krishagni.catissueplus.core.administrative.domain.ScheduledJobRun;
import com.krishagni.catissueplus.core.admin... |
Raise NotImplementedError instead of just passing in AttributeObject
That way, if somebody uses it directly, it will fail with a proper error. | class AttributeObject:
def __init__(self, *excluded_keys):
self._excluded_keys = excluded_keys
def __getattr__(self, item):
return self._getattr(item)
def __setattr__(self, key, value):
if key == "_excluded_keys" or key in self._excluded_keys:
super().__setattr__(key, v... | class AttributeObject:
def __init__(self, *excluded_keys):
self._excluded_keys = excluded_keys
def __getattr__(self, item):
return self._getattr(item)
def __setattr__(self, key, value):
if key == "_excluded_keys" or key in self._excluded_keys:
super().__setattr__(key, v... |
Stop using deprecated list_dir in the examples.
Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com> | #!/usr/bin/python2
# This is a simple example program to show how to use PyCdlib to open up an
# existing ISO passed on the command-line, and print out all of the file names
# at the root of the ISO.
# Import standard python modules.
import sys
# Import pycdlib itself.
import pycdlib
# Check that there are enough c... | #!/usr/bin/python2
# This is a simple example program to show how to use PyCdlib to open up an
# existing ISO passed on the command-line, and print out all of the file names
# at the root of the ISO.
# Import standard python modules.
import sys
# Import pycdlib itself.
import pycdlib
# Check that there are enough c... |
Change treeData to be explicitly declared. | // Auto-magically referenced. Yay.
$(document).ready(function() {
var rubyFolders = gon.folders;
var folders = {};
var currentId = gon.currentFolder.id;
// Convert all the folders to tree nodes.
rubyFolders.forEach(function(folder) {
var nameAndCount = folder.name + " (" + folder.count + ")";
f... | // Auto-magically referenced. Yay.
$(document).ready(function() {
var rubyFolders = gon.folders;
var folders = {};
var currentId = gon.currentFolder.id;
// Convert all the folders to tree nodes.
rubyFolders.forEach(function(folder) {
var nameAndCount = folder.name + " (" + folder.count + ")";
f... |
Fix model id to auto increment | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free ... | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free ... |
Add DirectoriesToChange field to sub.UpdateRequest message. | package sub
import (
"github.com/Symantec/Dominator/lib/filesystem"
"github.com/Symantec/Dominator/lib/hash"
"github.com/Symantec/Dominator/lib/triggers"
"github.com/Symantec/Dominator/proto/common"
"github.com/Symantec/Dominator/sub/scanner"
)
type Configuration struct {
ScanSpeedPercent uint
NetworkSpeedP... | package sub
import (
"github.com/Symantec/Dominator/lib/filesystem"
"github.com/Symantec/Dominator/lib/hash"
"github.com/Symantec/Dominator/lib/triggers"
"github.com/Symantec/Dominator/proto/common"
"github.com/Symantec/Dominator/sub/scanner"
)
type Configuration struct {
ScanSpeedPercent uint
NetworkSpeedP... |
Downgrade 'Failed to reconcile' from error to warning | from __future__ import absolute_import
from celery import shared_task
from django.core.exceptions import ValidationError
from wellsfargo.connector import actions
from wellsfargo.models import AccountMetadata
import logging
logger = logging.getLogger(__name__)
@shared_task(bind=True, ignore_result=True)
def reconcile... | from __future__ import absolute_import
from celery import shared_task
from django.core.exceptions import ValidationError
from wellsfargo.connector import actions
from wellsfargo.models import AccountMetadata
import logging
logger = logging.getLogger(__name__)
@shared_task(bind=True, ignore_result=True)
def reconcile... |
Fix typo in prop name | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class CandidateMatchCategory extends Component {
render() {
return (
<div className="candidate-match-category">
<div className="match-rate">
{this.props.matchRate}
... | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class CandidateMatchCategory extends Component {
render() {
return (
<div className="candidate-match-category">
<div className="match-rate">
{this.props.matchRate}
... |
Change to fireteam email address. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
from setuptools.dist import Distribution
with open(os.path.join(os.path.dirname(__file__), 'README')) as f:
doc = f.read()
class BinaryDistribution(Distribution):
def is_pure(self):
return False
setup(
name='json-stream',
vers... | # -*- coding: utf-8 -*-
import os
from setuptools import setup
from setuptools.dist import Distribution
with open(os.path.join(os.path.dirname(__file__), 'README')) as f:
doc = f.read()
class BinaryDistribution(Distribution):
def is_pure(self):
return False
setup(
name='json-stream',
vers... |
Use wraps decorator for requires_nltk_corpus | # -*- coding: utf-8 -*-
'''Custom decorators.'''
from __future__ import absolute_import
from functools import wraps
from textblob.exceptions import MissingCorpusException
class cached_property(object):
'''A property that is only computed once per instance and then replaces
itself with an ordinary attribute. ... | # -*- coding: utf-8 -*-
'''Custom decorators.'''
from __future__ import absolute_import
from textblob.exceptions import MissingCorpusException
class cached_property(object):
'''A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute reset... |
Update the mpl rcparams for mpl 2.0+ | def setup_text_plots(fontsize=8, usetex=True):
"""
This function adjusts matplotlib settings so that all figures in the
textbook have a uniform format and look.
"""
import matplotlib
from distutils.version import LooseVersion
matplotlib.rc('legend', fontsize=fontsize, handlelength=3)
mat... | def setup_text_plots(fontsize=8, usetex=True):
"""
This function adjusts matplotlib settings so that all figures in the
textbook have a uniform format and look.
"""
import matplotlib
matplotlib.rc('legend', fontsize=fontsize, handlelength=3)
matplotlib.rc('axes', titlesize=fontsize)
matp... |
Add new action : fetchData | import "babel-polyfill"
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import Counter from './Counter'
import reducer from './reducers'
import rootSaga from './sagas'
const sagaMiddleware = createSagaMiddle... | import "babel-polyfill"
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import Counter from './Counter'
import reducer from './reducers'
import rootSaga from './sagas'
const sagaMiddleware = createSagaMiddle... |
Refactor code and added new comments | /*Author: Peter Chow
*
*
* SudokuCapture will capture images from a webcam,
* using still image capture from the video, another thread will approximate the bounds of the board
* and try to scan in the values of the board for the program to use.
* After a successful scan, the program will solve the board and di... | import javax.swing.JFrame;
/*Author: Peter Chow
*
*
* SudokuCapture will capture images from a webcam,
* using still image capture from the video, another thread will approximate the bounds of the board
* and try to scan in the values of the board for the program to use.
* After a successful scan, the program ... |
Modify db client to __new__
change db singlton from instance() staticmethod to __new__() | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Ethan Zhang<http://github.com/Ethan-Zhang>
#
# 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/lice... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Ethan Zhang<http://github.com/Ethan-Zhang>
#
# 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/lice... |
Fix CI for node 6
Summary:
This file is executed without transforms so we can't have trailing commas in function calls until we drop node 6.
Closes https://github.com/facebook/relay/pull/2424
Differential Revision: D7754622
Pulled By: kassens
fbshipit-source-id: a3a54348cc4890616304c9ed5a739d4a92a9e305 | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @noformat
*/
'use strict';
module.exports = function(options) {
options = Object.assign(
{
env: 'production',
modu... | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
module.exports = function(options) {
options = Object.assign(
{
env: 'production',
mod... |
Remove duplicated db_object_type=protein from the test value for annotation properties. | package uk.ac.ebi.quickgo.index.annotation;
/**
* A class for creating stubbed annotations, representing rows of data read from
* annotation source files.
*
* Created 22/04/16
* @author Edd
*/
public class AnnotationMocker {
public static Annotation createValidAnnotation() {
Annotation annotation = n... | package uk.ac.ebi.quickgo.index.annotation;
/**
* A class for creating stubbed annotations, representing rows of data read from
* annotation source files.
*
* Created 22/04/16
* @author Edd
*/
public class AnnotationMocker {
public static Annotation createValidAnnotation() {
Annotation annotation = n... |
Add amount to payment at creation | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\CoreBundle\OrderProcessing;
use Sylius\Bundle\CoreBundle\Model\OrderInterface... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\CoreBundle\OrderProcessing;
use Sylius\Bundle\CoreBundle\Model\OrderInterface... |
Add the missing docs for the parameter. | /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR... | /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR... |
Move init_app after DJANGO_SETTINGS_MODULE set up | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
from website.app import init_app
init_app(set_backends=True, routes=False, attach_request_handlers=... | #!/usr/bin/env python
import os
import sys
from website.app import init_app
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
init_app(set_backends=True, routes=False, attach_request_handlers=False... |
Remove unnecessary else from formatAmount() method. | <?php
namespace Laravel\Cashier;
class Cashier
{
/**
* The custom currency formatter.
*
* @var callable
*/
protected static $formatCurrencyUsing;
/**
* Set the custom currency formatter.
*
* @param callable $callback
* @return void
*/
public static funct... | <?php
namespace Laravel\Cashier;
class Cashier
{
/**
* The custom currency formatter.
*
* @var callable
*/
protected static $formatCurrencyUsing;
/**
* Set the custom currency formatter.
*
* @param callable $callback
* @return void
*/
public static funct... |
[template] Change bare template to use function component | import * as React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
const instructions = Platform.select({
ios: `Press Cmd+R to reload,\nCmd+D or shake for dev menu`,
android: `Double tap R on your keyboard to reload,\nShake or press menu button for dev menu`,
});
export default funct... | import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu',
});
... |
Remove old and uneeded test dependencies | #!/usr/bin/env python
from setuptools import setup
__about__ = {}
with open("nacl/__about__.py") as fp:
exec(fp.read(), None, __about__)
try:
import nacl.nacl
except ImportError:
# installing - there is no cffi yet
ext_modules = []
else:
# building bdist - cffi is here!
ext_modules = [nacl.n... | #!/usr/bin/env python
from setuptools import setup
__about__ = {}
with open("nacl/__about__.py") as fp:
exec(fp.read(), None, __about__)
try:
import nacl.nacl
except ImportError:
# installing - there is no cffi yet
ext_modules = []
else:
# building bdist - cffi is here!
ext_modules = [nacl.n... |
Add more fields to Release serializer. | from rest_framework import serializers
from .models import Release, Track, Comment
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('id', 'comment')
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields... | from rest_framework import serializers
from .models import Release, Track, Comment
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('id', 'comment')
class TrackSerializer(serializers.ModelSerializer):
cdid = serializers.StringRelatedField(
re... |
Remove lat/long from zika download | import os,datetime
from download import download
from download import get_parser
class zika_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accessio... | import os,datetime
from download import download
from download import get_parser
class zika_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accessio... |
Remove line breaks from method signatures | package heroku.template.controller;
import heroku.template.model.Person;
import heroku.template.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bin... | package heroku.template.controller;
import heroku.template.model.Person;
import heroku.template.service.PersonService;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;... |
Use insert_text instead of changed | #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__insert_text(self, ent... | #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__changed(self, entry, ... |
Allow null being passed to fromXML | <?php
declare(strict_types=1);
namespace SAML2\XML;
use DOMElement;
/**
* Abstract class to be implemented by all the classes in this namespace
*
* @author Tim van Dijen, <tvdijen@gmail.com>
* @package SimpleSAMLphp
*/
abstract class AbstractConvertable
{
/**
* Output the class as an XML-formatted st... | <?php
declare(strict_types=1);
namespace SAML2\XML;
use DOMElement;
/**
* Abstract class to be implemented by all the classes in this namespace
*
* @author Tim van Dijen, <tvdijen@gmail.com>
* @package SimpleSAMLphp
*/
abstract class AbstractConvertable
{
/**
* Output the class as an XML-formatted st... |
Fix missing @api (see comment of Joachim Van der Auwera on GBE-247) | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contr... | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contr... |
Update parallel convergence test runs to not spawn OMP threads | import os
import time
import multiprocessing
threads = 4
os.environ["OMP_NUM_THREADS"] = "1"
dev_null = "/dev/null"
input_dir = "./convergence_inputs/"
log_file = "log.log"
call = "nice -n 19 ionice -c2 -n7 ../build/main.x "
call_end = " >> " + log_file
syscall_arr = []
input_files = os.listdir(input_dir)
if __... | import os
import time
import multiprocessing
threads = 4
dev_null = "/dev/null"
input_dir = "./convergence_inputs/"
log_file = dev_null
call = "nice -n 19 ionice -c2 -n7 ../build/main.x "
call_end = " >> " + log_file
syscall_arr = []
input_files = os.listdir(input_dir)
if __name__ == "__main__":
pool = multip... |
Trim whitespace from url input | if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
giblets: [
{ text: "This is task 1" },
{ text: "This is task 2" },
{ text: "This is task 3" }
]
});
// This code only runs on the client
Template.body.helpers({
giblets: function () {
retur... | if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
giblets: [
{ text: "This is task 1" },
{ text: "This is task 2" },
{ text: "This is task 3" }
]
});
// This code only runs on the client
Template.body.helpers({
giblets: function () {
retur... |
Set up continuous integration script | /*global desc, task, jake, fail, complete */
(function() {
"use strict";
desc("Build and test");
task("default", ["lint"]);
desc("Lint everything");
task("lint", [], function() {
var lint = require("./build/lint/lint_runner.js");
var files = new jake.FileList();
files.include("**/*.js");
files.exclude("... | /*global desc, task, jake, fail, complete */
(function() {
"use strict";
task("default", ["lint"]);
desc("Lint everything");
task("lint", [], function() {
var lint = require("./build/lint/lint_runner.js");
var files = new jake.FileList();
files.include("**/*.js");
files.exclude("node_modules");
var opt... |
Set min requirement for tornado-botocore | # coding: utf-8
from setuptools import setup, find_packages
setup(
name='tc_aws',
version='6.0.5',
description='Thumbor AWS extensions',
author='Thumbor-Community & William King',
author_email='willtrking@gmail.com',
zip_safe=False,
include_package_data=True,
packages=find_packages(),
... | # coding: utf-8
from setuptools import setup, find_packages
setup(
name='tc_aws',
version='6.0.5',
description='Thumbor AWS extensions',
author='Thumbor-Community & William King',
author_email='willtrking@gmail.com',
zip_safe=False,
include_package_data=True,
packages=find_packages(),
... |
Remove .md extension from CONTRIBUTING file | /*
* grunt-contrib-internal
* http://gruntjs.com/
*
* Copyright (c) 2012 Tyler Kellen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Add custom template delimiters.
grunt.template.addDelimiters('build-cfpb', '{%', '%}');
grunt.registerTask('build-c... | /*
* grunt-contrib-internal
* http://gruntjs.com/
*
* Copyright (c) 2012 Tyler Kellen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Add custom template delimiters.
grunt.template.addDelimiters('build-cfpb', '{%', '%}');
grunt.registerTask('build-c... |
Remove extra view from safeImage component | import React from 'react'
import { ImageBackground, ActivityIndicator, View } from 'react-native'
import css from '../../styles/css'
class SafeImage extends React.Component {
constructor(props) {
super(props)
this.state = { validImage: true, loading: true }
}
_handleError = (event) => {
console.log(`Error lo... | import React from 'react'
import { ImageBackground, ActivityIndicator, View } from 'react-native'
import css from '../../styles/css'
class SafeImage extends React.Component {
constructor(props) {
super(props)
this.state = { validImage: true, loading: true }
}
_handleError = (event) => {
console.log(`Error lo... |
Change to id from className | import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) =>
{
// Numb... | import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) =>
{
// Numb... |
Make it work with Py3 | from curses import wrapper
from ui import ChatUI
from client import Client
import configparser
def main(stdscr):
cp = configparser.ConfigParser()
cp.read('config.cfg')
username = cp.get('credentials', 'username')
password = cp.get('credentials', 'password').encode('utf-8')
stdscr.clear()
ui = ... | from curses import wrapper
from ui import ChatUI
from client import Client
import ConfigParser
def main(stdscr):
cp = ConfigParser.ConfigParser()
cp.read('config.cfg')
username = cp.get('credentials', 'username')
password = cp.get('credentials', 'password')
stdscr.clear()
ui = ChatUI(stdscr)
... |
fix(routes): Update to match express v4 API | /**
* Module dependencies
*/
var oidc = require('../oidc')
, settings = require('../boot/settings')
, User = require('../models/User')
;
/**
* Exports
*/
module.exports = function (server) {
/**
* UserInfo Endpoint
*/
server.get('/userinfo',
oidc.parseAuthorizationHeader,
oidc.... | /**
* Module dependencies
*/
var oidc = require('../oidc')
, settings = require('../boot/settings')
, User = require('../models/User')
;
/**
* Exports
*/
module.exports = function (server) {
/**
* UserInfo Endpoint
*/
server.get('/userinfo',
oidc.parseAuthorizationHeader,
oidc.... |
Move namedtuple definition outside of argspec function | import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.it... | import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.it... |
Configure single run of tests | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
process.env.CHROME_BIN = require('puppeteer').executablePath();
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angula... | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
process.env.CHROME_BIN = require('puppeteer').executablePath();
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angula... |
Fix incorrect ATerms being emitted for booleans | package org.metaborg.meta.interpreter.framework;
import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
public class TermUtils {
public static boolean boolFromTerm(IStratego... | package org.metaborg.meta.interpreter.framework;
import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
public class TermUtils {
public static boolean boolFromTerm(IStratego... |
Drop unused variables (make Uglify happy) | let React = require("react")
let ReactDOM = require("react-dom")
let Colr = require('colr')
let draggable = require('./higher_order_components/draggable.js')
@draggable({
updateClientCoords({clientY}) {
let rect = ReactDOM.findDOMNode(this).getBoundingClientRect()
let hue = this.getScaledValue((rect.bottom -... | let React = require("react")
let ReactDOM = require("react-dom")
let Colr = require('colr')
let draggable = require('./higher_order_components/draggable.js')
let { div } = React.DOM
@draggable({
updateClientCoords({clientX, clientY}) {
let rect = ReactDOM.findDOMNode(this).getBoundingClientRect()
let hue = t... |
Set DEBUG = False in production | from local_settings import *
settings.DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', ... | from local_settings import *
ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database fi... |
Enable much stricter CSP on the iframe | <?php
namespace Korobi\WebBundle\Controller;
use Korobi\WebBundle\Exception\NotImplementedException;
use Michelf\Markdown;
use Symfony\Component\HttpFoundation\Response;
class DocsController extends BaseController {
public function renderAction($file) {
if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) {
... | <?php
namespace Korobi\WebBundle\Controller;
use Korobi\WebBundle\Exception\NotImplementedException;
use Michelf\Markdown;
use Symfony\Component\HttpFoundation\Response;
class DocsController extends BaseController {
public function renderAction($file) {
if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) {
... |
Fix in error when analyze directories without duplicates | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... |
Remove default class switch-off (fix css bug when a switcher is set to true by default) | angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() {
return {
restrict: 'EA',
replace: true,
scope: {
model: '='
},
template: '<div class="switch" ng-click="toggle()"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="... | angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() {
return {
restrict: 'EA',
replace: true,
scope: {
model: '='
},
template: '<div class="switch" ng-click="toggle()"><div class="switch-animate switch-off" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><s... |
Add unique constraint to rid | # -*- coding: utf-8 -*-
"""
app.models
~~~~~~~~~~
Provides the SQLAlchemy models
"""
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
import savalidation.validators as val
from datetime import datetime as dt
from app import db
from savalidation... | # -*- coding: utf-8 -*-
"""
app.models
~~~~~~~~~~
Provides the SQLAlchemy models
"""
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
import savalidation.validators as val
from datetime import datetime as dt
from app import db
from savalidation... |
Fix class name in doc block
When putting the annotation back we forgot to use the aliased name. This
fixes it, making static analysers and IDEs work as expected.
More info: 31df2e805fe0cf184bdfcb528a696dc1daae40c3 | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject;
use PHPUnit\Framework\Mock... | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject;
use PHPUnit\Framework\Mock... |
Add cache support for ASN1_Packet()
--HG--
branch : fix-padding-after-pull-request-18 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
Packet holding data in Abstract Syntax Notation (ASN.1).
"""
from packet import *
class ASN1_Packet(Packet):
AS... | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
Packet holding data in Abstract Syntax Notation (ASN.1).
"""
from packet import *
class ASN1_Packet(Packet):
AS... |
Remove temporary code to tell if networktables is running on the robot, as it no longer works with the RoboRIO. | package org.ingrahamrobotics.robottables.util;
public class Platform {
private static final Object LOCK = new Object();
private static boolean ready = false;
private static boolean onRobot = false;
public static boolean onRobot() {
synchronized (LOCK) {
if (!ready) {
... | package org.ingrahamrobotics.robottables.util;
public class Platform {
private static final Object LOCK = new Object();
private static boolean ready = false;
private static boolean onRobot = false;
public static boolean onRobot() {
synchronized (LOCK) {
if (!ready) {
... |
Revert "apply caveman rate limiting to europe pmc api calls"
This reverts commit f2d0b4ab961325dfffaf3a54603b56e848f46da0. | #!/usr/bin/python
# -*- coding: utf-8 -*-
from cachetools import LRUCache
from kids.cache import cache
from http_cache import http_get
# examples
# https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3039489&resulttype=core&format=json&tool=oadoi
# https://www.ebi.ac.uk/europepmc/webservices/rest/searc... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from time import sleep
from cachetools import LRUCache
from kids.cache import cache
from http_cache import http_get
# examples
# https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3039489&resulttype=core&format=json&tool=oadoi
# https://www.ebi.ac.uk/europepm... |
Remove include that may be problematic on Azure Web Apps | const dotenv = require('dotenv');
const webpack = require('webpack');
dotenv.config({ silent: true });
module.exports = {
entry: [
'whatwg-fetch',
'./src/client/app.js'
],
output: {
path: './public/lib',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
... | const path = require('path');
const dotenv = require('dotenv');
const webpack = require('webpack');
dotenv.config({ silent: true });
module.exports = {
entry: [
'whatwg-fetch',
'./src/client/app.js'
],
output: {
path: './public/lib',
filename: 'bundle.js'
},
module: {
loaders: [
{
... |
Check if username was actually changed by the CSRF | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const models = require('../models/index')
const insecurity = require('../lib/insecurity')
const utils = require('../lib/utils')
const cache = require('../data/datacache')
const challenges = cache.challenges
module.exports = function u... | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const models = require('../models/index')
const insecurity = require('../lib/insecurity')
const utils = require('../lib/utils')
const cache = require('../data/datacache')
const challenges = cache.challenges
module.exports = function u... |
Add new "critically low" foreground trim level
Differential Revision: D10369483
fbshipit-source-id: c4a55701c31e8a9375f0ab6a9238e5247758d57d | /*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.common.memory;
/**
* Types of memory trim.
*
* <p>Each type of trim will provide a suggested trim ratio.
*
* <... | /*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.common.memory;
/**
* Types of memory trim.
*
* <p>Each type of trim will provide a suggested trim ratio.
*
* <... |
Make install_requires into an array | import os
import sys
from distutils.core import setup
# Don't import stripe module here, since deps may not be installed
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'stripe'))
import importer
import version
path, script = os.path.split(sys.argv[0])
os.chdir(os.path.abspath(path))
# Get simplejson if w... | import os
import sys
from distutils.core import setup
# Don't import stripe module here, since deps may not be installed
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'stripe'))
import importer
import version
path, script = os.path.split(sys.argv[0])
os.chdir(os.path.abspath(path))
# Get simplejson if w... |
Remove query from Sizes collection url
(cherry picked from commit ca808fb15f0ce3b6da46fb2198d88b8ed807fce1) | define(function (require) {
"use strict";
var Backbone = require('backbone'),
_ = require('underscore'),
Size = require('models/Size'),
globals = require('globals');
return Backbone.Collection.extend({
model: Size,
url: globals.API_V2_ROOT + "/sizes",
parse: function (response) {
... | define(function (require) {
"use strict";
var Backbone = require('backbone'),
_ = require('underscore'),
Size = require('models/Size'),
globals = require('globals');
return Backbone.Collection.extend({
model: Size,
url: globals.API_V2_ROOT + "/sizes?archived=true",
parse: function (res... |
Improve fetchOne to only return 1 result
Inspired by meteor's findOne | import createGraph from './lib/createGraph.js';
import prepareForProcess from './lib/prepareForProcess.js';
import hypernova from './hypernova/hypernova.js';
import Base from './query.base';
export default class Query extends Base {
/**
* Retrieves the data.
* @param context
* @returns {*}
*/
... | import createGraph from './lib/createGraph.js';
import prepareForProcess from './lib/prepareForProcess.js';
import hypernova from './hypernova/hypernova.js';
import Base from './query.base';
export default class Query extends Base {
/**
* Retrieves the data.
* @param context
* @returns {*}
*/
... |
Add method to serve prediction result files | import flask
from cref.app.web import app
from cref.app.web.tasks import predict_structure
def success(result):
return flask.jsonify({
'status': 'success',
'retval': result
})
def failure(reason='Unknown'):
return flask.jsonify({
'status': 'failure',
'reason': reason
... | import flask
from cref.app.web import app
from cref.app.web.tasks import predict_structure
def success(result):
return flask.jsonify({
'status': 'success',
'retval': result
})
def failure(reason='Unknown'):
return flask.jsonify({
'status': 'failure',
'reason': reason
... |
Fix SDK check methods NPE.
Summary: Ref T9503
Test Plan: done
Reviewers: fenghonghua, durunnan, xiewenliang
Reviewed By: durunnan
Maniphest Tasks: T9503
Differential Revision: https://phabricator.d.xiaomi.net/D63687 | package com.xiaomi.infra.galaxy.emq.client;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
/**
* Copyright 2015, Xiaomi.
* All rights reserved.
* Author: shenyuannan@xiaomi.com... | package com.xiaomi.infra.galaxy.emq.client;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Copyright 2015, Xiaomi.
* All rights reserved.
* Author: shenyuannan@xiaomi.com
*/
public class EMQCli... |
Exit with code 1 if tests fail.
Fixes #621 and Travis. | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path,... | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path,... |
Add ctrl-c support to quit.
Closes #4 | package main
import "github.com/nsf/termbox-go"
import "time"
import "flag"
func main() {
loops := flag.Int("loops", 0, "number of times to loop (default: infinite)")
flag.Parse()
err := termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
event_queue := make(chan termbox.Event)
go func() {
... | package main
import "github.com/nsf/termbox-go"
import "time"
import "flag"
func main() {
loops := flag.Int("loops", 0, "number of times to loop (default: infinite)")
flag.Parse()
err := termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
event_queue := make(chan termbox.Event)
go func() {
... |
Fix soname generation on non-Darwin Unix platforms.
Change-Id: Ifc2d7edf883072067b76a51368ea3e89172cff94
Reviewed-by: Christian Kandeler <3aa99dcdd3f0cac61fb81c2a11771c0cc2497607@theqtcompany.com> | var FileInfo = loadExtension("qbs.FileInfo");
function soname(product, outputFileName) {
if (product.moduleProperty("qbs", "targetOS").contains("darwin")) {
if (product.moduleProperty("bundle", "isBundle"))
outputFileName = product.moduleProperty("bundle", "executablePath");
var prefix ... | var FileInfo = loadExtension("qbs.FileInfo");
function soname(product, outputFileName) {
if (product.moduleProperty("qbs", "targetOS").contains("darwin")) {
if (product.moduleProperty("bundle", "isBundle"))
outputFileName = product.moduleProperty("bundle", "executablePath");
var prefix ... |
Remove queue too big logging. | package abra;
import htsjdk.samtools.DefaultSAMRecordFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import java.io.IOException;
import java.io.InputStream;
impor... | package abra;
import htsjdk.samtools.DefaultSAMRecordFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import java.io.IOException;
import java.io.InputStream;
impor... |
Remove uneccessary event reference from anonymous callback | import '@material/mwc-dialog';
import '@material/mwc-button';
import '@material/mwc-textfield';
import '../shared/demo-header';
addEventListener('load', function() {
document.body.classList.remove('unresolved');
});
const buttons = document.body.querySelectorAll('mwc-button[data-num]');
for (let i = 0; i < buttons... | import '@material/mwc-dialog';
import '@material/mwc-button';
import '@material/mwc-textfield';
import '../shared/demo-header';
addEventListener('load', function() {
document.body.classList.remove('unresolved');
});
const buttons = document.body.querySelectorAll('mwc-button[data-num]');
for (let i = 0; i < buttons... |
Add missed json to json() tweak | from __future__ import print_function
import json
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import GithubAPIClient
parser = ArghParser(description="Browse the GitHub API")
@arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")')
@arg('url', help='URL to browse')... | from __future__ import print_function
import json
from argh import ArghParser, arg
from ghtools import cli
from ghtools.api import GithubAPIClient
parser = ArghParser(description="Browse the GitHub API")
@arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")')
@arg('url', help='URL to browse')... |
Use domain name instead of localhost when it's available to make webpack works with local domain names | process.traceDeprecation = true;
const path = require('path');
const webpack = require('webpack');
const WebpackCommon = require('./webpack.common');
const BundleTracker = require('webpack-bundle-tracker');
var isPublicDomainDefined = process.env.KOBOFORM_PUBLIC_SUBDOMAIN &&
process.env.PUBLIC_DOMAIN_NAME;
var public... | process.traceDeprecation = true;
const path = require('path');
const webpack = require('webpack');
const WebpackCommon = require('./webpack.common');
const BundleTracker = require('webpack-bundle-tracker');
var publicPath = 'http://kpi.kobo.local:3000/static/compiled/';
module.exports = WebpackCommon({
mode: "develo... |
Update example to allow downgrading to http1 | var path = require('path');
var fs = require('fs');
var pino = require('pino');
var restify = require('../../lib');
var srv = restify.createServer({
http2: {
cert: fs.readFileSync(path.join(__dirname, './keys/http2-cert.pem')),
key: fs.readFileSync(path.join(__dirname, './keys/http2-key.pem')),
... | var path = require('path');
var fs = require('fs');
var pino = require('pino');
var restify = require('../../lib');
var srv = restify.createServer({
http2: {
cert: fs.readFileSync(path.join(__dirname, './keys/http2-cert.pem')),
key: fs.readFileSync(path.join(__dirname, './keys/http2-key.pem')),
... |
Improve message in version command when it cannot get server version | package io.digdag.cli.client;
import io.digdag.cli.SystemExitException;
import io.digdag.client.DigdagClient;
import java.util.Map;
import static io.digdag.cli.SystemExitException.systemExit;
public class Version extends ClientCommand
{
@Override
public void mainWithClientException()
throws Exce... | package io.digdag.cli.client;
import io.digdag.cli.SystemExitException;
import io.digdag.client.DigdagClient;
import java.util.Map;
import static io.digdag.cli.SystemExitException.systemExit;
public class Version extends ClientCommand
{
@Override
public void mainWithClientException()
throws Exce... |
Add generic Python 3 trove classifier | from setuptools import setup
setup(
name='tangled.mako',
version='0.1a3.dev0',
description='Tangled Mako integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.mako/tags',
author='Wyatt Baldwin',
... | from setuptools import setup
setup(
name='tangled.mako',
version='0.1a3.dev0',
description='Tangled Mako integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.mako/tags',
author='Wyatt Baldwin',
... |
Make SVG dimensions normalized and remove width and height attrs. | // @flow
import { NARROW_SPACE, WIDE_SPACE, NARROW_BAR, WIDE_BAR } from "../Core/Characters"
const NARROW_WIDTH = 1
const WIDE_WIDTH = 3
export function rect(x: number, wide: boolean, filled: boolean): string {
return `<rect x="${x}" y="0" width="${wide ? WIDE_WIDTH : NARROW_WIDTH}" height="1" fill="${filled ? "blac... | // @flow
import { NARROW_SPACE, WIDE_SPACE, NARROW_BAR, WIDE_BAR } from "../Core/Characters"
export function rect(x: number, height: number, width: number, filled: boolean): string {
return `<rect x="${x}" y="0" width="${width}" height="${height}" fill="${filled ? "black" : "white"}"/>`
}
export function renderBarco... |
Fix trait, methods are declared as abstract instead of inside docblock | <?php namespace GenericCollections\Traits;
/**
* This methods apply to BaseCollectionInterface and
* its shared between all the different AbstractCollections like
* AbstractCollection and AbstractMap
*
* This methods are declared to avoid warnings
*
* @package GenericCollections\Traits
*/
trait CollectionMetho... | <?php namespace GenericCollections\Traits;
/**
* This methods apply to BaseCollectionInterface and
* its shared between all the different AbstractCollections like
* AbstractCollection and AbstractMap
*
* This methods are declared to avoid warnings
* @method string getElementType()
* @method bool add(mixed $elem... |
Check whether or not email is taken already upon registration | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// use App\Http\Controllers\Controller;
use App\Currency;
use App\User;
use Hash;
class RegisterController extends Controller {
public function index() {
$currencies = Currency::all();
return view('register', compact('currencies... | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
// use App\Http\Controllers\Controller;
use App\Currency;
use App\User;
use Hash;
class RegisterController extends Controller {
public function index() {
$currencies = Currency::all();
return view('register', compact('currencies... |
Fix comment; They were never runes | // See LICENSE.txt for licensing information.
package main
import (
"fmt"
"strings"
)
var (
SPINNER_STRINGS = []string{"◢ ", "◣ ", "◤ ", "◥ "}
SPINNER_LEN = len(SPINNER_STRINGS)
)
type Spinner struct {
running bool // indiacte we're actually printing
msg string // current message
pos int ... | // See LICENSE.txt for licensing information.
package main
import (
"fmt"
"strings"
)
var (
SPINNER_STRINGS = []string{"◢ ", "◣ ", "◤ ", "◥ "}
SPINNER_LEN = len(SPINNER_STRINGS)
)
type Spinner struct {
running bool // indiacte we're actually printing
msg string // current message
pos int ... |
Remove dead code from `getNamesFromPattern`. | "use strict";
exports.getNamesFromPattern = function (pattern) {
var queue = [pattern];
var names = [];
for (var i = 0; i < queue.length; ++i) {
var pattern = queue[i];
switch (pattern.type) {
case "Identifier":
names.push(pattern.name);
break;
case "Property":
case "ObjectPrope... | "use strict";
exports.getNamesFromPattern = function (pattern) {
var queue = [pattern];
var names = [];
for (var i = 0; i < queue.length; ++i) {
var pattern = queue[i];
if (! pattern) {
continue;
}
switch (pattern.type) {
case "Identifier":
names.push(pattern.name);
break;... |
Allow Glazebrook to be executed in a multi-pass fashion + parallelise | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Produces IPHAS Data Release 2 using an MPI computing cluster."""
from IPython import parallel
from astropy import log
__author__ = 'Geert Barentsen'
# Create the cluster view
client = parallel.Client('/home/gb/.config/ipython/profile_mpi/security/ipcontroller-seaming-c... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Produces IPHAS Data Release 2 using an MPI computing cluster."""
from IPython import parallel
from astropy import log
__author__ = 'Geert Barentsen'
# Create the cluster view
client = parallel.Client('/home/gb/.config/ipython/profile_mpi/security/ipcontroller-seaming-c... |
Update example autograding code to use heading names | from nose.tools import eq_ as assert_eq
@score(problem="Problem 1/Part A", points=0.5)
def grade_hello1():
"""Grade 'hello' with input 'Jessica'"""
msg = hello("Jessica")
assert_eq(msg, "Hello, Jessica!")
@score(problem="Problem 1/Part A", points=0.5)
def grade_hello2():
"""Grade 'hello' with input ... | from nose.tools import eq_ as assert_eq
@score(problem="hello", points=0.5)
def grade_hello1():
"""Grade 'hello' with input 'Jessica'"""
msg = hello("Jessica")
assert_eq(msg, "Hello, Jessica!")
@score(problem="hello", points=0.5)
def grade_hello2():
"""Grade 'hello' with input 'Python'"""
msg = he... |
:bug: Fix a bug affecting shared workers | 'use babel'
import {Disposable, CompositeDisposable} from 'sb-event-kit'
import Communication from 'sb-communication'
class Exchange {
constructor(worker) {
this.worker = worker
this.port = worker.port || worker
this.communication = new Communication()
this.subscriptions = new CompositeDisposable()... | 'use babel'
import {Disposable, CompositeDisposable} from 'sb-event-kit'
import Communication from 'sb-communication'
class Exchange {
constructor(worker) {
this.worker = worker
this.port = worker.port || worker
this.communication = new Communication()
this.subscriptions = new CompositeDisposable()... |
Improve security by creating a much stronger secret by default
Webs using vkwf are not effected by this as they use hashPrivatePart config setting | <?php
class Kwf_Util_Hash
{
public static function getPrivatePart()
{
$salt = Kwf_Cache_SimpleStatic::fetch('hashpp-');
if (!$salt) {
if ($salt = Kwf_Config::getValue('hashPrivatePart')) {
//defined in config, required if multiple webservers should share the same salt... | <?php
class Kwf_Util_Hash
{
public static function getPrivatePart()
{
$salt = Kwf_Cache_SimpleStatic::fetch('hashpp-');
if (!$salt) {
if ($salt = Kwf_Config::getValue('hashPrivatePart')) {
//defined in config, required if multiple webservers should share the same salt... |
Fix code style for custom attribute value | # Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: laran@reciprocitylabs.com
# Maintained By: laran@reciprocitylabs.com
from ggrc import db
from ggrc.models.mixins import Base
from ggrc.models.mixin... | # Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: laran@reciprocitylabs.com
# Maintained By: laran@reciprocitylabs.com
from ggrc import db
from .mixins import (
deferred, Base
)
class Cust... |
Change the order of execution of various commands | <?php
namespace Rafni\LaravelToolkit\Console\Scaffolding;
use Illuminate\Console\Command;
class PackageBuilder extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'toolkit:package {name : Name of the service package in singular}... | <?php
namespace Rafni\LaravelToolkit\Console\Scaffolding;
use Illuminate\Console\Command;
class PackageBuilder extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'toolkit:package {name : Name of the service package in singular}... |
Fix the path to fake database data | import json
from meetup_facebook_bot import server
from meetup_facebook_bot.models import base, talk, speaker
base.Base.metadata.create_all(bind=server.engine)
session = server.Session()
# This part of the script provides the app with mockup data
# TODO: replace it with actually working method
json_talks = []
with ... | import json
from meetup_facebook_bot import server
from meetup_facebook_bot.models import base, talk, speaker
base.Base.metadata.create_all(bind=server.engine)
session = server.Session()
# This part of the script provides the app with mockup data
# TODO: replace it with actually working method
json_talks = []
with ... |
Fix task to output coverage for every files | var es = require("event-stream");
var path = require("path");
"use strict";
var istanbul = require("istanbul");
var hook = istanbul.hook;
var Report = istanbul.Report;
var Collector = istanbul.Collector;
var instrumenter = new istanbul.Instrumenter();
var plugin = module.exports = function () {
var fileMap = {};
... | var es = require("event-stream");
var path = require("path");
"use strict";
var istanbul = require("istanbul");
var hook = istanbul.hook;
var Report = istanbul.Report;
var Collector = istanbul.Collector;
var instrumenter = new istanbul.Instrumenter();
var plugin = module.exports = function (param) {
function crea... |
REF: Isolate import error to DataBroker. | import warnings
import logging
logger = logging.getLogger(__name__)
try:
from .databroker import DataBroker
except ImportError:
warnings.warn("The top-level functions (get_table, get_events, etc.)"
"cannot be created because "
"the necessary configuration was not found.")... | import warnings
import logging
logger = logging.getLogger(__name__)
try:
from .databroker import (DataBroker, DataBroker as db,
get_events, get_table, stream, get_fields,
restream, process)
from .pims_readers import get_images
from .handler_regis... |
Rename mana level to mana pool | import React from 'react';
import PropTypes from 'prop-types';
import ManaLevelGraph from 'Main/ManaLevelGraph';
import ManaUsageGraph from 'Main/ManaUsageGraph';
const Mana = ({ parser }) => (
<div>
<h1>Mana pool</h1>
<ManaLevelGraph
reportCode={parser.report.code}
actorId={parser.playerId}
... | import React from 'react';
import PropTypes from 'prop-types';
import ManaLevelGraph from 'Main/ManaLevelGraph';
import ManaUsageGraph from 'Main/ManaUsageGraph';
const Mana = ({ parser }) => (
<div>
<h1>Mana level</h1>
<ManaLevelGraph
reportCode={parser.report.code}
actorId={parser.playerId}
... |
Switch to Iriscouch in production | var cradle = require('cradle');
var applyDesignDocuments = require('./design-documents');
var couchLocation = process.env.IRISCOUCH;
// var couchLocation = process.env.CLOUDANT_URL || process.env.COUCHDB || 'http://localhost';
var couch = new(cradle.Connection)(couchLocation, 5984, {
cache: true,
raw: false
});
v... | var cradle = require('cradle');
var applyDesignDocuments = require('./design-documents');
var couchLocation = process.env.CLOUDANT_URL || process.env.COUCHDB || 'http://localhost';
var couch = new(cradle.Connection)(couchLocation, 5984, {
cache: true,
raw: false
});
var db = couch.database('emergencybadges');
db... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.