text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use asyncio.run() to run the test client.
This makes for cleaner code. | import asyncio
import platform
import time
from zeep import AsyncClient
from zeep.cache import InMemoryCache
from zeep.transports import AsyncTransport
# Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client
# Allow CTRL+C on windows console w/ asyncio
if platform.system() == "Wi... | import asyncio
import platform
import time
from zeep import AsyncClient
from zeep.cache import InMemoryCache
from zeep.transports import AsyncTransport
# Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client
# Allow CTRL+C on windows console w/ asyncio
if platform.system() == "Wi... |
Add a check for an array to prevent fatal error | <?php
/**
* Go! OOP&AOP PHP framework
*
* @copyright Copyright 2013, Lissachenko Alexander <lisachenko.it@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace Go\Instrument\ClassLoading;
use Go\Instrument\ClassLoading\UniversalClassLoader;
/**
* Ensures... | <?php
/**
* Go! OOP&AOP PHP framework
*
* @copyright Copyright 2013, Lissachenko Alexander <lisachenko.it@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace Go\Instrument\ClassLoading;
use Go\Instrument\ClassLoading\UniversalClassLoader;
/**
* Ensures... |
Disable one more graph test | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.graphrbac;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit... | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.graphrbac;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit... |
Rename Legal to Data policy | import React from 'react'
import './Footer.scss'
export const Footer = () => (
<div className='footer'>
<div className='container'>
<ul className='footer-links'>
<li>
<a href='https://ooni.torproject.org/about/'>About OONI</a>
</li>
<li>
<a href='https://ooni.tor... | import React from 'react'
import './Footer.scss'
export const Footer = () => (
<div className='footer'>
<div className='container'>
<ul className='footer-links'>
<li>
<a href='https://ooni.torproject.org/about/'>About OONI</a>
</li>
<li>
<a href='https://ooni.tor... |
Update test to cover windows environment
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
namespace Orchestra\Tenanti\Tests\Unit\Migrator;
use Mockery as m;
use Orchestra\Tenanti\Migrator\Creator;
use PHPUnit\Framework\TestCase;
class CreatorTest extends TestCase
{
/**
* Teardown the test environment.
*/
protected function tearDown(): void
{
m::close();
}
/**
... | <?php
namespace Orchestra\Tenanti\Tests\Unit\Migrator;
use Mockery as m;
use Orchestra\Tenanti\Migrator\Creator;
use PHPUnit\Framework\TestCase;
class CreatorTest extends TestCase
{
/**
* Teardown the test environment.
*/
protected function tearDown(): void
{
m::close();
}
/**
... |
Remove rogue debugger how embarassing | from rest_framework import serializers as ser
from api.base.utils import absolute_reverse
from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
filterable_fields = frozenset(['categor... | from rest_framework import serializers as ser
from api.base.utils import absolute_reverse
from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
filterable_fields = frozenset(['categor... |
Featured-image: Stop limiting error handling for aggregated requests
Several feed endpoints have graceful error handling for aggregated
requests, meant to allow RESTBase to gracefully omit featured feed
content where the underlying content is not found as expected.
For the featured image endpoint, this is limited to ... | /**
* To retrieve the picture of the day for a given date.
*/
'use strict';
const BBPromise = require('bluebird');
const dateUtil = require('../dateUtil');
const imageinfo = require('../imageinfo');
/**
* Get imageinfo data for featured image (Picture of the day)
* @param {Object} req req Server request
*... | /**
* To retrieve the picture of the day for a given date.
*/
'use strict';
const BBPromise = require('bluebird');
const dateUtil = require('../dateUtil');
const sUtil = require('../util');
const imageinfo = require('../imageinfo');
const HTTPError = sUtil.HTTPError;
/**
* Get imageinfo data for featured image (P... |
Fix encoding issue when test lcd | # -*- coding: utf-8 -*-
import unittest
from ev3.ev3dev import Lcd
from util import get_input
import time
from PIL import Image,ImageDraw,ImageFont
class TestLcd(unittest.TestCase):
def test_lcd(self):
get_input('Test lcd')
d= Lcd()
d.draw.ellipse((20, 20, 60, 60))
d.update(... | from ev3.ev3dev import Lcd
# -*- coding: utf-8 -*-
import unittest
from util import get_input
import time
from PIL import Image,ImageDraw,ImageFont
class TestLcd(unittest.TestCase):
def test_lcd(self):
get_input('Test lcd')
d= Lcd()
d.draw.ellipse((20, 20, 60, 60))
d.update(... |
Convert tabs to spaces in source. | /* Hover Image Replacement Plug-in for jQuery
*
* Authors:
* Sam Moore - sam@hashtack.com
*
* Adds a query function to swap the 'src' attribute
* of the given img tag to a desired URL on hover.
*
*/
(function ( $ ) {
swapImageSrc = function (image) {
oldSrc = image.attr('src');
newSrc = image.at... | /* Hover Image Replacement Plug-in for jQuery
*
* Authors:
* Sam Moore - sam@hashtack.com
*
* Adds a query function to swap the 'src' attribute
* of the given img tag to a desired URL on hover.
*
*/
(function ( $ ) {
swapImageSrc = function (image) {
oldSrc = image.attr('src');
newSrc = image.att... |
Add missing 'use SA\CpeSDK' in SWF HAndler | <?php
namespace SA\CpeSdk\Swf;
use Aws\Swf\SwfClient;
// SA Cpe SDK
use SA\CpeSdk;
/**
* Create the AWS SWF connection
* Check for AWS environment variables
*/
class CpeSwfHandler
{
public $swf;
public function __construct()
{
# Check if preper env vars are setup
if (!($region = ... | <?php
namespace SA\CpeSdk\Swf;
use Aws\Swf\SwfClient;
/**
* Create the AWS SWF connection
* Check for AWS environment variables
*/
class CpeSwfHandler
{
public $swf;
public function __construct()
{
# Check if preper env vars are setup
if (!($region = getenv("AWS_DEFAULT_REGION")))... |
Support correctly weird characters in filenames when downloading
This commit add support for the following:
- Correctly encoded oData parameter sent to the endpoint.
- Support for # and % in filenames by using a newer 365 endpoint.
Summary:
Current implementation was injecting an URL directly quoted to
the endpoint,... | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
... | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
"""
A download file content query
:type file_url: ... |
Update PSR-2 and remove unused use
Former-commit-id: e54069691862a3c7d4249b624a720b9a536875cc | <?php
namespace Concrete\Core\Form\Service\Widget;
use View;
class Typography
{
/**
* Creates form fields and JavaScript includes to add a font picker widget.
* <code>
* $dh->output('background-color', '#f00');
* </code>
* @param string $inputName
* @param array $value
* @par... | <?php
namespace Concrete\Core\Form\Service\Widget;
use Loader;
use View;
use Request;
class Typography {
/**
* Creates form fields and JavaScript includes to add a font picker widget.
* <code>
* $dh->output('background-color', '#f00');
* </code>
* @param string $inputName
* @para... |
Fix ConnectedSWFObject: pass default value to pop() | # -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attribu... | # -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attribu... |
Clear create comment form after posting. | module.exports = Zeppelin.FormView.extend({
className: 'create-comment',
formSelector: 'form.create-comment-form',
template: require('account/templates/create-comment'),
model: require('core/models/comment'),
elements: {
'commentInput': 'textarea.create-comment-input'
},
events: {
'click [dat... | module.exports = Zeppelin.FormView.extend({
className: 'create-comment',
formSelector: 'form.create-comment-form',
template: require('account/templates/create-comment'),
model: require('core/models/comment'),
elements: {
'commentInput': 'textarea.create-comment-input'
},
events: {
'click [dat... |
Fix model definition in signature form | from petition.forms import BaseSignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
import swapper
Signature = swapper.load_model("petition", "Signature")
class SignatureForm(BaseSignatureForm):
def __init__(self, *args, **kwargs):
super(SignatureForm, sel... | from petition.forms import BaseSignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
class SignatureForm(BaseSignatureForm):
def __init__(self, *args, **kwargs):
super(SignatureForm, self).__init__(*args, **kwargs)
self.helper.layout = Layout(
... |
Set updatedAt field on insertion | events = {};
events.beforeInsert = function() {
var doc = this;
var Class = doc.constructor;
// Find a class on which the behavior had been set.
var behaviorData = Astro.utils.behaviors.findBehavior(
Class,
'timestamp'
);
// Get current date.
var date = new Date();
// If the "hasCreatedField... | events = {};
events.beforeInsert = function() {
// Find a class on which the behavior had been set.
var behaviorData = Astro.utils.behaviors.findBehavior(this.constructor, 'timestamp');
// If the "hasCreatedField" option is set.
if (behaviorData.hasCreatedField) {
// Set value for created field.
this.... |
feat(autocomplete): Allow trieOptions to be passed into autocomplete
- trieOptions to be passed into autocomplete
- add properties of autocomplete to documentation
- update autocomplete syntax
- update event-stream dependency to from and through
[#130668639]
Signed-off-by: Ryan Dy <9eea7ae7eaa2d8efe5cde89ff3ed761900... | const axs = require('../../node_modules/accessibility-developer-tools/dist/js/axs_testing.js');
function failureMessageForAdtResult(result) {
const elements = result.elements.map((element) => element.outerHTML);
return [
result.rule.heading,
...elements
].join('\n ');
}
module.exports = function toPa... | const axs = require('../../node_modules/accessibility-developer-tools/dist/js/axs_testing.js');
function failureMessageForAdtResult(result) {
const elements = result.elements.map((element) => element.outerHTML);
return [
result.rule.heading,
...elements
].join('\n ');
}
module.exports = function toPa... |
Add optional "fail" action handler to Check actions | package com.elmakers.mine.bukkit.action;
import org.bukkit.configuration.ConfigurationSection;
import com.elmakers.mine.bukkit.api.action.ActionHandler;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
publ... | package com.elmakers.mine.bukkit.action;
import com.elmakers.mine.bukkit.api.action.ActionHandler;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
public abstract class CheckAction extends CompoundAction {
protected abstract boolean isAllowed(CastCon... |
Fix space for the tests | module.exports = inject
function inject (bot) {
bot.isAlive = true
bot._client.on('respawn', (packet) => {
bot.isAlive = false
bot.emit('respawn')
})
bot._client.once('update_health', (packet) => {
if (bot.isAlive && packet.health > 0) {
bot.emit('spawn')
}
})
bot._client.on('upd... | module.exports = inject
function inject (bot) {
bot.isAlive = true
bot._client.on('respawn', (packet) => {
bot.isAlive = false
bot.emit('respawn')
})
bot._client.once('update_health', (packet) => {
if(bot.isAlive && packet.health > 0) {
bot.emit('spawn')
}
})
bot._client.on('upda... |
Add test for clock_seq increase if the clock is set backwards | var uuid = require('../uuid'),
assert = require('assert');
function compare(ids) {
console.log(ids);
for (var i = 0; i < ids.length; i++) {
var id = ids[i].split('-');
id = [id[2], id[1], id[0], id[3], id[4]].join('');
ids[i] = id;
}
var sorted = ([].concat(ids)).sort();
assert.equal(sorted.... | var uuid = require('../uuid');
var today = new Date().getTime();
var tenhoursago = new Date(today - 10*3600*1000).getTime();
function compare(ids) {
console.log(ids);
for (var i = 0; i < ids.length; i++) {
var id = ids[i].split('-');
id = [id[2], id[1], id[0], id[3], id[4]].join('');
ids[i] = id;
}
... |
Support Go export on windows. | package targets
import "path"
import "os"
import "os/exec"
import "runtime"
import "errors"
type Go struct {}
func (Go) Compile(mainFile string) error {
compile := exec.Command("go", "build", "-tags", "example", "-o", path.Base(mainFile[:len(mainFile)-2])+".gob")
compile.Stdout = os.Stdout
compile.Stderr = os.S... | package targets
import "path"
import "os"
import "os/exec"
import "runtime"
import "errors"
type Go struct {}
func (Go) Compile(mainFile string) error {
compile := exec.Command("go", "build", "-tags", "example", "-o", path.Base(mainFile[:len(mainFile)-2])+".gob")
compile.Stdout = os.Stdout
compile.Stderr = os.S... |
mattdrayer/WL-525: Handle for missing product attribute | import hashlib
from django.conf import settings
from django.core.cache import cache
from edx_rest_api_client.client import EdxRestApiClient
from ecommerce.core.url_utils import get_lms_url
def mode_for_seat(product):
"""
Returns the enrollment mode (aka course mode) for the specified product.
If the spe... | import hashlib
from django.conf import settings
from django.core.cache import cache
from edx_rest_api_client.client import EdxRestApiClient
from ecommerce.core.url_utils import get_lms_url
def mode_for_seat(product):
"""
Returns the enrollment mode (aka course mode) for the specified product.
If the spe... |
Fix E_NOTICE caused by unset styles | <?php
abstract class SVGNode {
protected $parent;
protected $styles;
public function __construct() {
$this->styles = array();
}
public function getStyle($name) {
return isset($this->styles[$name]) ? $this->styles[$name] : null;
}
public function setStyle($name, $va... | <?php
abstract class SVGNode {
protected $parent;
protected $styles;
public function __construct() {
$this->styles = array();
}
public function getStyle($name) {
return $this->styles[$name];
}
public function setStyle($name, $value) {
$this->styles[$name] =... |
Use prefix parameter to set prefixPath | const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
module.exports.onCreateWebpackConfig = ({ actions, stage, getConfig }, { logo, icons = {}, title, background }) => {
if (stage === 'develop-html' || stage === 'build-html') {
actions.setWebpackConfig({
plugins: [
new FaviconsWebpackP... | const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
module.exports.onCreateWebpackConfig = ({ actions, stage, getConfig }, { logo, icons = {}, title, background }) => {
if (stage === 'develop-html' || stage === 'build-html') {
actions.setWebpackConfig({
plugins: [
new FaviconsWebpackP... |
Initialize empty tiles array for Meld object | # -*- coding: utf-8 -*-
from mahjong.tile import TilesConverter
class Meld(object):
CHI = 'chi'
PON = 'pon'
KAN = 'kan'
CHANKAN = 'chankan'
NUKI = 'nuki'
who = None
tiles = None
type = None
from_who = None
called_tile = None
# we need it to distinguish opened and closed ka... | # -*- coding: utf-8 -*-
from mahjong.tile import TilesConverter
class Meld(object):
CHI = 'chi'
PON = 'pon'
KAN = 'kan'
CHANKAN = 'chankan'
NUKI = 'nuki'
who = None
tiles = None
type = None
from_who = None
called_tile = None
# we need it to distinguish opened and closed ka... |
Remove test of deprecated method | from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher... | from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_start_cypher():
jim = User2(email='jim@test.com').save()
email = jim.start_cypher("RETURN a.email")[0][0][0]
assert email == 'jim@test.com'
def test_cypher():
jim... |
Change TSpec focus script to use windowing (now that it is supported).
git-svn-id: a38512e6531051f4ba6aaa1c8358347ddeca2e1b@117751 b00c9580-4927-0410-8824-811d448ea4c7 | """Take a series of exposures at different focus positions to estimate best focus.
History:
2008-03-25 ROwen First version
2008-04-03 ROwen Changed doWindow to True because the TripleSpec slitviewer can now window
"""
import TUI.Base.BaseFocusScript
# make script reload also reload BaseFocusScript
reload(TUI.Bas... | """Take a series of exposures at different focus positions to estimate best focus.
"""
import TUI.Base.BaseFocusScript
# make script reload also reload BaseFocusScript
reload(TUI.Base.BaseFocusScript)
SlitviewerFocusScript = TUI.Base.BaseFocusScript.SlitviewerFocusScript
Debug = False # run in debug-only mode (which d... |
Print messagen if there is no matched test | package h2spec
import (
"fmt"
"time"
"github.com/summerwind/h2spec/config"
"github.com/summerwind/h2spec/http2"
"github.com/summerwind/h2spec/log"
"github.com/summerwind/h2spec/reporter"
"github.com/summerwind/h2spec/spec"
)
func Run(c *config.Config) error {
total := 0
failed := false
specs := []*spec.Te... | package h2spec
import (
"fmt"
"time"
"github.com/summerwind/h2spec/config"
"github.com/summerwind/h2spec/http2"
"github.com/summerwind/h2spec/log"
"github.com/summerwind/h2spec/reporter"
"github.com/summerwind/h2spec/spec"
)
func Run(c *config.Config) error {
failed := false
specs := []*spec.TestGroup{
h... |
Refactor to use method references | package helloworld;
import static org.requirementsascode.UseCaseModelBuilder.newBuilder;
import org.requirementsascode.UseCaseModel;
import org.requirementsascode.UseCaseModelBuilder;
import org.requirementsascode.UseCaseModelRunner;
public class HelloWorld03_EnterNameExample extends AbstractHelloWorldExample{
pr... | package helloworld;
import static org.requirementsascode.UseCaseModelBuilder.newBuilder;
import java.util.function.Consumer;
import org.requirementsascode.UseCaseModel;
import org.requirementsascode.UseCaseModelBuilder;
import org.requirementsascode.UseCaseModelRunner;
public class HelloWorld03_EnterNameExample ext... |
Fix a bug in alembic downgrading script | """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirn... | """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirn... |
Change the ordering of celery global options | import sys
from celery.__main__ import main as celerymain
from sea import create_app
from sea.cli import jobm
def celery(argv, app):
if argv[0] == "inspect":
from sea.contrib.extensions.celery import empty_celeryapp
empty_celeryapp.load_config(app)
sys.argv = (
["celery"]
... | import sys
from celery.__main__ import main as celerymain
from sea import create_app
from sea.cli import jobm
def celery(argv, app):
if argv[0] == "inspect":
from sea.contrib.extensions.celery import empty_celeryapp
empty_celeryapp.load_config(app)
sys.argv = (
["celery"] + a... |
Add test admin to retrieve a user detail | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST ... | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoint """
... |
Add sleep calls for AWS loops | import boto3
import time
def await_volume(client, volumeId, waitingState, finishedState):
while True:
volumes = client.describe_volumes(VolumeIds=[volumeId])
state = volumes['Volumes'][0]['State']
if state != waitingState:
break
time.sleep(1)
if state != finishedSta... | import boto3
def await_volume(client, volumeId, waitingState, finishedState):
while True:
volumes = client.describe_volumes(VolumeIds=[volumeId])
state = volumes['Volumes'][0]['State']
if state != waitingState:
break
if state != finishedState:
print 'Unexpected volu... |
[hints] Check url safety before redirecting. Safety first! | from zenaida.contrib.hints.models import Dismissed
from zenaida.contrib.hints.forms import DismissHintForm
from django.core.exceptions import SuspiciousOperation
from django.http import (HttpResponse, HttpResponseNotAllowed,
HttpResponseBadRequest, HttpResponseRedirect)
from django.utils.http i... | from zenaida.contrib.hints.models import Dismissed
from zenaida.contrib.hints.forms import DismissHintForm
from django.http import (HttpResponse, HttpResponseNotAllowed,
HttpResponseBadRequest, HttpResponseRedirect)
def dismiss(request):
if not request.POST:
return HttpResponseNotA... |
Use central definition of property. | package org.eobjects.build;
import java.io.File;
import java.util.Map;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Parameter;
public abstract class AbstractDotnetMojo extends AbstractMojo {
@Parameter(defaultValue = PluginHelper.PROPERTY_BASEDIR, readonly = true)
... | package org.eobjects.build;
import java.io.File;
import java.util.Map;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Parameter;
public abstract class AbstractDotnetMojo extends AbstractMojo {
@Parameter(defaultValue = PluginHelper.PROPERTY_BASEDIR, readonly = true)
... |
Exit fragment-ready event handler when it's from a non-applicable fragment | (function ($) {
var FIELDS = {
'centerpage': 'referenced_cp',
'channel': 'query',
'query': 'raw_query'
};
var show_matching_field = function(container, current_type) {
$(['referenced_cp', 'query', 'raw_query']).each(function(i, field) {
var method = field == FIELDS[current_type] ? 'show' : 'h... | (function ($) {
var FIELDS = {
'centerpage': 'referenced_cp',
'channel': 'query',
'query': 'raw_query'
};
var show_matching_field = function(container, current_type) {
$(['referenced_cp', 'query', 'raw_query']).each(function(i, field) {
var method = field == FIELDS[current_type] ? 'show' : 'h... |
Update PowerShell alias to handle no history
If history is cleared (or the shell is new and there is no history),
invoking thefuck results in an error because the alias attempts to execute
the usage string.
The fix is to check if Get-History returns anything before invoking
thefuck. | from .generic import Generic
class Powershell(Generic):
def app_alias(self, fuck):
return 'function ' + fuck + ' {\n' \
' $history = (Get-History -Count 1).CommandLine;\n' \
' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \
' $fuck = $(thef... | from .generic import Generic
class Powershell(Generic):
def app_alias(self, fuck):
return 'function ' + fuck + ' { \n' \
' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \
' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \
' if ($fuc... |
Add pop method on Stack class | #!/usr/bin/env python
'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''
class Item(object):
def __init__(self, value, next_item=None):
self.value = value
self.... | #!/usr/bin/env python
'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''
class Item(object):
def __init__(self, value, next_item=None):
self.value = value
self.... |
Change extend from Content to Widget as additional level not needed | /* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2010, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*******************************************************... | /* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2010, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*******************************************************... |
Use Livequery on default input action. | $(document).ready(function() {
$('a[rel*=facebox]').facebox();
$('input[type=text][default]').livequery(function(){
$(this).addClass('defaulted');
$(this).attr('value', $(this).attr('default'));
$(this).focus(function(){
if($(this).attr('value') == $(this).attr('default')){
$(th... | $(document).ready(function() {
$('a[rel*=facebox]').facebox();
$('input[type=text][default]').each(function(){
$(this).addClass('defaulted');
$(this).attr('value', $(this).attr('default'));
$(this).focus(function(){
if($(this).attr('value') == $(this).attr('default')){
$(this).r... |
Remove StringIO in favor of BytesIO. | """ Test the virtual IO system. """
from io import BytesIO
import sys
import os
from mock import call
from mock import patch
import pytest
sys.path.append(os.path.join('..', '..', 'snake'))
from snake.vm import System
@pytest.fixture()
def system():
""" Fixture to load a new VM. """
return System()
def te... | """ Test the virtual IO system. """
from StringIO import StringIO
import sys
import os
from mock import call
from mock import patch
import pytest
sys.path.append(os.path.join('..', '..', 'snake'))
from snake.vm import System
@pytest.fixture()
def system():
""" Fixture to load a new VM. """
return System()
... |
Add callbacks to the unimplemented functions | /*
* Copyright (c) 2012, Joyent, Inc. All rights reserved.
*
* A brief overview of this source file: what is its purpose.
*/
module.exports = {
add: add,
modify: modify,
del: del
};
function add(replicator, entry, callback) {
var log = replicator.log;
var ufds = replicator.localUfds;
// TODO: targetdn ne... | /*
* Copyright (c) 2012, Joyent, Inc. All rights reserved.
*
* A brief overview of this source file: what is its purpose.
*/
module.exports = {
add: add,
modify: modify,
del: del
};
function add(replicator, entry, callback) {
var log = replicator.log;
var ufds = replicator.localUfds;
// TODO: targetdn ne... |
Add CDN origin domain to allowed hosts. | import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
... | import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
... |
Change return value of getResults | define(["underscore", "jquery"], function(_, $) {
return function (averageCartype) {
var public = {};
var private = {};
private.createObject = function (averageCartype) {
var queryObject = {
c: [],
sc: null,
p: null,
ecol: []
};
for (var carclass in ave... | define(["underscore", "jquery"], function(_, $) {
return function (averageCartype) {
var public = {};
var private = {};
private.createObject = function (averageCartype) {
var queryObject = {
c: [],
sc: null,
p: null,
ecol: []
};
for (var carclass in ave... |
Change signed in to true (just for testing) | import React from "react";
import {render} from "react-dom";
//import my components
import CalendarContainer from "../containers/CalendarContainer";
import SourceViewButton from "../components/SourceViewButton";
import SignIn from "../components/SignIn";
export function renderComponents(){
var signedIn = true;
... | import React from "react";
import {render} from "react-dom";
//import my components
import CalendarContainer from "../containers/CalendarContainer";
import SourceViewButton from "../components/SourceViewButton";
import SignIn from "../components/SignIn";
export function renderComponents(){
var signedIn = false;
... |
Add fkey constraints at the same time | from sqlalchemy import *
from migrate import *
import annotateit
from annotateit import db
from annotateit.model import Consumer, User
meta = MetaData()
consumer = Table('consumer', meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('key', String),
Column('secret', String),
Column(... | from __future__ import print_function
from getpass import getpass
import readline
import sys
from sqlalchemy import *
from migrate import *
from migrate.changeset.constraint import ForeignKeyConstraint
import annotateit
from annotateit import db
from annotateit.model import Consumer, User
meta = MetaData()
consumer... |
Remove unnecessary call for modules | <?php
namespace Amazon\Pay\Test\Mftf\Helper;
use Magento\FunctionalTestingFramework\Helper\Helper;
class WaitForPopup extends Helper {
public function waitForPopup() {
/** @var \Magento\FunctionalTestingFramework\Module\MagentoWebDriver $webDriver */
$webDriver = $this->getModule('\Magento\Funct... | <?php
namespace Amazon\Pay\Test\Mftf\Helper;
use Magento\FunctionalTestingFramework\Helper\Helper;
class WaitForPopup extends Helper {
public function waitForPopup() {
/** @var \Magento\FunctionalTestingFramework\Module\MagentoWebDriver $webDriver */
$webDriver = $this->getModule('\Magento\Funct... |
Fix use of deprecated api | package de.christinecoenen.code.zapp.utils.video;
import android.view.View;
import com.google.android.exoplayer2.Player;
import java.lang.ref.WeakReference;
/**
* Allows the screen to turn off as soon as video playback finishes
* or pauses.
*/
class ScreenDimmingVideoEventListener implements Player.EventListener... | package de.christinecoenen.code.zapp.utils.video;
import android.view.View;
import com.google.android.exoplayer2.Player;
import java.lang.ref.WeakReference;
/**
* Allows the screen to turn off as soon as video playback finishes
* or pauses.
*/
class ScreenDimmingVideoEventListener implements Player.EventListener... |
Update missed file to UTF-8 encoding. | package com.emilsjolander.components.StickyListHeaders;
import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
/**
*
* @author Emil Sj�lander
*
*
Copyright 2012 Emil Sj�lander
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in... | package com.emilsjolander.components.StickyListHeaders;
import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
/**
*
* @author Emil Sjlander
*
*
Copyright 2012 Emil Sjlander
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except i... |
Refactor IconView to simplify placeholder behaviour | var $ = require('jquery');
var CoreView = require('backbone/core-view');
var iconTemplates = {};
var importAllIconTemplates = function () {
var templates = require.context('./templates', false, /\.tpl$/);
templates.keys().forEach(function (template) {
iconTemplates[template] = templates(template);
});
};
i... | var $ = require('jquery');
var CoreView = require('backbone/core-view');
var iconTemplates = {};
var importAllIconTemplates = function () {
var templates = require.context('./templates', false, /\.tpl$/);
templates.keys().forEach(function (template) {
iconTemplates[template] = templates(template);
});
};
i... |
Define the default policy file
This change ensures that the default policy file for Manila API access
is defined by default, so that operators can deploy their own policy
more easily.
Change-Id: Ie890766ea2a274791393304cdfe532e024171195 | # Copyright 2016 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | # Copyright 2016 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
Update sass block to use new API | /**
* SASS webpack block.
*
* @see https://github.com/jtangelder/sass-loader
*/
module.exports = sass
/**
* @param {object} [options] See https://github.com/sass/node-sass#options
* @param {string[]} [options.includePaths]
* @param {bool} [options.indentedSyntax]
* @param {string} [op... | /**
* SASS webpack block.
*
* @see https://github.com/jtangelder/sass-loader
*/
module.exports = sass
/**
* @param {object} [options] See https://github.com/sass/node-sass#options
* @param {string[]} [options.includePaths]
* @param {bool} [options.indentedSyntax]
* @param {string} [op... |
Use identity instead of global id. | /**
* DashboardController
*
* @description :: Server-side logic for managing Dashboards
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (req, res) {
if(!req.user.hasPermission('system.dashboard.view')) {
res.forbidden(req.__('Error.Auth... | /**
* DashboardController
*
* @description :: Server-side logic for managing Dashboards
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (req, res) {
if(!req.user.hasPermission('system.dashboard.view')) {
res.forbidden(req.__('Error.Auth... |
Replace all '.' by '\.' in the names | function subscribe(link) {
$.ajax(link, {
success: function(json, stat, xhr) {
var name, sel;
name = json.repo.name;
name = name.replace(/\./g, '\\.');
sel = $("#"+json.github_username+'-'+name);
sel.toggleClass('btn-success');
sel.togg... | function subscribe(link) {
$.ajax(link, {
success: function(json, stat, xhr) {
var name, sel;
name = json.repo.name;
name = name.replace('.', '\\.');
sel = $("#"+json.github_username+'-'+name);
sel.toggleClass('btn-success');
sel.toggle... |
Sort package list in required installs | #!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
__version__ = "0.13.0"
setup(
name='pyramid_zipkin',
version=__version__,
provides=["pyramid_zipkin"],
author='Yelp, Inc.',
author_email='opensource+pyramid-zipkin@yelp.com',
license='C... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
__version__ = "0.13.0"
setup(
name='pyramid_zipkin',
version=__version__,
provides=["pyramid_zipkin"],
author='Yelp, Inc.',
author_email='opensource+pyramid-zipkin@yelp.com',
license='C... |
Add examples/* to linted files. | /*jslint node: true */
"use strict";
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
laxcomma: true
, strict: true
, globals: { 'require': fa... | /*jslint node: true */
"use strict";
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
laxcomma: true
, strict: true
, globals: { 'require': fa... |
FIX query class for Member MDL | <?php
namespace frontend\modules\bbii\models\_query;
use yii\db\ActiveQuery;
/**
* Created to replace Yii1's scope concept. Yii2 uses query classes
*
* @since 0.0.5
*/
class BbiiMemberQuery extends ActiveQuery
{
public function find()
{
return $this;
}
public function findAll()
{
return $this;
}
... | <?php
namespace frontend\modules\bbii\models\_query;
use yii\db\ActiveQuery;
/**
* Created to replace Yii1's scope concept. Yii2 uses query classes
*
* @since 0.0.5
*/
class BbiiMemberQuery extends ActiveQuery
{
public function find()
{
return $this;
}
public function findAll()
{
return $this;
}
... |
Add url assignment to each crawled dataset item | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from dataset import DatasetItem
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.... | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from dataset import DatasetItem
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.... |
Add a convex hull operation to really close this up. | import scipy.ndimage as ndim
from skimage.filters import gaussian
from skimage.morphology import convex_hull_image
def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
... | import scipy.ndimage as ndim
from skimage.filters import gaussian
def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
fix that up.
Parameters
----------
... |
Use brighter colors in contextual Graphite graphs | // TODO: This is not a real model or controller
App.Graphs = Ember.Controller.extend({
graph: function(emberId, entityName, entityType, numSeries) {
entityName = entityName.replace(/\./g, '-');
var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityTy... | // TODO: This is not a real model or controller
App.Graphs = Ember.Controller.extend({
graph: function(emberId, entityName, entityType, numSeries) {
entityName = entityName.replace(/\./g, '-');
var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityTy... |
Add safer function call for CLI | #!/usr/bin/env node
import yargs from 'yargs';
import path from 'path';
import fs from 'fs';
import * as pose from '.';
const opts = yargs
.usage('$ pose <action> [options]')
.help('help')
.options({
name: {
alias: ['n'],
default: path.basename(process.cwd()),
desc: 'Name of template',
},
entry: {
... | #!/usr/bin/env node
import yargs from 'yargs';
import path from 'path';
import fs from 'fs';
import * as pose from '.';
const opts = yargs
.usage('$ pose <action> [options]')
.help('help')
.options({
name: {
alias: ['n'],
default: path.basename(process.cwd()),
desc: 'Name of template',
},
entry: {
... |
Resolve a couple of compiler warnings that crept into the code. | // Copyright (C) 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | // Copyright (C) 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... |
Fix pre-commit issues in the cli_parse tests. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for the 'parse' CLI command."""
import tempfile
import pytest
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.ma... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('pos_kind', ['wannier', 'ne... |
Mark as commented explicitly all encrypted types by default | <?php
/**
* LICENSE: This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
*
* @copyright 2016 Copyright(c) - All rights reserved.
*/
namespace Rafrsr\DoctrineExtraBundle\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Encrypte... | <?php
/**
* LICENSE: This file is subject to the terms and conditions defined in
* file 'LICENSE', which is part of this source code package.
*
* @copyright 2016 Copyright(c) - All rights reserved.
*/
namespace Rafrsr\DoctrineExtraBundle\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Encrypte... |
Send messages more than once | if (process.argv.length < 7) {
throw new Error("Need at least 7 command line arguments. In order, must be:\n" +
"consumer_key\n" +
"consumer_secret\n" +
"access_token\n" +
"access_token_secret\n" +
"target_screen... | if (process.argv.length < 7) {
throw new Error("Need at least 5 command line arguments. In order, must be:\n" +
"consumer_key\n" +
"consumer_secret\n" +
"access_token\n" +
"access_token_secret\n" +
"target_screen... |
Replace moment with luxon in test | import { module, test } from 'qunit';
import { setupRenderingTest } from 'dummy/tests/helpers';
import { setupIntl } from 'ember-intl/test-support';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { DateTime } fr... | import { module, test } from 'qunit';
import { setupRenderingTest } from 'dummy/tests/helpers';
import { setupIntl } from 'ember-intl/test-support';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { setupMirage } from 'ember-cli-mirage/test-support';
import moment from 'mo... |
Revert "Revert "set opennms home for JMXDataCollectionConfigFactory""
This reverts commit c460f2203e5b22a0786c473072e4b59073bca8b9. | package org.opennms.netmgt.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/*
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/emptyContext.xml"
})... | package org.opennms.netmgt.config;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class JMXDataCollectionConfigFactoryTest {
@Test
// Tests that the JmxDataCollectionConfigFactory also supports/implements the ... |
Use the new safeRunForDist method | package info.u_team.u_team_core;
import org.apache.logging.log4j.*;
import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor... | package info.u_team.u_team_core;
import org.apache.logging.log4j.*;
import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor... |
Fix re-evaluation loop with assignment expression | package com.madisp.bad.expr;
import com.madisp.bad.eval.BadConverter;
import com.madisp.bad.eval.Scope;
import com.madisp.bad.eval.Watcher;
/**
* Created with IntelliJ IDEA.
* User: madis
* Date: 3/27/13
* Time: 7:02 PM
*/
public class AssignExpression implements Expression {
private final Expression expr;
pri... | package com.madisp.bad.expr;
import com.madisp.bad.eval.BadConverter;
import com.madisp.bad.eval.Scope;
import com.madisp.bad.eval.Watcher;
/**
* Created with IntelliJ IDEA.
* User: madis
* Date: 3/27/13
* Time: 7:02 PM
*/
public class AssignExpression implements Expression {
private final Expression expr;
pri... |
Remove global var to seek if outputs works | package fnlog_test
import (
"github.com/northbright/fnlog"
"log"
)
/*var (
noTagLog *log.Logger
)
*/
func Example() {
iLog := fnlog.New("i")
wLog := fnlog.New("w")
eLog := fnlog.New("e")
iLog.Printf("print infos")
wLog.Printf("print warnnings")
eLog.Printf("print errors")
//noTagLog.Printf("print messages ... | package fnlog_test
import (
"github.com/northbright/fnlog"
"log"
)
var (
noTagLog *log.Logger
)
func Example() {
iLog := fnlog.New("i")
wLog := fnlog.New("w")
eLog := fnlog.New("e")
iLog.Printf("print infos")
wLog.Printf("print warnnings")
eLog.Printf("print errors")
noTagLog.Printf("print messages withou... |
Remove unnecessary string constants from service | package com.ibm.mil.smartringer;
import android.app.IntentService;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
public class RingerAdjusterService extends IntentService {
private static final String TAG = RingerAdjusterService.class.getName();
public RingerAdjust... | package com.ibm.mil.smartringer;
import android.app.IntentService;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
public class RingerAdjusterService extends IntentService {
private static final String TAG = RingerAdjusterService.class.getName();
private static final... |
Add six to the explicit dependencies | from setuptools import find_packages, setup
setup(
name='jupyter-notebook-gist',
version='0.4.0',
description='Create a gist from the Jupyter Notebook UI',
author='Mozilla Firefox Data Platform',
author_email='fx-data-platform@mozilla.com',
packages=find_packages(where='src'),
package_dir={... | from setuptools import find_packages, setup
setup(
name='jupyter-notebook-gist',
version='0.4.0',
description='Create a gist from the Jupyter Notebook UI',
author='Mozilla Firefox Data Platform',
author_email='fx-data-platform@mozilla.com',
packages=find_packages(where='src'),
package_dir={... |
Add the headers to the response
https://developer.forecast.io/docs/v2#response-headers | <?php
namespace Forecast;
class Forecast
{
const API_ENDPOINT = 'https://api.forecast.io/forecast/';
private $api_key;
public function __construct($api_key)
{
$this->api_key = $api_key;
}
private function request($latitude, $longitude, $time = null, $options = array())
{
... | <?php
namespace Forecast;
class Forecast
{
const API_ENDPOINT = 'https://api.forecast.io/forecast/';
private $api_key;
public function __construct($api_key)
{
$this->api_key = $api_key;
}
private function request($latitude, $longitude, $time = null, $options = array())
{
... |
Update os_version to High Sierra | module.exports = {
browsers: {
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'High Sierra'
},
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'High Sierra'
},
bs_firefox_win: {
... | module.exports = {
browsers: {
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Mountain Lion'
},
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Mountain Lion'
},
bs_firefox_win: {... |
Allow sending kwars to mesh shader | from pyrr import Matrix33
class MeshShader:
def __init__(self, shader, **kwargs):
self.shader = shader
def draw(self, mesh, proj_mat, view_mat):
"""Minimal draw function. Should be overridden"""
mesh.vao.bind(self.shader)
self.shader.uniform_mat4("m_proj", proj_mat)
s... | from pyrr import Matrix33
class MeshShader:
def __init__(self, shader):
self.shader = shader
def draw(self, mesh, proj_mat, view_mat):
"""Minimal draw function. Should be overridden"""
mesh.vao.bind(self.shader)
self.shader.uniform_mat4("m_proj", proj_mat)
self.shader... |
Fix - needed to provide create_task a function, not a class | # -*- coding: utf-8 -*-
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=N... | # -*- coding: utf-8 -*-
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=N... |
Send notification to the correct address | import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
def main(address_pattern=None):
my_name = input("Name: ")
my_address = nw0.a... | import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
def main(address_pattern=None):
my_name = input("Name: ")
my_address = nw0.a... |
Use BaseDbObjectTestCase in AddressScope UT
AddressScopeDbObjectTestCase class is using _BaseObjectTestCase class
which doesn't contain all the unit test cases for Oslo-Versioned
classes. This patch replace that class.
Partially-Implements: blueprint adopt-oslo-versioned-objects-for-db
Change-Id: I180046743471487a9f... | # Copyright (c) 2016 Intel Corporation.
#
# 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 la... | # Copyright (c) 2016 Intel Corporation.
#
# 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 la... |
Enable service compositions command to instantiate the linked ontology | package eu.scasefp7.eclipse.core.handlers;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
/**
* A command handler for exporting all service compositions to the linked ontology.
*
* @author themis
*/
public class CompileServiceCompositionsHandler ex... | package eu.scasefp7.eclipse.core.handlers;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
/**
* A command handler for exporting all service compositions to the linked ontology.
*
* @author themis
*/
public class CompileServiceCompositionsHandler ex... |
Set default mustValidateSecret to true | <?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Repositories;
use League\OAuth2\Server\Entities\ClientEntityInterface;
/**... | <?php
/**
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Repositories;
use League\OAuth2\Server\Entities\ClientEntityInterface;
/**... |
Fix crash in 1.6 at Accessibility settings intent.
Check SDK version & launch intent differently for 1.6.
Instead of OnPreferenceClickListener, use .setIntent on preference. | package com.pilot51.voicenotify;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
public class MainActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedIn... | package com.pilot51.voicenotify;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
public class MainActivity extends PreferenceActivity {
@Override
protected voi... |
FIX AL CAMPO DEL REPORTE DE PROVEEDOR - AHORA ES TIPO HIDDEN | <div class="container">
<input type="hidden" id="tipo_reporte" value="por_proveedor">
<div class="row">
<div class="col-sm-8 col-md-8 col-lg-8">
<label for="">Seleccione proveedor</label>
<select name="proveedor_id" id="proveedor_id" class="form-control">
@foreach(App\Models\compras\Proveedor::get() as $p... | <div class="container">
<input type="text" id="tipo_reporte" value="por_proveedor">
<div class="row">
<div class="col-sm-8 col-md-8 col-lg-8">
<label for="">Seleccione proveedor</label>
<select name="proveedor_id" id="proveedor_id" class="form-control">
@foreach(App\Models\compras\Proveedor::get() as $pro... |
Change registration email sender to Phuxivator | from django.core.mail import send_mail
# TODO: check whether this should be sent from Phuxivator
def mailApplicantSubmission(context, sender='phuxivator@tf.fi'):
name = context['name']
receiver = context['email']
subject = 'Tack för din medlemsansökan till Teknologföreningen!'
message = '''Hej {name}... | from django.core.mail import send_mail
# TODO: check whether this should be sent from Phuxivator
def mailApplicantSubmission(context, sender='infochef@tf.fi'):
name = context['name']
receiver = context['email']
subject = 'Tack för din medlemsansökan till Teknologföreningen!'
message = '''Hej {name},
... |
Clean up the clean up
Typo :( | (function () {
CKEDITOR.plugins.add('structuredheadings', {
icons: 'structuredheadings',
init: (editor) => {
// The command to add an autonumbering class
editor.addCommand('autoNumberHeading', {
exec: (editor) => {
/* Get all header elements and assign classes
* only if needed
*/
as... | (function () {
CKEDITOR.plugins.add('structuredheadings', {
icons: 'structuredheadings',
init: (editor) => {
// The command to add an autonumbering class
editor.addCommand('autoNumberHeading', {
exec: (editor) => {
/* Get all header elements and assign classes
* only if needed
*/
as... |
Add --strict flag to raise exception on undefined variables | import sys
import argparse
import yaml
import jinja2
def render(template_string, context_dict, strict=False):
template = jinja2.Template(template_string)
if strict:
template.environment.undefined = jinja2.StrictUndefined
return template.render(**context_dict)
def main():
parser = argparse.A... | import sys
import argparse
import yaml
from jinja2 import Template
def render(template_string, context_dict):
template = Template(template_string)
return template.render(**context_dict)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('template', nargs='?', type=argparse.FileType(... |
Enable the additional validation methods. | define([
'require',
'../../lib/jquery.validate',
'../../lib/jquery-validation-1.9.0/additional-methods.min',
'../logging'
], function(require) {
var log = require('../logging').getLogger('validate');
var init = function($el, opts) {
var rules = $el.find('[data-required-if]').toArray().r... | define([
'require',
'../../lib/jquery.validate',
'../logging'
], function(require) {
var log = require('../logging').getLogger('validate');
var init = function($el, opts) {
var rules = $el.find('[data-required-if]').toArray().reduce(function(acc, el) {
var $el = $(el),
... |
Remove use of depracated share method in Laravel 5 service provider | <?php namespace ZackKitzmiller\Laravel5;
use ZackKitzmiller\Tiny;
use Illuminate\Support\ServiceProvider;
class TinyServiceProvider extends ServiceProvider
{
public function boot()
{
$this->app->singleton('tiny.generate', function () {
return new TinyGenerateCommand();
});
... | <?php namespace ZackKitzmiller\Laravel5;
use ZackKitzmiller\Tiny;
use Illuminate\Support\ServiceProvider;
class TinyServiceProvider extends ServiceProvider
{
public function boot()
{
$this->app['tiny.generate'] = $this->app->share(function ($app) {
return new TinyGenerateCommand();
... |
Fix wrong java tmp dir sys property
git-svn-id: 2433085265c0232ec46d186f8a8240da49417e22@32162 2c54a935-e501-0410-bc05-97a93f6bca70 | package com.atlassian.sal.refimpl;
import com.atlassian.sal.api.ApplicationProperties;
import java.util.Date;
import java.io.File;
/**
* Implementation of ApplicationProperties for http://localhost
*/
public class RefimplApplicationProperties implements ApplicationProperties
{
private static final Date THEN = ... | package com.atlassian.sal.refimpl;
import com.atlassian.sal.api.ApplicationProperties;
import java.util.Date;
import java.io.File;
/**
* Implementation of ApplicationProperties for http://localhost
*/
public class RefimplApplicationProperties implements ApplicationProperties
{
private static final Date THEN = ... |
Fix numero secu input value | 'use strict';
angular.module('impactApp').directive('numeroSecu', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
const isValid = (value) => {
if (!value) {
return true;
}
const valueKey = value.slice(-2);
const valueRest... | 'use strict';
angular.module('impactApp').directive('numeroSecu', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
const isValid = (value) => {
if (!value) {
return true;
}
const valueKey = value.slice(-2);
const valueRest... |
[form-builder] Make latlon example use PatchEvent | import React, {PropTypes} from 'react'
import PatchEvent, {set} from '../../../../src/PatchEvent'
export default class MyCustomLatLonInput extends React.Component {
static propTypes = {
value: PropTypes.object,
onChange: PropTypes.func
};
static defaultProps = {
onChange() {},
value: {}
};
... | import React, {PropTypes} from 'react'
export default class MyCustomLatLonInput extends React.Component {
static propTypes = {
value: PropTypes.object,
onChange: PropTypes.func
};
static defaultProps = {
onChange() {},
value: {}
};
static contextTypes = {
resolveInputComponent: PropTyp... |
Allow users to run Step Stool as either `step-stool` or `stepstool`. | from setuptools import setup
requires = ['Markdown', 'PyRSS2Gen', 'Pygments', 'PyYAML >= 3.10', 'typogrify']
packages = ['step_stool']
entry_points = {
'console_scripts': [
'stepstool = step_stool:main',
'step-stool = step_stool:main'
]
}
classifiers = [
'Environment :: Console',
'Deve... | from setuptools import setup
requires = ['Markdown', 'PyRSS2Gen', 'Pygments', 'PyYAML >= 3.10', 'typogrify']
packages = ['step_stool']
entry_points = {
'console_scripts': [
'step-stool = step_stool:main'
]
}
classifiers = [
'Environment :: Console',
'Development Status :: 1 - Planning',
'I... |
Move some fixtures into better places
Move datadir into the sipsecmon plugin and testname into
lab.runnerctl. | """
pytest runner control plugin
"""
import pytest
import string
def pytest_runtest_makereport(item, call):
if 'setup_test' in item.keywords and call.excinfo:
if not call.excinfo.errisinstance(pytest.skip.Exception):
pytest.halt('A setup test has failed, aborting...')
class Halt(object):
... | """
pytest runner control plugin
"""
import pytest
def pytest_runtest_makereport(item, call):
if 'setup_test' in item.keywords and call.excinfo:
if not call.excinfo.errisinstance(pytest.skip.Exception):
pytest.halt('A setup test has failed, aborting...')
class Halt(object):
def __init__(... |
Add logo and fix styling | import React from 'react'
import { Link } from 'react-router-dom'
import injectSheet from 'react-jss'
import Spacer from '../../components/spacer'
import LogoBetaWhite from '../../components/icons/icon-components/logo-beta-white'
const MiniAppFooter = ({ classes }) => {
return (
<div>
<Spacer height="100px" />
... | import React from 'react'
import { Link } from 'react-router-dom'
import injectSheet from 'react-jss'
import Spacer from '../../components/spacer'
const MiniAppFooter = ({ classes }) => {
return (
<div>
<Spacer height="100px" />
<div className={classes.footerRoot}>
<Link to="/about" className={classes.na... |
Fix ItemEditController observer accessing model when model was destroyed | var ItemEditController = Em.ObjectController.extend({
setComplete: function () {
var model = this.get('model'),
complete;
// this observer fires even when this controller is not part of the active route.
// this is because route controllers are singletons and persist.
// since changing routes... | var ItemEditController = Em.ObjectController.extend({
setComplete: function () {
var complete = this.get('canonicalModel.complete');
this.set('model.complete', complete);
}.observes('canonicalModel.complete'),
actions: {
cancel: function () {
this.get('model').destroy();
this.transitionTo... |
Fix a bug where Assertion's stack is always true even when set to false | /**
* External dependencies.
*/
var chai = global.chai || require('chai');
/**
* Chai.js plugin.
*
* Options:
*
* - styles: array/string should, expect, assert
* - stack: boolean include stack
* - diff: boolean show diff
*
* @param {Object} hydro
* @api public
*/
module.exports ... | /**
* External dependencies.
*/
var chai = global.chai || require('chai');
/**
* Chai.js plugin.
*
* Options:
*
* - styles: array/string should, expect, assert
* - stack: boolean include stack
* - diff: boolean show diff
*
* @param {Object} hydro
* @api public
*/
module.exports ... |
Change to look more like a "plugin js" | var Shortcut = function() {};
Shortcut.prototype.CreateShortcut: = function (shortcut_text, successCallback, errorCallback) {
cordova.exec(
successCallback,
errorCallback,
'ShortcutPlugin',
'addShortcut',
[{
"shortcuttext": shortcut_... | var ShortcutPlugin = {
CreateShortcut: function(shortcut_text, successCallback, errorCallback) {
cordova.exec(
successCallback,
errorCallback,
'ShortcutPlugin',
'addShortcut',
[{
"shortcuttext": shortcut_text
}]
... |
Fix wrong block entity type | package info.u_team.u_team_test.block;
import info.u_team.u_team_core.block.UEntityBlock;
import info.u_team.u_team_test.init.TestBlockEntityTypes;
import info.u_team.u_team_test.init.TestCreativeTabs;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.Interactio... | package info.u_team.u_team_test.block;
import info.u_team.u_team_core.block.UEntityBlock;
import info.u_team.u_team_test.init.TestBlockEntityTypes;
import info.u_team.u_team_test.init.TestCreativeTabs;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.Interactio... |
Fix - ribbon doesn't open contact form | var codebrag = codebrag || {};
/**
* Module for adding scripts not related with app features and Angular
*/
codebrag.addons = {};
codebrag.addons.betaRibbon = (function() {
var ribbon = $('.ribbon');
var infoPopup = $('#early-version-popup');
var popupCloseBtn = infoPopup.find('.close-btn');
var li... | var codebrag = codebrag || {};
/**
* Module for adding scripts not related with app features and Angular
*/
codebrag.addons = {};
codebrag.addons.betaRibbon = (function() {
var ribbon = $('.ribbon');
var infoPopup = $('.popup-page');
var popupCloseBtn = infoPopup.find('.close-btn');
var link = info... |
Revert to simple tokens for front-matter multiplex | import CodeMirror from "codemirror"
import _ from "underscore"
require("codemirror/addon/mode/multiplex")
require("codemirror/addon/edit/trailingspace")
// Load modes
_.each([
"gfm",
"javascript",
"ruby",
"coffeescript",
"css",
"sass",
"stylus",
"yaml"
], mode => require(`codemirror/mode/${mode}/${mod... | import CodeMirror from "codemirror"
import _ from "underscore"
require("codemirror/addon/mode/multiplex")
require("codemirror/addon/edit/trailingspace")
// Load modes
_.each([
"gfm",
"javascript",
"ruby",
"coffeescript",
"css",
"sass",
"stylus",
"yaml"
], mode => require(`codemirror/mode/${mode}/${mod... |
Add resolving for item queries | import Item from "./graphql/types/item"
import Update from "./graphql/types/update"
import { makeExecutableSchema } from "graphql-tools"
const RuneScapeQuery = `
type RuneScapeQuery {
items: [Item]
item(id: Int!): Item
updates: [Update]
}
`
const SchemaDefinition = `
schema {
query: RuneScapeQuery
... | import Item from "./graphql/types/item"
import Update from "./graphql/types/update"
import { makeExecutableSchema } from "graphql-tools"
const RuneScapeQuery = `
type RuneScapeQuery {
items: [Item]
item(id: Int!): Item
updates: [Update]
}
`
const SchemaDefinition = `
schema {
query: RuneScapeQuery
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.