text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix (JWT Service): Text files should end with a newline character | <?php
namespace AppBundle\Service;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
/**
* Class JwtService
* @package AppBundle\Service
*/
class JwtService{
private $ts;
/**
* JwtService constructor.
* @param TokenStorage $ts
*/
public function __construc... | <?php
namespace AppBundle\Service;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Doctrine\ORM\EntityManager;
/**
* Class JwtService
* @package AppBundle\Service
*/
class JwtService{
private $ts;
/**
* JwtService const... |
Set default value of property "initProperty" of custom object annotation. | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Mapping\Ann... | <?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Mapping\Ann... |
Handle Edge as an IE browser.
Edge was handled as a non IE browser, and no resize events was triggered. Not, when handling Edge as an IE browser, events are triggered again. | "use strict";
var detector = module.exports = {};
detector.isIE = function(version) {
function isAnyIeVersion() {
var agent = navigator.userAgent.toLowerCase();
return agent.indexOf("msie") !== -1 || agent.indexOf("trident") !== -1 || agent.indexOf(" edge/") !== -1;
}
if(!isAnyIeVersion()... | "use strict";
var detector = module.exports = {};
detector.isIE = function(version) {
function isAnyIeVersion() {
var agent = navigator.userAgent.toLowerCase();
return agent.indexOf("msie") !== -1 || agent.indexOf("trident") !== -1;
}
if(!isAnyIeVersion()) {
return false;
}
... |
Remove workaround for broken el.find() | import { NodeComponent } from 'substance'
import katex from 'katex'
export default class InlineFormulaComponent extends NodeComponent {
render($$) {
const node = this.props.node
const texMath = node.find('tex-math')
const el = $$('span').addClass('sc-inline-formula')
el.append(
$$(TexMathCompo... | import { NodeComponent } from 'substance'
import katex from 'katex'
export default class InlineFormulaComponent extends NodeComponent {
render($$) {
const node = this.props.node
// TODO: Find out why node.find('tex-math') returns null here
const texMath = node.findChild('tex-math')
const el = $$('sp... |
Update to use primary key instead of ID
Rule::unique($user->getTable())->ignore($user->getKey())
By default uses the user table of idColumn = id. Added additional attribute of getKeyName to use the primary key defined in the user table. | <?php
namespace Backpack\Base\app\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class AccountInfoRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{... | <?php
namespace Backpack\Base\app\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class AccountInfoRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{... |
Fix redirection to home on invalid token | <?php namespace Watson\Autologin;
use Auth, Redirect;
use Illuminate\Routing\Controller;
use Watson\Autologin\Interfaces\AuthenticationInterface;
use Watson\Autologin\Interfaces\AutologinInterface;
class AutologinController extends Controller {
/**
* AuthenticationInterface provider instance.
*
* @var \Studi... | <?php namespace Watson\Autologin;
use Auth, Redirect;
use Illuminate\Routing\Controller;
use Watson\Autologin\Interfaces\AuthenticationInterface;
use Watson\Autologin\Interfaces\AutologinInterface;
class AutologinController extends Controller {
/**
* AuthenticationInterface provider instance.
*
* @var \Studi... |
Add an id to the results. | const fetch = require('node-fetch')
const url = 'https://api.tumblr.com/v2/tagged?tag=pitbull&api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4'
module.exports = (pluginContext) => {
return {
respondsTo: (query) => {
return query === 'pibble'
},
search: (query, env = {}) => {
return ... | const fetch = require('node-fetch')
const url = 'https://api.tumblr.com/v2/tagged?tag=pitbull&api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4'
module.exports = (pluginContext) => {
return {
respondsTo: (query) => {
return query === 'pibble'
},
search: (query, env = {}) => {
return ... |
Fix error when multiple objects were returned for coordinators in admin | from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from locations.models import District
class Coordinator(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_manage... | from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from locations.models import District
class Coordinator(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_manage... |
Update the way we assert newly created contacts | const selectors = require('../../../../selectors')
const userActions = require('../../support/user-actions')
describe('Contacts', () => {
const data = {
name: 'NewAddress',
lastName: 'Contact',
jobTitle: 'Coffee machine operator',
countryCode: '44',
phone: '0778877778800',
email: 'company.con... | const selectors = require('../../../../selectors')
const userActions = require('../../support/user-actions')
describe('Contacts', () => {
const data = {
name: 'NewAddress',
lastName: 'Contact',
jobTitle: 'Coffee machine operator',
countryCode: '44',
phone: '0778877778800',
email: 'company.con... |
Make callback loader take into account directory names in loadable module name | # -*- coding: latin-1 -*-
'''
Created on 16.10.2012
@author: Teemu Pkknen
'''
import imp
import sys
import os
import ntpath
from qsdl.simulator.errors.ConfigurationInvalidError import ConfigurationInvalidError
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def g... | # -*- coding: latin-1 -*-
'''
Created on 16.10.2012
@author: Teemu Pkknen
'''
import imp
import sys
import os
from qsdl.simulator.errors.ConfigurationInvalidError import ConfigurationInvalidError
def get_callback_module( name ):
scriptDir = os.path.dirname(os.path.realpath(__file__))
# Already loaded?
... |
Fix error accessing class variable | '''
This module retrieves the course catalog and overviews of the Udacity API
Link to Documentation:
https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf
'''
import json
import requests
class UdacityAPI(object):
'''
This class defines attributes and method... | '''
This module retrieves the course catalog and overviews of the Udacity API
Link to Documentation:
https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf
'''
import json
import requests
class UdacityAPI(object):
'''
This class defines attributes and method... |
Fix failing bash completion function test signature. | import click
import pytest
if click.__version__ >= '3.0':
def test_legacy_callbacks(runner):
def legacy_callback(ctx, value):
return value.upper()
@click.command()
@click.option('--foo', callback=legacy_callback)
def cli(foo):
click.echo(foo)
with ... | import click
import pytest
if click.__version__ >= '3.0':
def test_legacy_callbacks(runner):
def legacy_callback(ctx, value):
return value.upper()
@click.command()
@click.option('--foo', callback=legacy_callback)
def cli(foo):
click.echo(foo)
with ... |
Update version, email and requirements
[ci skip] | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': """MiniCPS is a lightweight simulator for accurate network
traffic in an industrial control system, with basic support for physical
layer interaction.""",
'author': 'scy-phy',
... | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': """MiniCPS is a lightweight simulator for accurate network
traffic in an industrial control system, with basic support for physical
layer interaction.""",
'author': 'scy-phy',
... |
Add TODO's for improving admin experience for Event Content Listing | from icekit.plugins.content_listing.forms import ContentListingAdminForm
from icekit_events.models import EventBase
from .models import EventContentListingItem
class EventContentListingAdminForm(ContentListingAdminForm):
# TODO Improve admin experience:
# - horizontal filter for `limit_to_types` choice
... | from icekit.plugins.content_listing.forms import ContentListingAdminForm
from icekit_events.models import EventBase
from .models import EventContentListingItem
class EventContentListingAdminForm(ContentListingAdminForm):
class Meta:
model = EventContentListingItem
fields = '__all__'
def fi... |
Fix a bug in node 0.10 (and presumably other browsers) where the zero-width space is erroneously trimmed. | 'use strict';
var bind = require('function-bind');
var define = require('define-properties');
var replace = bind.call(Function.call, String.prototype.replace);
var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u20... | 'use strict';
var bind = require('function-bind');
var define = require('define-properties');
var replace = bind.call(Function.call, String.prototype.replace);
var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u20... |
Add Django version trove classifiers | # -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from setuptools import find_packages
setup(
name='django-password-reset',
version=__import__('password_reset').__version__,
author='Bruno Renie',
author_email='bruno@renie.fr',
p... | # -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from setuptools import find_packages
setup(
name='django-password-reset',
version=__import__('password_reset').__version__,
author='Bruno Renie',
author_email='bruno@renie.fr',
p... |
Rename argument, remove unusued one | <?php
/**
*@file
* Contains \Drupal\AppConsole\Generator\PluginImageEffectGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginImageEffectGenerator extends Generator
{
/**
* Generator Plugin Image Effect
* @param string $module Module name
* @param string $class_name Plugin Cla... | <?php
/**
*@file
* Contains \Drupal\AppConsole\Generator\PluginImageEffectGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginImageEffectGenerator extends Generator
{
/**
* Generator Plugin Image Effect
* @param string $module Module name
* @param string $class_name Plugin Cla... |
lxd/firewall/firewall/interface: Add NetworkSetup and remove feature specific network setup functions
Signed-off-by: Thomas Parrott <6b778ce645fb0e3dde76d79eccad490955b1ae74@canonical.com> | package firewall
import (
"net"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
drivers "github.com/lxc/lxd/lxd/firewall/drivers"
)
// Firewall represents a LXD firewall.
type Firewall interface {
String() string
Compat() (bool, error)
NetworkSetup(networkName string, opts drivers.Opts) error
NetworkClea... | package firewall
import (
"net"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
)
// Firewall represents a LXD firewall.
type Firewall interface {
String() string
Compat() (bool, error)
NetworkSetupForwardingPolicy(networkName string, ipVersion uint, allow bool) error
NetworkSetupOutboundNAT(networkName s... |
Add correct IIF and scope | /**
* @license
* Copyright (c) 2015 MediaMath Inc. All rights reserved.
* This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt
*/
(function (scope) {
scope.Action = Polymer({
is: "mm-action",
behaviors: [
StrandTraits.Stylable
],
properties: {
... | /**
* @license
* Copyright (c) 2015 MediaMath Inc. All rights reserved.
* This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt
*/
Polymer({
is: "mm-action",
behaviors: [
StrandTraits.Stylable
],
properties: {
ver:{
type:String,
value:"<<versio... |
Make sure the data is parse out as json from the server for SSE | 'use strict';
var glimpse = require('glimpse');
var polyfill = require('event-source')
var socket = (function() {
var connection;
var setup = function() {
connection = new polyfill.EventSource('/Glimpse/MessageStream');
connection.onmessage = function(e) {
if (!FAKE_SERVER) {
... | 'use strict';
var glimpse = require('glimpse');
var polyfill = require('event-source')
var socket = (function() {
var connection;
var setup = function() {
connection = new polyfill.EventSource('/Glimpse/MessageStream');
connection.onmessage = function(e) {
if (!FAKE_SERVER) {
... |
Use 0x04 for reset event since 0x00 is not supported | /**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | /**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
Revert "Fixed da bug. Right?"
This reverts commit 09c6aba54f7b73ab35b02b9f6b75462a3b3579a1. | // Auto-create new intput-groups
$(".js-lists").on("focus", ".disabled", function () {
var disabledRow = $(".input-group.disabled");
var newInputGroup = disabledRow.clone()[0];
disabledRow.removeClass("disabled").addClass("js-create-on-keypress");
$(".js-lists").one("keypress", ".js-create-on-keypress", function ()... | // Auto-create new intput-groups
$(".js-lists").on("focus", ".disabled", function () {
var disabledRow = $(".input-group.disabled");
var newInputGroup = disabledRow.clone()[0];
disabledRow.removeClass("disabled").addClass("js-create-on-keypress");
$(".js-lists").one("keypress", ".js-create-on-keypress", function ()... |
Remove Python 2.5 support, add support for Python 3.2 | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-uglifyjs',
version='0.1',
url='https://github.com/gears/gears-uglifyjs',
license='ISC',
author='Mike Yumatov',
author_email='... | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-uglifyjs',
version='0.1',
url='https://github.com/gears/gears-uglifyjs',
license='ISC',
author='Mike Yumatov',
author_email='... |
Fix loading of posts (lob) (again) | /*
* Copyright 2015 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | /*
* Copyright 2015 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... |
Replace call to deprecated virtool.file.processor | import os
import virtool.file
import virtool.utils
from virtool.handlers.utils import json_response, not_found
async def find(req):
db = req.app["db"]
query = {
"ready": True
}
file_type = req.query.get("type", None)
if file_type:
query["type"] = file_type
cursor = db.file... | import os
import virtool.file
import virtool.utils
from virtool.handlers.utils import json_response, not_found
async def find(req):
db = req.app["db"]
query = {
"ready": True
}
file_type = req.query.get("type", None)
if file_type:
query["type"] = file_type
cursor = db.file... |
Make the Bugsy PyPI page link to GitHub
Since there is currently no mention of the repo there.
Signed-off-by: AutomatedTester <3d61f6450d7e43c8b567795ed24e9858346487a0@mozilla.com> | from setuptools import setup, find_packages
setup(name='bugsy',
version='0.4.1',
description='A library for interacting Bugzilla Native REST API',
author='David Burns',
author_email='david.burns at theautomatedtester dot co dot uk',
url='https://github.com/AutomatedTester/Bugsy',
cl... | from setuptools import setup, find_packages
setup(name='bugsy',
version='0.4.1',
description='A library for interacting Bugzilla Native REST API',
author='David Burns',
author_email='david.burns at theautomatedtester dot co dot uk',
url='http://oss.theautomatedtester.co.uk/bugzilla',
... |
Use bootstrap utility to retrieve the configuration name from the environment. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Run a worker for the job queue."""
import sys
from redis import StrictRedis
from rq import Connection, Queue, Worker
from bootstrap.util import app_context, get_config_name_from_env
if __name__ == '__main__':
try:
config_name = get_config_name_from_env(... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Run a worker for the job queue."""
import os
import sys
from redis import StrictRedis
from rq import Connection, Queue, Worker
from bootstrap.util import app_context
if __name__ == '__main__':
config_name = os.environ.get('ENVIRONMENT')
if config_name is No... |
Make the expected Age header value a string because all header values are strings | /* eslint-env mocha */
"use strict";
const request = require("supertest");
const host = require("../helpers").host;
describe("Request with a If-None-Match value which is the same as the ETag", function() {
it(`responds with a 304 and an Age reset to 0`, function() {
this.timeout(30000);
return request(host)
... | /* eslint-env mocha */
"use strict";
const request = require("supertest");
const host = require("../helpers").host;
describe("Request with a If-None-Match value which is the same as the ETag", function() {
it(`responds with a 304 and an Age reset to 0`, function() {
this.timeout(30000);
return request(host)
... |
Rename offer signal to remove unused conditions/benefits | from django.db.models.signals import post_delete
from django.dispatch import receiver
from oscar.core.loading import get_model
ConditionalOffer = get_model('offer', 'ConditionalOffer')
Condition = get_model('offer', 'Condition')
Benefit = get_model('offer', 'Benefit')
@receiver(post_delete, sender=ConditionalOffer)... | from django.db.models.signals import post_delete
from django.dispatch import receiver
from oscar.core.loading import get_model
ConditionalOffer = get_model('offer', 'ConditionalOffer')
Condition = get_model('offer', 'Condition')
Benefit = get_model('offer', 'Benefit')
@receiver(post_delete, sender=ConditionalOffer)... |
Remove repeat option from coverage | # -*- coding: utf-8 -*-
"""py.test utilities."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import logging
import numpy as np
import warnings
import matplotlib
from phylib import add_defau... | # -*- coding: utf-8 -*-
"""py.test utilities."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import logging
import numpy as np
import warnings
import matplotlib
from phylib import add_defau... |
backend: Update logic on game controller | var inspect = require('eyes').inspector({ stream: null });
module.exports = {
index: function(req, res, next){
var project_id = req.query.project_id;
process.database.games.find({project_id: project_id}, function(error, games){
if(error){res.send(error); return false;}
games.toArray(function(... | var inspect = require('eyes').inspector({ stream: null });
module.exports = {
index: function(req, res, next){
var project_id = req.query.project_id;
process.database.games.find({project_id: project_id}, function(error, games){
if(error){res.send(error); return false;}
games.toArray(function(... |
Add support for an index mode | 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var getIndex = require( './get_index.js' );
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {...integer} idx - indices
* @throws {TypeError} provided indices must be integer valued
* @throws {Range... | 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {...integer} idx - indices
* @throws {TypeError} provided indices must be integer valued
* @throws {RangeError} index exceeds array dimensions
* @ret... |
Fix missing close for email logo file handle | from email.mime.image import MIMEImage
from django.contrib.staticfiles import finders
from .base import EmailBase
class PlatformEmailMixin:
"""
Attaches the static file images/logo.png so it can be used in an html
email.
"""
def get_attachments(self):
attachments = super().get_attachments... | from email.mime.image import MIMEImage
from django.contrib.staticfiles import finders
from .base import EmailBase
class PlatformEmailMixin:
"""
Attaches the static file images/logo.png so it can be used in an html
email.
"""
def get_attachments(self):
attachments = super().get_attachments... |
Remove "test" prefix from test methods for consistency
Fixes #19. | /*
* Copyright 2015-2017 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
packag... | /*
* Copyright 2015-2017 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
packag... |
Test sending a fresh message | import os
from flask import Flask, request
import twilio.twiml
from twilio.rest import TwilioRestClient
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.args.get('From')
text_content = request.args.get('Body').lower()
client = TwilioRestClient(os.environ... | import os
from flask import Flask, request, redirect, session
import twilio.twiml
from twilio.rest import TwilioRestClient
from charity import Charity
SECRET_KEY = os.environ['DONATION_SECRET_KEY']
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.values.get('From'... |
Replace hiding-face reaction with coffee reaction
The coffee reaction is meant to represent "BRB". | import m from 'mithril';
class ReactionPickerComponent {
oninit({ attrs: { game, session } }) {
this.game = game;
this.session = session;
}
sendReaction(reaction) {
this.session.emit('send-reaction', { reaction });
}
view() {
return m('div#reaction-picker', ReactionPickerComponent.availabl... | import m from 'mithril';
class ReactionPickerComponent {
oninit({ attrs: { game, session } }) {
this.game = game;
this.session = session;
}
sendReaction(reaction) {
this.session.emit('send-reaction', { reaction });
}
view() {
return m('div#reaction-picker', ReactionPickerComponent.availabl... |
Downgrade pytest version to be able to use default shippable minion |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'pelican-do',
'author': 'Commands to automate common pelican tasks',
'url': '',
'download_url': '',
'author_email': 'gustavoajz@gmail.com',
'version': '0.1',
'install_requires': [
'cl... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'pelican-do',
'author': 'Commands to automate common pelican tasks',
'url': '',
'download_url': '',
'author_email': 'gustavoajz@gmail.com',
'version': '0.1',
'install_requires': [
'cl... |
Update resource group unit test | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... |
Fix typo that was causing test failure.
git-svn-id: a346edc3f722475ad04b72d65977aa35d4befd55@543 3a26569e-5468-0410-bb2f-b495330926e5 | /*
* Copyright 2010 55 Minutes (http://www.55minutes.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by app... | /*
* Copyright 2010 55 Minutes (http://www.55minutes.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by app... |
Fix RDID reading code to ignore leading space | import serial
class iButton(object):
def __init__(self, ibutton_address, rfid_address, debug=False):
# self.ibutton_serial = serial.Serial(ibutton_address)
self.rfid_serial = serial.Serial(rfid_address)
self.debug = debug
def read(self):
if self.debug:
with open("i... | import serial
class iButton(object):
def __init__(self, ibutton_address, rfid_address, debug=False):
# self.ibutton_serial = serial.Serial(ibutton_address)
self.rfid_serial = serial.Serial(rfid_address)
self.debug = debug
def read(self):
if self.debug:
with open("i... |
Handle ActionBar possibly not existing. | package com.dglogik.mobile;
import android.app.ActivityManager;
import android.app.Service;
import android.app.*;
import android.graphics.*;
import android.graphics.drawable.*;
import android.content.Context;
import android.support.annotation.NonNull;
public class Utils {
public static boolean isServiceRunning(@N... | package com.dglogik.mobile;
import android.app.ActivityManager;
import android.app.Service;
import android.app.*;
import android.graphics.*;
import android.graphics.drawable.*;
import android.content.Context;
import android.support.annotation.NonNull;
public class Utils {
public static boolean isServiceRunning(@N... |
Fix detection of relative clause | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The Relative clauses class
class RelativeClauses:
# Constructor for the Relative Clauses class
def __init__(self):
self.has_wh_word = False
# Break the tree
def break_tree(self, tree):
t = Tree.fromstring(str(tree))
... | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The Relative clauses class
class RelativeClauses:
# Constructor for the Relative Clauses class
def __init__(self):
self.has_wh_word = False
# Break the tree
def break_tree(self, tree):
t = Tree.fromstring(str(tree))
... |
Change attribution message from 'by' to 'via' | var Twit = require('twit');
var config = require('./config.json');
var talks = require('libtlks').talk;
var T = new Twit({
consumer_key: config.twitterConsumerKey,
consumer_secret: config.twitterConsumerSecret,
access_token: config.workers.twitter.token,
access_token_secret: config.workers.twitter.sec... | var Twit = require('twit');
var config = require('./config.json');
var talks = require('libtlks').talk;
var T = new Twit({
consumer_key: config.twitterConsumerKey,
consumer_secret: config.twitterConsumerSecret,
access_token: config.workers.twitter.token,
access_token_secret: config.workers.twitter.sec... |
Fix namespace to work with sf2.2 | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\CoreBundle\Tests\Form\Type;
use Sonata\CoreBundle\Form... | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\CoreBundle\Tests\Form\Type;
use Sonata\CoreBundle\Form... |
Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2). | # pyinfra
# File: pyinfra_cli/__main__.py
# Desc: bootstrap stuff for the pyinfra CLI and provide it's entry point
import signal
import sys
import click
import gevent
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windo... | # pyinfra
# File: pyinfra_cli/__main__.py
# Desc: bootstrap stuff for the pyinfra CLI and provide it's entry point
import signal
import sys
import click
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windows ANSI color ... |
Improve examples to make composition order clear
Address comment made regarding ambiguous execution order:
https://github.com/Gozala/functional/commit/dda3adec7201114ef53356d4b4d5b93ce3c5c639#commitcomment-3348727 | "use strict";
var slicer = Array.prototype.slice
module.exports = compose
function compose() {
/**
Returns the composition of a list of functions, where each function
consumes the return value of the function that follows. In math
terms, composing the functions `f()`, `g()`, and `h()` produces
`f(g(h()))`.
... | "use strict";
var slicer = Array.prototype.slice
module.exports = compose
function compose() {
/**
Returns the composition of a list of functions, where each function
consumes the return value of the function that follows. In math
terms, composing the functions `f()`, `g()`, and `h()` produces
`f(g(h()))`.
... |
Update Item API handler to use api changes | <?php
header('Content-type:application/json');
// Object
require_once('./object/item.php');
// Service
// Database
require_once('./json/item.php');
// Initialize response.
$status = 500;
$body = [];
$header = '';
// Method router.
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
get();
break;
default:... | <?php
header('Content-type:application/json');
require_once('./json.php');
require_once('./objects/item.php');
/*
routes
*/
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
get();
break;
default:
http_response_code(405);
header('Allow: GET');
}
function get () {
switch ( count($_GET) ) {
... |
Fix formatting and spelling in block comment | /*
This package implements the leftpad function, inspired by the NPM (JS)
package of the same name.
Two functions are defined:
import "leftpad"
// pad with spaces
str, err := LeftPad(s, n)
// pad with specified character
str, err := func LeftPadStr(s, n, c)
*/
package leftpad
import (
"errors"
"fmt"
"s... | // leftpad.go
/*
This package implements the leftpad function, inspired by the NPM (JS)
package of the same name.
Two functions are defined:
import "leftpad"
// pad with spacex
str, err := LeftPad(s, n)
// pad with specified character
str, err := func LeftPadStr(s, n, c)
*/
package leftp... |
Fix migration error 'project_id' doesn't exist | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('project_use... | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('project_use... |
Remove some more unecessary @property doc comments | <?php
namespace PhpParser\Node\Expr;
use PhpParser\Node\Expr;
class AssignRef extends Expr
{
/** @var Expr Variable reference is assigned to */
public $var;
/** @var Expr Variable which is referenced */
public $expr;
/**
* Constructs an assignment node.
*
* @param Expr $var ... | <?php
namespace PhpParser\Node\Expr;
use PhpParser\Node\Expr;
/**
* @property Expr $var Variable reference is assigned to
* @property Expr $expr Variable which is referenced
*/
class AssignRef extends Expr
{
/** @var Expr Variable reference is assigned to */
public $var;
/** @var Expr Variable which ... |
Fix button for new versions | <?php
/*
This template expects following variables:
- Mandatory
$d: the object holding the goal
$p: the object describing the permissions
- Optional
*/
$parent = $d->parent;
$child = $d->child;
?>
@include('field', array('name' => 'name'))
@if(isset($p['own_page']) and $p['own_page'])
{{ link_to_route('goals.... | <?php
/*
This template expects following variables:
- Mandatory
$d: the object holding the goal
$p: the object describing the permissions
- Optional
*/
$parent = $d->parent;
$child = $d->child;
?>
@include('field', array('name' => 'name'))
@if($p['own_page'])
{{ link_to_route('goals.create', trans('ui.goals.n... |
Improve build task to run test before | ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsF... | ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsF... |
Define unicode in Python 3
__unicode__ was removed in Python 3 because all __str__ are Unicode.
[flake8](http://flake8.pycqa.org) testing of https://github.com/mwouts/jupytext on Python 3.7.0
$ __flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics__
```
./.jupyter/jupyter_notebook_con... | # coding: utf-8
import sys
import pytest
import jupytext
from .utils import list_all_notebooks
try:
unicode # Python 2
except NameError:
unicode = str # Python 3
@pytest.mark.parametrize('nb_file', list_all_notebooks('.ipynb') +
list_all_notebooks('.Rmd'))
def test_notebook_conte... | # coding: utf-8
import sys
import pytest
import jupytext
from .utils import list_all_notebooks
@pytest.mark.parametrize('nb_file', list_all_notebooks('.ipynb') +
list_all_notebooks('.Rmd'))
def test_notebook_contents_is_unicode(nb_file):
nb = jupytext.readf(nb_file)
for cell in nb.ce... |
Update to work with new versions of ember-cli | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-inject-asset-map',
// Add asset map hash to asset-map controller
postBuild: function (results) {
var fs = require('fs'),
path = require('path'),
colors = require('colors'),
tree = re... | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-inject-asset-map',
// Add asset map hash to asset-map controller
postBuild: function (results) {
console.log('Injecting asset map hash...');
var fs = require('fs'),
path = require('path'),
assetMap = res... |
Clean GET and POST params before create an instance | <?php
namespace AmoCRM;
class Client
{
private $parameters = null;
public function __construct($domain, $login, $apikey)
{
$this->parameters = new ParamsBag();
$this->parameters->addAuth('domain', $domain);
$this->parameters->addAuth('login', $l... | <?php
namespace AmoCRM;
class Client
{
private $parameters = null;
public function __construct($domain, $login, $apikey)
{
$this->parameters = new ParamsBag();
$this->parameters->addAuth('domain', $domain);
$this->parameters->addAuth('login', $l... |
Disable debug toolbar. It creates import problems | from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper additions
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
... | from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper additions
# ..........................
INSTALLED_APPS = (
'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
IN... |
Enable sourcemaps for easier debugging | var path = require('path');
var webpack = require('webpack')
var modules = {
preLoaders: [
{ test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ }
],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: [ 'es2015', 'rea... | var path = require('path');
var webpack = require('webpack')
var modules = {
preLoaders: [
{ test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ }
],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: [ 'es2015', 'rea... |
Add notice if config.php is missing | <?php
/**
* Gallery - A project for 'WPF - Moderne Webanwendungen' at
* Cologne University of Applied Sciences.
*
* @author Dominik Schilling <dominik.schilling@smail.fh-koeln.de>
* @author Laura Hermann
* @author Dario Vizzaccaro
* @link https://github.com/ocean90/wpfmw-gallery
* @license MIT
... | <?php
/**
* Gallery - A project for 'WPF - Moderne Webanwendungen' at
* Cologne University of Applied Sciences.
*
* @author Dominik Schilling <dominik.schilling@smail.fh-koeln.de>
* @author Laura Hermann
* @author Dario Vizzaccaro
* @link https://github.com/ocean90/wpfmw-gallery
* @license MIT
... |
Add method to check whether Vault is running. | 'use strict';
const AWS = require('aws-sdk');
const Err = require('./error');
const upload = require('multer')();
const rp = require('request-promise');
// Hit the Vault health check endpoint to see if we're actually working with a Vault server
/**
* Checks whether there is an actual Vault server running at the Va... | 'use strict';
const AWS = require('aws-sdk');
const Err = require('./error');
const upload = require('multer')();
module.exports = function Index(app) {
app.get('/', function(req, res, next) {
const KMS = new AWS.KMS({region: Config.get('aws:region')});
if (Config.get('aws:key')) {
return res.render(... |
Enable development mode and source maps for webpack | module.exports = {
entry: './src/app.js',
devtool: 'inline-source-map',
mode: 'development',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
... | module.exports = {
entry: './src/app.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.js$/,... |
Add an extension parameter to the save function. | #!/usr/bin/env python2
'''Read and write image files as NumPy arrays'''
from numpy import asarray, float32
from PIL import Image
from . import np
from . import utils
_DEFAULT_DTYPE = float32
_PIL_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def get_channels(img):
'''Return a list of channels of an image a... | #!/usr/bin/env python2
'''Read and write image files as NumPy arrays'''
from numpy import asarray, float32
from PIL import Image
from . import np
from . import utils
_DEFAULT_DTYPE = float32
_PIL_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def get_channels(img):
'''Return a list of channels of an image a... |
Drop TODO for getVmVersion method
Review URL: https://codereview.chromium.org/12324002
git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@1139 fc8a088e-31da-11de-8fef-1f5ae417a2df | // Copyright (c) 2009 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.
package org.chromium.sdk;
import java.io.IOException;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* Abstraction of a remote JavaSc... | // Copyright (c) 2009 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.
package org.chromium.sdk;
import java.io.IOException;
import org.chromium.sdk.util.MethodIsBlockingException;
/**
* Abstraction of a remote JavaSc... |
Add authentication for terminal websockets | """Tornado handlers for the terminal emulator."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
import terminado
from ..base.handlers import IPythonHandler
class TerminalHandler(IPythonHandler):
"""Render the terminal interface."""
... | """Tornado handlers for the terminal emulator."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
import terminado
from ..base.handlers import IPythonHandler
class TerminalHandler(IPythonHandler):
"""Render the terminal interface."""
... |
Add validation display_name and theme | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... |
Add combo editor tests
Add tests for adding and deleting a task from the combo task. | import { mount } from 'enzyme';
import React from 'react';
import assert from 'assert';
import ComboEditor from './editor';
import { workflow } from '../../../pages/dev-classifier/mock-data';
const task = {
type: 'combo',
loosen_requirements: true,
tasks: ['write', 'ask', 'features', 'draw', 'survey', 'slider']
... | import { shallow, mount } from 'enzyme';
import React from 'react';
import assert from 'assert';
import ComboEditor from './editor';
import { workflow } from '../../../pages/dev-classifier/mock-data';
const task = {
type: 'combo',
loosen_requirements: true,
tasks: ['write', 'ask', 'features', 'draw', 'survey', '... |
Make tag map available in Indonesian defaults | # coding: utf8
from __future__ import unicode_literals
from .stop_words import STOP_WORDS
from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .norm_exceptions import NORM_EXCEPTIONS
from .lemmatizer import LOOKUP
from .lex_attrs... | # coding: utf8
from __future__ import unicode_literals
from .stop_words import STOP_WORDS
from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .norm_exceptions import NORM_EXCEPTIONS
from .lemmatizer import LOOKUP
from .lex_attrs... |
Use the 'with' statement to create the PR2 object | #! /usr/bin/env python
import logging
logger = logging.getLogger("robots")
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)-15s %(name)s: %(levelname)s - %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
... | #! /usr/bin/env python
import logging
logger = logging.getLogger("robots")
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)-15s %(name)s: %(levelname)s - %(message)s')
console.setFormatter(formatter)
logger.addHandler(console)
... |
Resolve directories in the app folder | var webpack = require('webpack');
var path = require('path');
module.exports = {
context: __dirname + '/app',
entry: './index.js',
output: {
path: __dirname + '/bin',
publicPath: '/',
filename: 'bundle.js',
},
stats: {
colors: true,
progress: true,
},
resolve: {
extensions: [''... | var webpack = require('webpack');
var path = require('path');
module.exports = {
context: __dirname + '/app',
entry: './index.js',
output: {
path: __dirname + '/bin',
publicPath: '/',
filename: 'bundle.js',
},
stats: {
colors: true,
progress: true,
},
resolve: {
extensions: [''... |
Use err variable of getCpuInfo() | package cpu
import (
"io/ioutil"
"strings"
"regexp"
)
type Cpu struct{}
func (self *Cpu) Collect() (result map[string]map[string]string, err error) {
cpuinfo, err := getCpuInfo()
return map[string]map[string]string{
"cpu": cpuinfo,
}, err
}
func getCpuInfo() (cpuinfo map[string]string, err error) {
conten... | package cpu
import (
"io/ioutil"
"strings"
"regexp"
)
type Cpu struct{}
func (self *Cpu) Collect() (result map[string]map[string]string, err error) {
return map[string]map[string]string{
"cpu": getCpuInfo(),
}, err
}
func getCpuInfo() (cpuinfo map[string]string) {
contents, err := ioutil.ReadFile("/proc/cpu... |
Add way to unset static logger | <?php
namespace Kronos\Log;
use Kronos\Log\Writer\TriggerError;
class LogLocator
{
/**
* @var \Psr\Log\LoggerInterface
*/
private static $logger;
/**
* @param \Psr\Log\LoggerInterface $logger
* @param bool $force
*/
public static function setLogger(\Psr\Log\LoggerInterface ... | <?php
namespace Kronos\Log;
use Kronos\Log\Writer\TriggerError;
class LogLocator
{
/**
* @var \Psr\Log\LoggerInterface
*/
private static $logger;
/**
* @param \Psr\Log\LoggerInterface $logger
* @param bool $force
*/
public static function setLogger(\Psr\Log\LoggerInterface ... |
[api] Make API look like `net.Server` | var util = require('util'),
ws = require('ws'),
WebSocketServer = ws.Server,
EventEmitter2 = require('eventemitter2').EventEmitter2;
exports.createServer = function createServer(target) {
};
var WSProxy = exports.WSProxy = function (target) {
if (!target) {
throw new TypeError("No target given");
... | var ws = require('ws'),
WebSocketServer = ws.Server;
var WSProxy = exports.WSProxy = function (options) {
options || (options = {});
if (!options.target) {
throw new TypeError("No target given");
}
this.target = options.target;
if (!options.proxy || !options.proxy.port) {
throw new TypeError("N... |
Fix query for oldest (un-swapped) project | package uk.ac.ic.wlgitbridge.bridge.db.sqlite.query;
import uk.ac.ic.wlgitbridge.bridge.db.sqlite.SQLQuery;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by winston on 23/08/2016.
*/
public class GetOldestProjectName implements SQLQuery<String> {
private static final String GET_OLDEST... | package uk.ac.ic.wlgitbridge.bridge.db.sqlite.query;
import uk.ac.ic.wlgitbridge.bridge.db.sqlite.SQLQuery;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by winston on 23/08/2016.
*/
public class GetOldestProjectName implements SQLQuery<String> {
private static final String GET_OLDEST... |
Simplify the use of `phutil_get_library_root`
Summary:
Currently, in order to retrieve the library root of the current phutil module, the following code is required:
```lang=php
$library = phutil_get_current_library_name();
$root = phutil_get_library_root($library);
```
This can be simplified by allowing the use of ... | <?php
function phutil_get_library_root($library = null) {
if (!$library) {
$library = phutil_get_current_library_name();
}
$bootloader = PhutilBootloader::getInstance();
return $bootloader->getLibraryRoot($library);
}
function phutil_get_library_root_for_path($path) {
foreach (Filesystem::walkToRoot($pa... | <?php
function phutil_get_library_root($library) {
$bootloader = PhutilBootloader::getInstance();
return $bootloader->getLibraryRoot($library);
}
function phutil_get_library_root_for_path($path) {
foreach (Filesystem::walkToRoot($path) as $dir) {
if (Filesystem::pathExists($dir.'/__phutil_library_init__.php... |
Add basic element pickle cycle test | import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, ... | import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.... |
Create variables and initial loop | // Harmless Ransom Note
/* Rules:
Takes two parameters
First will be the note we want to write as a string.
The second will be the magazine text we have available to make the note out of as a string
The purpose of the algorithm is to see if we have enough words in the magazine text to write our note
If... | // Harmless Ransom Note
/* Rules:
Takes two parameters
First will be the note we want to write as a string.
The second will be the magazine text we have available to make the note out of as a string
The purpose of the algorithm is to see if we have enough words in the magazine text to write our note
If... |
Fix to use setOptions() syntax | <?php
/*
* This file is part of StashServiceProvider
*
* (c) Ben Tollakson <btollakson.os@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Bt51\Silex\Provider\StashServiceProvider;
use Silex\Application;
use ... | <?php
/*
* This file is part of StashServiceProvider
*
* (c) Ben Tollakson <btollakson.os@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Bt51\Silex\Provider\StashServiceProvider;
use Silex\Application;
use ... |
Add first name and last name to Admin employee list | from django.contrib import admin
from .models import Employee, Role
class RoleAdmin(admin.ModelAdmin):
list_display = ("name",)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ("username", "first_name", "last_name", "email",)
fieldsets = (
(None, {'fields': ('username', 'email', 'password')}... | from django.contrib import admin
from .models import Employee, Role
class RoleAdmin(admin.ModelAdmin):
list_display = ("name",)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ("username", "email",)
fieldsets = (
(None, {'fields': ('username', 'email', 'password')}),
('Personal info'... |
Remove is_upcoming field from Event response and Add explicit fields to EventActivity serializer | from .models import Event, EventActivity
from employees.serializers import LocationSerializer
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
location = LocationSerializer()
class Meta(object):
model = Event
depth = 1
fields = ("pk", "name", ... | from .models import Event, EventActivity
from employees.serializers import LocationSerializer
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
location = LocationSerializer()
class Meta(object):
model = Event
depth = 1
fields = ("pk", "name", ... |
Fix getting wireframe property of instance instead of the material | /**
* CG Space Invaders
* CG45179 16'17
*
* @author: Rui Ventura ( ist181045 )
* @author: Diogo Freitas ( ist181586 )
* @author: Sara Azinhal ( ist181700 )
*/
import { Object3D } from '../lib/threejs/core/Object3D';
import { MeshNormalMaterial } from '../lib/threejs/materials/MeshNormalMaterial';
class GameObj... | /**
* CG Space Invaders
* CG45179 16'17
*
* @author: Rui Ventura ( ist181045 )
* @author: Diogo Freitas ( ist181586 )
* @author: Sara Azinhal ( ist181700 )
*/
import { Object3D } from '../lib/threejs/core/Object3D';
import { MeshNormalMaterial } from '../lib/threejs/materials/MeshNormalMaterial';
class GameObj... |
Fix uptime and minor re-factoring | <?php
function collect_kernel($debug) {
$kernel = exec('uname -r') . " " . exec('uname -v');
if ($debug == TRUE) {
echo "[DEBUG_COLLECT] Kernel: " . $kernel . "\n";
}
return $kernel;
}
function collect_hostname($debug) {
$hostname = exec('uname -n');
if ($debug == TRUE) {
ec... | <?php
function collect_kernel($debug) {
$kernel = exec('uname -r')." ".exec('uname -v');
if ($debug == TRUE) {
echo "[DEBUG_COLLECT] Kernel: ".$kernel."\n";
}
return $kernel;
}
function collect_hostname($debug) {
$hostname = exec('uname -n');
if ($debug == TRUE) {
... |
Make callable statements work again for JDK 1.5 builds. Any code
int the jdbc3/Jdbc3 classes also needs to get into the corresponding
jdbc3g/Jdbc3g class. | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.4 2005/01/11 08:25:47 jurka Exp $
*
*--------------------------------------------... | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.3 2004/11/09 08:51:22 jurka Exp $
*
*--------------------------------------------... |
Remove duplicate implementation (already done in parent class). | <?php
namespace FluxBB\Markdown\Node;
class Blockquote extends Container implements NodeAcceptorInterface
{
public function acceptParagraph(Paragraph $paragraph)
{
$this->addChild($paragraph);
return $paragraph;
}
public function acceptBlockquote(Blockquote $blockquote)
{
... | <?php
namespace FluxBB\Markdown\Node;
class Blockquote extends Container implements NodeAcceptorInterface
{
public function acceptParagraph(Paragraph $paragraph)
{
$this->addChild($paragraph);
return $paragraph;
}
public function acceptHeading(Heading $heading)
{
$this->... |
Update name of url mapping for ProjectEntriesListAPIView | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from trex.views import project
urlpatterns = patterns(
'',
url(r"^$",
Te... | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from trex.views import project
urlpatterns = patterns(
'',
url(r"^$",
Te... |
Add Info to Weather Check
Add current weather status to weather check features. | from configparser import ConfigParser
from googletrans import Translator
import pyowm
import logging
import re
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
cfg = ConfigParser()
cfg.read('config')
api_key = cfg.get('auth', 'o... | from configparser import ConfigParser
from googletrans import Translator
import pyowm
import logging
import re
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
cfg = ConfigParser()
cfg.read('config')
api_key = cfg.get('auth', 'o... |
Increment PyPi package to 1.9.16.1 | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing MR lib."""
import distribute_setup
# User may not have setuptools installed on their machines.
# This script will automatically install the right version from PyPI.
distribute_setup.use_setuptools()
# pylint: disable=g-import-not-at-top... | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing MR lib."""
import distribute_setup
# User may not have setuptools installed on their machines.
# This script will automatically install the right version from PyPI.
distribute_setup.use_setuptools()
# pylint: disable=g-import-not-at-top... |
Add cast from varbinary to HLL | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribut... | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribut... |
Add all settings to populateStorage | 'use strict'
// Code thanks to MDN
export function storageAvailable (type) {
try {
let storage = window[type]
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (e) {
let storage = window[type]
return e instanceof DOMException && (
// everyt... | 'use strict'
// Code thanks to MDN
export function storageAvailable (type) {
try {
let storage = window[type]
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (e) {
let storage = window[type]
return e instanceof DOMException && (
// everyt... |
Print packet lengths in sniff | package main
import (
"log"
"time"
"github.com/ecc1/medtronic"
"github.com/ecc1/medtronic/packet"
)
const (
verbose = true
)
func main() {
if verbose {
log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC)
}
pump := medtronic.Open()
defer pump.Close()
for pump.Error() == nil {
p, rssi := pump.Radio.R... | package main
import (
"log"
"time"
"github.com/ecc1/medtronic"
"github.com/ecc1/medtronic/packet"
)
const (
verbose = true
)
func main() {
if verbose {
log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC)
}
pump := medtronic.Open()
defer pump.Close()
for pump.Error() == nil {
p, rssi := pump.Radio.R... |
Make sure "yaml" files are compatible too | <?php
namespace Orbitale\Bundle\EasyImpressBundle\DependencyInjection\Compiler;
use Orbitale\Bundle\EasyImpressBundle\Configuration\ConfigProcessor;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Finder\Finder;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Componen... | <?php
namespace Orbitale\Bundle\EasyImpressBundle\DependencyInjection\Compiler;
use Orbitale\Bundle\EasyImpressBundle\Configuration\ConfigProcessor;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Finder\Finder;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Componen... |
Simplify project banner on home page | import React from 'react'
import {
Card,
Box,
Text,
Icon,
Container,
Flex,
Link
} from '@hackclub/design-system'
export default () => (
<Container maxWidth={24} my={-3}>
<Link href="challenge">
<Card bg="blue.1" p={[2, 3]}>
<Flex justify="flex-start" align="center">
<Icon na... | import React from 'react'
import {
Card,
Box,
Text,
Icon,
Container,
Flex,
Link
} from '@hackclub/design-system'
export default () => (
<Container maxWidth={38}>
<Link href="challenge">
<Card bg="blue.1" p={[2, 3]} mt={-2} mb={4}>
<Flex justify="flex-start">
<Icon name="open... |
Return event dictionary at the end of the task. | from celery import Celery
from settings import SETTINGS
import requests
HOOKS = SETTINGS.get('hooks', [])
CELERY_SETTINGS = SETTINGS.get('celery', {})
app = Celery()
app.conf.update(**CELERY_SETTINGS)
@app.task
def dispatch_event(event):
event_repr = '%s:%s' % (event['id'][:10], event['status'])
for url in... | from celery import Celery
from settings import SETTINGS
import requests
HOOKS = SETTINGS.get('hooks', [])
CELERY_SETTINGS = SETTINGS.get('celery', {})
app = Celery()
app.conf.update(**CELERY_SETTINGS)
@app.task
def dispatch_event(event):
event_repr = '%s:%s' % (event['id'][:10], event['status'])
for url in... |
Update help message to use -model. | /*
word-server creates an HTTP server which exports endpoints for querying a word2vec model.
*/
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"github.com/sajari/word2vec"
)
var listen, modelPath string
func init() {
flag.StringVar(&listen, "listen", "localhost:1234", "bind `address` for HTTP serve... | /*
word-server creates an HTTP server which exports endpoints for querying a word2vec model.
*/
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"github.com/sajari/word2vec"
)
var listen, modelPath string
func init() {
flag.StringVar(&listen, "listen", "localhost:1234", "bind `address` for HTTP serve... |
Create an address if none exists for a user | from django.db import models
from bluebottle.bb_accounts.models import BlueBottleBaseUser
from bluebottle.utils.models import Address
from djchoices.choices import DjangoChoices, ChoiceItem
from django.conf import settings
from django.utils.translation import ugettext as _
class Member(BlueBottleBaseUser):
# Cre... | from django.db import models
from bluebottle.bb_accounts.models import BlueBottleBaseUser
from bluebottle.utils.models import Address
from djchoices.choices import DjangoChoices, ChoiceItem
from django.conf import settings
from django.utils.translation import ugettext as _
class Member(BlueBottleBaseUser):
pass
... |
Remove spammy warning which doesn't apply when stores check emails | from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from social_auth.utils import setting
from social_auth.models import UserSocialAuth
from social_auth.backends.pipeline import warn_setting
from social_auth.backends.exceptions import AuthException
def associate_by_email(details, user=None... | from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from social_auth.utils import setting
from social_auth.models import UserSocialAuth
from social_auth.backends.pipeline import warn_setting
from social_auth.backends.exceptions import AuthException
def associate_by_email(details, user=None... |
Enable markdown extensions for TOC and linebreaks | import bbcode
import markdown
import html
from c2corg_ui.format.wikilinks import C2CWikiLinkExtension
from markdown.extensions.nl2br import Nl2BrExtension
from markdown.extensions.toc import TocExtension
_markdown_parser = None
_bbcode_parser = None
def _get_markdown_parser():
global _markdown_parser
if no... | import bbcode
import markdown
import html
from c2corg_ui.format.wikilinks import C2CWikiLinkExtension
_markdown_parser = None
_bbcode_parser = None
def _get_markdown_parser():
global _markdown_parser
if not _markdown_parser:
extensions = [
C2CWikiLinkExtension(),
]
_mark... |
Add todo note in ExclusiveRegistrationForm. | from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationForm
from .models import WhitelistedUsername
User = get_user_model()
class ExclusiveRegistrationF... | from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationForm
from .models import WhitelistedUsername
User = get_user_model()
class ExclusiveRegistrationF... |
Change default section to Home | // @flow
import type { SectionType } from "../enums/Section.js";
import { ReduceStore } from "flux/utils";
import UniversalDispatcher from "./UniversalDispatcher.js";
import { Record } from "immutable";
import Section from "../enums/Section.js";
import url from "../utils/url.js";
export type NavigationActionType = {... | // @flow
import type { SectionType } from "../enums/Section.js";
import { ReduceStore } from "flux/utils";
import UniversalDispatcher from "./UniversalDispatcher.js";
import { Record } from "immutable";
import Section from "../enums/Section.js";
import url from "../utils/url.js";
export type NavigationActionType = {... |
Update TRPO, inconsistent results between Travis and local. | # Copyright 2017 reinforce.io. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2017 reinforce.io. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
Add ability to specify iteration count in Hash class. | <?php namespace System;
class Hash {
/**
* Hash a string using PHPass.
*
* PHPass provides reliable bcrypt hashing, and is used by many popular PHP
* applications such as Wordpress and Joomla.
*
* @access public
* @param string $value
* @return string
*/
public static function make($value, $roun... | <?php namespace System;
class Hash {
/**
* Hash a string using PHPass.
*
* PHPass provides reliable bcrypt hashing, and is used by many popular PHP
* applications such as Wordpress and Joomla.
*
* @access public
* @param string $value
* @return string
*/
public static function make($value)
{
... |
Remove force as it may overwrite somthing unwanted. | const spawn = require("./spawn");
module.exports = function(workDir, isDebug){
function git() {
var len = arguments.length;
var args = new Array(len);
for (var i = 0; i < len; i++) {
args[i] = arguments[i];
}
return spawn('git', args, {
cwd: workDir... | const spawn = require("./spawn");
module.exports = function(workDir, isDebug){
function git() {
var len = arguments.length;
var args = new Array(len);
for (var i = 0; i < len; i++) {
args[i] = arguments[i];
}
return spawn('git', args, {
cwd: workDir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.