text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Add method to create resource | import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = sub... | import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = sub... |
Add default value to entity in constructor | <?php
namespace HiPay\Wallet\Mirakl\Vendor\Event;
use Symfony\Component\EventDispatcher\Event;
/**
* Class CheckAvailability
* Event object used when the event 'before.availability.check'
* is dispatched from the processor.
*
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
class... | <?php
namespace HiPay\Wallet\Mirakl\Vendor\Event;
use Symfony\Component\EventDispatcher\Event;
/**
* Class CheckAvailability
* Event object used when the event 'before.availability.check'
* is dispatched from the processor.
*
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
class... |
Add function for getting installed plugins | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
import os
class Config:
def __init__(self, prefix='SHELDON_'):
"""
Load config from environment variables.
:param prefix: string, all needed environment va... | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
import os
class Config:
def __init__(self, prefix='SHELDON_'):
"""
Load config from environment variables.
:param prefix: string, all needed environment va... |
Remove use of ipify.org service | module.exports = function geoip (ip) {
return (state, emitter) => {
state.geoip = {
ip: ip,
isLoading: false
}
emitter.on('geoip:fetch', () => {
if (state.geoip.isLoading) return
state.geoip.isLoading = true
window.fetch('https://freegeoip.net/json/').then(body => {
... | module.exports = function geoip (ip) {
return (state, emitter) => {
state.geoip = {
ip: ip,
isLoading: false
}
emitter.on('geoip:fetch', () => {
if (state.geoip.isLoading) return
state.geoip.isLoading = true
window.fetch('//api.ipify.org?format=json')
.then(body => ... |
Stop the repl test on an error, making sure all Pipes are closed |
from tests.util.pipe import Pipe
from threading import Thread
from pycell.repl import repl
from tests.util.system_test import system_test
from tests.util.all_examples import all_sessions
def _validate_line(exp_line, strin, strout):
expprompt = exp_line[:4]
if expprompt in (">>> ", "... "):
prompt =... |
from tests.util.pipe import Pipe
from threading import Thread
from pycell.repl import repl
from tests.util.system_test import system_test
from tests.util.all_examples import all_sessions
def _validate_session(f):
strin = Pipe()
strout = Pipe()
strerr = Pipe()
replthread = Thread(target=repl, args=(s... |
Fix subject getter to support subject alts
git-svn-id: 28fe03dfd74dd77dcc8ecfe99fabcec8eed81bba@3722 8555b757-d854-4b86-925a-82fd84c90ff4 | <div class="box">
<?php
if(!Config::get('lang_selector_enabled')) {
$opts = array();
$code = Lang::getCode();
foreach(Lang::getAvailableLanguages() as $id => $dfn) {
$selected = ($id == $code) ? 'selected="selected"' : '';
$opts[] = '<option value="'.$id.'" '.$selecte... | <div class="box">
<?php
if(!Config::get('lang_selector_enabled')) {
$opts = array();
$code = Lang::getCode();
foreach(Lang::getAvailableLanguages() as $id => $dfn) {
$selected = ($id == $code) ? 'selected="selected"' : '';
$opts[] = '<option value="'.$id.'" '.$selecte... |
Use 50 times the page size for faceting | "use strict";
var search = require('../lib/search');
module.exports = function (input, callback) {
if (typeof input.query.plan !== 'undefined' && typeof input.query.plan.esquery !== 'undefined') {
input.query.plan.esquery.from = input.query.offset || 0;
if (input.query.plan.esonly) {
in... | "use strict";
var search = require('../lib/search');
module.exports = function (input, callback) {
if (typeof input.query.plan !== 'undefined' && typeof input.query.plan.esquery !== 'undefined') {
input.query.plan.esquery.from = input.query.offset || 0;
if (input.query.plan.esonly) {
in... |
Add dynamic database name to getColumns() | <?php
namespace UserControlSkeleton\Models\Database;
use PDO;
use UserControlSkeleton\Interfaces\AdapterInterface;
class MysqlAdapter implements AdapterInterface
{
protected $user;
protected $pass;
protected $host;
protected $port;
protected $name;
protected $driver;
public function... | <?php
namespace UserControlSkeleton\Models\Database;
use PDO;
use UserControlSkeleton\Interfaces\AdapterInterface;
class MysqlAdapter implements AdapterInterface
{
protected $user;
protected $pass;
protected $host;
protected $port;
protected $name;
protected $driver;
public function... |
Handle multiple receiver domain properly | import datetime
import smtpd
from email.parser import Parser
from mailchute import db
from mailchute import settings
from mailchute.model import RawMessage, IncomingEmail
from logbook import Logger
logger = Logger(__name__)
class MessageProcessor(object):
def _should_persist(self, recipient):
recipient_... | import datetime
import smtpd
from email.parser import Parser
from mailchute import db
from mailchute import settings
from mailchute.model import RawMessage, IncomingEmail
from logbook import Logger
logger = Logger(__name__)
class MessageProcessor(object):
def _should_persist(self, recipient):
allowed_re... |
Fix spacing and conditional braces | package seedu.todo.ui;
import seedu.todo.controllers.*;
public class InputHandler {
Controller handlingController = null;
public boolean processInput(String input) {
if (this.handlingController != null) {
handlingController.process(input);
} else {
Controller[] contro... | package seedu.todo.ui;
import seedu.todo.controllers.*;
public class InputHandler {
Controller handlingController = null;
public boolean processInput(String input) {
if (this.handlingController != null) {
handlingController.process(input);
} else {
Controller[... |
Add missing `await` to outer iterator `next` call.
Closes #73. | module.exports = function (paginator, filter) {
const iterator = paginator[Symbol.asyncIterator]()
let done = false
return {
[Symbol.asyncIterator]: function () {
return this
},
next: async function () {
if (done) {
return { done: true }
... | module.exports = function (paginator, filter) {
const iterator = paginator[Symbol.asyncIterator]()
let done = false
return {
[Symbol.asyncIterator]: function () {
return this
},
next: async function () {
if (done) {
return { done: true }
... |
Use initial value from api | import {div, header, footer, button, p, hJSX} from '@cycle/dom'
import isolate from '@cycle/isolate'
import AceEditor from 'cyclejs-ace-editor'
let {Observable} = require('rx')
function intent({DOM, context}) {
const buttonClicks$ = DOM.select('.submit-button').events('click')
const initialCodeValue$ = conte... | import {div, header, footer, button, p, hJSX} from '@cycle/dom'
import isolate from '@cycle/isolate'
import AceEditor from 'cyclejs-ace-editor'
let {Observable} = require('rx')
function intent({DOM}) {
const buttonClicks$ = DOM.select('.submit-button').events('click')
return {
buttonClicks$
}
}
... |
Tweak old integration test docstring | from spec import skip, Spec, ok_
from fabric.connection import Connection
class Main(Spec):
def connection_open_generates_real_connection(self):
c = Connection('localhost')
c.open()
ok_(c.client.get_transport().active)
def simple_command_on_host(self):
"""
Run command... | from spec import skip, Spec, ok_
from fabric.connection import Connection
class Main(Spec):
def connection_open_generates_real_connection(self):
c = Connection('localhost')
c.open()
ok_(c.client.get_transport().active)
def simple_command_on_host(self):
"""
Run command... |
Update product relative link to link to the correct parent page | <?php
class CataloguePageProductExtension extends DataExtension
{
public function updateRelativeLink($base, $action)
{
$page = null;
// Try to find the current product's page
if ($this->owner->CataloguePages()->exists()) {
$page = $this->owner->CataloguePages()->first(... | <?php
class CataloguePageProductExtension extends DataExtension
{
public function updateRelativeLink($base, $action)
{
$page = CataloguePage::get()->first();
$link = Controller::join_links(
$page->RelativeLink("product"),
$this->owner->URLSegment,
... |
ENH: Update tools script for file renaming | #! /usr/bin/env python
"""
Run this script to convert dataset documentation to ReST files. Relies
on the meta-information from the datasets of the currently installed version.
Ie., it imports the datasets package to scrape the meta-information.
"""
import statsmodels.api as sm
import os
from os.path import join
import... | #! /usr/bin/env python
"""
Run this script to convert dataset documentation to ReST files. Relies
on the meta-information from the datasets of the currently installed version.
Ie., it imports the datasets package to scrape the meta-information.
"""
import statsmodels.api as sm
import os
from os.path import join
import... |
Prepend the base URL to all endpoints | package co.phoenixlab.discord.api;
/**
* Contains various useful API URLs and paths
*/
public class ApiConst {
/**
* Utility class
*/
private ApiConst() {
}
/**
* The base URL from which Discord runs
*/
public static final String BASE_URL = "https://discordapp.com/";
/**... | package co.phoenixlab.discord.api;
/**
* Contains various useful API URLs and paths
*/
public class ApiConst {
/**
* Utility class
*/
private ApiConst() {
}
/**
* The base URL from which Discord runs
*/
public static final String BASE_URL = "https://discordapp.com/";
/**... |
Update sample of google chrome developer tools | console.warn('devtools.js');
chrome.devtools.panels.create(
'sample',
'',
'./panel.html',
(panel) => {
let _panelWindow;
// a-0. connect to background
const backgroundPageConnection = chrome.runtime.connect({
name: 'devtools-page'
});
// a-4. pass t... | console.warn('devtools.js');
chrome.devtools.panels.create(
'sample',
'',
'./panel.html',
(panel) => {
let _panelWindow;
// a-0. connect to background
const backgroundPageConnection = chrome.runtime.connect({
name: 'devtools-page'
});
// a-4. pass t... |
Use directly magento classes to do store emulation. | <?php
class SPM_ShopyMind_Action_GetCategory implements SPM_ShopyMind_Interface_Action
{
private $scope;
private $categoryId;
private $Category;
private $Formatter;
public function __construct(SPM_ShopyMind_Model_Scope $scope, $categoryId)
{
$this->Category = Mage::getModel('catalog/ca... | <?php
class SPM_ShopyMind_Action_GetCategory implements SPM_ShopyMind_Interface_Action
{
private $scope;
private $categoryId;
private $Category;
private $Formatter;
public function __construct(SPM_ShopyMind_Model_Scope $scope, $categoryId)
{
$this->Category = Mage::getModel('catalog/ca... |
Switch accidentally changed call and dial sounds | 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
angular.module('audiohandler', [])
.factory('audioFactory', function ($ionicPlatform, $window, $cordovaNativeAudio) {
$ionicPlatform.ready(function () {
if ($window.cordova) {
$cordovaNativeAudio.preloadComplex('dial', 'res... | 'use strict';
/*
* Module for playing audio, now the Angular way!
*/
angular.module('audiohandler', [])
.factory('audioFactory', function ($ionicPlatform, $window, $cordovaNativeAudio) {
$ionicPlatform.ready(function () {
if ($window.cordova) {
$cordovaNativeAudio.preloadComplex('call', 'res... |
Clean hint logic from copy/paste | (function(win, doc, $, ko){
var options = {
hiddenClass: 'hidden'
};
ko.bindingHandlers.hint = {
init:function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
hintOptions = allBindingsAccessor().hintOptions,
cssCl... | (function(win, doc, $, ko){
var options = {
hiddenClass: 'hidden'
};
ko.bindingHandlers.hint = {
init:function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
hintOptions = allBindingsAccessor().hintOptions,
cssCl... |
Raise our own ImportError if all fails. Looks better than to complain about
django when that happens | """
Get the best JSON encoder/decoder available on this system.
"""
__version__ = "0.1"
__author__ = "Rune Halvorsen <runefh@gmail.com>"
__homepage__ = "http://bitbucket.org/runeh/anyjson/"
__docformat__ = "restructuredtext"
"""
.. function:: serialize(obj)
Serialize the object to JSON.
.. function:: deseriali... | """
Get the best JSON encoder/decoder available on this system.
"""
__version__ = "0.1"
__author__ = "Rune Halvorsen <runefh@gmail.com>"
__homepage__ = "http://bitbucket.org/runeh/anyjson/"
__docformat__ = "restructuredtext"
"""
.. function:: serialize(obj)
Serialize the object to JSON.
.. function:: deseriali... |
Remove relevance settings, but leave the extended example. | /*
Language: Flix
Category: functional
Author: Magnus Madsen <mmadsen@uwaterloo.ca>
*/
function (hljs) {
var CHAR = {
className: 'string',
begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/
};
var STRING = {
className: 'string',
variants: [
{
begin: '"', e... | /*
Language: Flix
Category: functional
Author: Magnus Madsen <mmadsen@uwaterloo.ca>
*/
function (hljs) {
var CHAR = {
className: 'string',
begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/,
relevance: 0
};
var STRING = {
className: 'string',
variants: [
{
... |
Correct paths to Codeception etc. | <?php
/**
* Define Robo commands for building and testing Drupal User Registry Codeception module.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks
{
/**
* @type string
* Location of directory containing source code.
*/
const SRC_DIR = "src";
/**
* @type string
... | <?php
/**
* Define Robo commands for building and testing Drupal User Registry Codeception module.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks
{
/**
* @type string
* Location of directory containing source code.
*/
const SRC_DIR = "src";
/**
* @type string
... |
Allow Django Evolution to install along with Django >= 1.7.
As we're working toward some degree of compatibility with newer versions
of Django, we need to ease up on the version restriction. Now's a good
time to do so. Django Evolution no longer has an upper bounds on the
version range. | #!/usr/bin/env python
#
# Setup script for Django Evolution
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
from django_evolution import get_package_version, VERSION
def run_tests(*args):
import os
os.system('tests/ru... | #!/usr/bin/env python
#
# Setup script for Django Evolution
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
from django_evolution import get_package_version, VERSION
def run_tests(*args):
import os
os.system('tests/ru... |
Support older apache httpclient libs | package com.akamai.edgegrid.signer.apachehttpclient;
import com.akamai.edgegrid.signer.ClientCredential;
import com.akamai.edgegrid.signer.ClientCredentialProvider;
import com.akamai.edgegrid.signer.exceptions.NoMatchingCredentialException;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
impo... | package com.akamai.edgegrid.signer.apachehttpclient;
import com.akamai.edgegrid.signer.ClientCredential;
import com.akamai.edgegrid.signer.ClientCredentialProvider;
import com.akamai.edgegrid.signer.exceptions.NoMatchingCredentialException;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
impo... |
Bump elastalert version to 0.1.0 | # -*- coding: utf-8 -*-
import os
from setuptools import find_packages
from setuptools import setup
base_dir = os.path.dirname(__file__)
setup(
name='elastalert',
version='0.1.0',
description='Runs custom filters on Elasticsearch and alerts on matches',
author='Quentin Long',
author_email='qlo@ye... | # -*- coding: utf-8 -*-
import os
from setuptools import find_packages
from setuptools import setup
base_dir = os.path.dirname(__file__)
setup(
name='elastalert',
version='0.0.99',
description='Runs custom filters on Elasticsearch and alerts on matches',
author='Quentin Long',
author_email='qlo@y... |
Fix declaration of namespace and uses | <?php
namespace SlaxWeb\Bootstrap;
use SlaxWeb\Hooks\Hooks;
use SlaxWeb\Registry\Container as Registry;
class Swf
{
/**
* Composer Autoloader
*
* @var object
*/
protected $_loader = null;
/**
* Router
*
* @var \SlaxWeb\Router\Router
*/
protected $_router = null;... | <?php
namespace \SlaxWeb\Bootstrap;
use \SlaxWeb\Hooks\Hooks;
use \SlaxWeb\Registry\Container as Registry;
class Swf
{
/**
* Composer Autoloader
*
* @var object
*/
protected $_loader = null;
/**
* Router
*
* @var \SlaxWeb\Router\Router
*/
protected $_router = nu... |
Correct sequence name for oracle
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@977 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.domain;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
impor... | package edu.northwestern.bioinformatics.studycalendar.domain;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
impor... |
Add test case for new version of IUCN | <?php
namespace Test\AppBundle\API\Details;
use AppBundle\API\Details\OrganismsWithTrait;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class OrganismsWithTraitTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->defau... | <?php
namespace Test\AppBundle\API\Details;
use AppBundle\API\Details\OrganismsWithTrait;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class OrganismsWithTraitTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->defau... |
Update ALLOWED_HOSTS for move to service domain | from .base import *
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG
GOOGLE_ANALYTICS_ID = "UA-53811587-1"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ.g... | from .base import *
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG
GOOGLE_ANALYTICS_ID = "UA-53811587-1"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ.g... |
Fix serverUrl invokable call in the mailer plugin | <?php
namespace RbComment\Mvc\Controller\Plugin;
use Zend\Mail\Message;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class Mailer extends AbstractPlugin
{
private $serverUrlHelper;
private $mailerService;
private $configService;
... | <?php
namespace RbComment\Mvc\Controller\Plugin;
use Zend\Mail\Message;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class Mailer extends AbstractPlugin
{
private $serverUrlHelper;
private $mailerService;
private $configService;
... |
Fix default captcha reload algo
System helper on method "buildSingleTag" escaping all quotes that make
imposible use inline javascript in onClick method | <?php
namespace Ffcms\Core\Helper\HTML\Form;
use Ffcms\Core\App;
use Ffcms\Core\Helper\HTML\System\NativeGenerator;
class CaptchaField extends NativeGenerator implements iField
{
private $properties;
private $name;
/**
* CaptchaField constructor. Pass attributes inside model.
* @param arra... | <?php
namespace Ffcms\Core\Helper\HTML\Form;
use Ffcms\Core\App;
use Ffcms\Core\Helper\HTML\System\NativeGenerator;
class CaptchaField extends NativeGenerator implements iField
{
private $properties;
private $name;
/**
* CaptchaField constructor. Pass attributes inside model.
* @param arra... |
Set the customer_themes static dir prefix for devstack (no S3) customer theme file storage to match expectation in SiteConfiguration model method | """
Settings for Appsembler on devstack/LMS.
"""
from os import path
from openedx.core.djangoapps.appsembler.settings.settings import devstack_common
def plugin_settings(settings):
"""
Appsembler LMS overrides for devstack.
"""
devstack_common.plugin_settings(settings)
settings.DEBUG_TOOLBAR_PAT... | """
Settings for Appsembler on devstack/LMS.
"""
from os import path
from openedx.core.djangoapps.appsembler.settings.settings import devstack_common
def plugin_settings(settings):
"""
Appsembler LMS overrides for devstack.
"""
devstack_common.plugin_settings(settings)
settings.DEBUG_TOOLBAR_PAT... |
Put exception eating back in | package org.opencds.cqf.config;
import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;
import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider;
import org.cqframework.cql.cql2elm.LibrarySourceProvider;
import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.ds... | package org.opencds.cqf.config;
import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;
import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider;
import org.cqframework.cql.cql2elm.LibrarySourceProvider;
import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.ds... |
Fix font-awesome LESS source not being found in some cases | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Asset;
use Less_Exception_Parser;
use Less_Parser;
class LessCompiler extends R... | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Asset;
use Less_Exception_Parser;
use Less_Parser;
class LessCompiler extends R... |
[FIX] Define UTC as tz in get_working_days_of_date method | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_... | # -*- coding: utf-8 -*-
# See README.rst file on addon root folder for license details
from openerp import models, api
from datetime import datetime, timedelta
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
@api.v7
def get_working_days_of_date(self, cr, uid, id, start_dt=None, end_... |
Refresh the widget data on browser restart. | (function() {
'use strict';
window.widgets = {};
$(function() {
var defaults = {
platformUrl: 'https://partner.voipgrid.nl/',
c2d: 'true',
};
for(var key in defaults) {
if(defaults.hasOwnProperty(key)) {
if(storage.get(key) === n... | (function() {
'use strict';
window.widgets = {};
$(function() {
var defaults = {
platformUrl: 'https://partner.voipgrid.nl/',
c2d: 'true',
};
for(var key in defaults) {
if(defaults.hasOwnProperty(key)) {
if(storage.get(key) === n... |
Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.Pa... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.Pa... |
Fix line ending printing on Python 3
To reflect the changes in
https://chromium-review.googlesource.com/c/chromium/src/+/2896248/8/third_party/node/node.py
R=993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org
Bug: none
Change-Id: I25ba29042f537bfef57fba93115be2c194649864
Reviewed-on: https://chromium-review.googl... | #!/usr/bin/env vpython
# Copyright 2017 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.
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
... | #!/usr/bin/env vpython
# Copyright 2017 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.
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
... |
Fix an issue with being able to update statuses | <?php
namespace Github\Api\Repository;
use Github\Api\AbstractApi;
use Github\Exception\MissingArgumentException;
/**
* @link http://developer.github.com/v3/repos/statuses/
* @author Joseph Bielawski <stloyd@gmail.com>
*/
class Statuses extends AbstractApi
{
/**
* @link http://developer.github.com/v3/r... | <?php
namespace Github\Api\Repository;
use Github\Api\AbstractApi;
use Github\Exception\MissingArgumentException;
/**
* @link http://developer.github.com/v3/repos/statuses/
* @author Joseph Bielawski <stloyd@gmail.com>
*/
class Statuses extends AbstractApi
{
/**
* @link http://developer.github.com/v3/r... |
Fix regression error in file path. | 'use strict';
var path = require('path'),
childProcess = require('child_process'),
phantomjs = require('phantomjs'),
binPath = phantomjs.path;
module.exports = function (filepath, options, callback) {
var opt = options || {},
cb = callback || function () {},
runner = './node_modules/qu... | 'use strict';
var path = require('path'),
childProcess = require('child_process'),
phantomjs = require('phantomjs'),
binPath = phantomjs.path;
module.exports = function (filepath, options, callback) {
var opt = options || {},
cb = callback || function () {},
runner = './node_modules/qu... |
Remove treebeard dependency (it's django-treebeard). | from setuptools import setup
version = '0.2.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django',
'cassandralib',
'django-extensions',
'django-nose',
'django-treebeard',
'liza... | from setuptools import setup
version = '0.2.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django',
'cassandralib',
'django-extensions',
'django-nose',
'django-treebeard',
'liza... |
Update component state even when not editing | import React, { Component } from 'react'
import { Creatable } from 'react-select'
import R from 'ramda'
class TagSelect extends Component {
state = {
multi: true,
multiValue: [],
options: this.props.options
}
componentWillReceiveProps = nextProps => {
if (nextProps.input.value) {
... | import React, { Component } from 'react'
import { Creatable } from 'react-select'
import R from 'ramda'
class TagSelect extends Component {
state = {
multi: true,
multiValue: [],
options: this.props.options
}
componentWillReceiveProps = nextProps => {
if (nextProps.edit && nextProp... |
Revert "adding settings for EJS render method" | 'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var ejs = require('ejs');
var assign = require('object-assign');
module.exports = function (options, settings) {
options = options || {};
settings = settings || {};
return through.obj(function (file, enc, cb) {
if ... | 'use strict';
var through = require('through2');
var gutil = require('gulp-util');
var ejs = require('ejs');
var assign = require('object-assign');
module.exports = function (options, settings) {
options = options || {};
settings = settings || {};
return through.obj(function (file, enc, cb) {
if ... |
Make it possible to run this test stand-alone. | # Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import captured_stdout, run_unittest
import unittest
import sys, os
class FrozenTests(unittest.TestCase):
def test_frozen(self):
with captured_stdout() as stdout:
try:
im... | # Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import captured_stdout, run_unittest
import unittest
import sys, os
class FrozenTests(unittest.TestCase):
def test_frozen(self):
with captured_stdout() as stdout:
try:
im... |
Add in ajax for newadminbox | $.fn.editable.defaults.mode = 'inline';
$(document).ready(function() {
$('#newelectionbox').submit(function(event) {
document.getElementById("submitbtn").disabled = true;
document.getElementById("submitbtn").innerHTML = "Creating...";
var formData = {
'election'... | $.fn.editable.defaults.mode = 'inline';
$(document).ready(function() {
$('#newelectionbox').submit(function(event) {
document.getElementById("submitbtn").disabled = true;
document.getElementById("submitbtn").innerHTML = "Creating...";
var formData = {
'election'... |
Build base instead of preflight | import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'
function buildDistFile(filename) {
return new Promise((resolve, reject) => {
console.log(`Processing ./${filename}.css...`)
fs.readFile(`./${filename}.css`, (err, css) => {
if (err) throw err
... | import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'
function buildDistFile(filename) {
return new Promise((resolve, reject) => {
console.log(`Processing ./${filename}.css...`)
fs.readFile(`./${filename}.css`, (err, css) => {
if (err) throw err
... |
Remove esacpe method at driver (use bind instead) | <?php
namespace DB\Driver;
/**
* Interface for all database driver. Any database driver must implement
* this class.
*
* @package DB\Driver
*/
interface IDriver
{
/**
* Connect to selected database host
*
* @param string $host Database ho... | <?php
namespace DB\Driver;
/**
* Interface for all database driver. Any database driver must implement
* this class.
*
* @package DB\Driver
*/
interface IDriver
{
/**
* Connect to selected database host
*
* @param string $host Database ho... |
Update to compatible with PHPWebDriver 1.12.0 | <?php
require_once('PHPWebDriver/WebDriver.php');
require_once('SystemWebDriverSession.php');
/**
* SystemWebDriver This class is a duplication of WebDriver class in order to return a custom session object, which extends a few methods based on WebDriverSession class
*
* @uses PHPWebDriver_WebDriver
* @package test... | <?php
require_once('PHPWebDriver/WebDriver.php');
require_once('SystemWebDriverSession.php');
class SystemWebDriver extends PHPWebDriver_WebDriver {
function __construct($executor = null) {
if (! is_null($executor)) {
parent::__construct($executor);
} else {
parent::__... |
Update tests to use refactored path() | <?php
require_once 'minim/plugins/tests/tests.php';
require_once 'minim/minim.php';
class Minim_TestCase extends TestCase
{
function test_minim_get_plugin()
{
$minim = new Minim();
$this->assertTrue($minim !== minim());
$minim->plugin_paths = array(
path(dirname(__FILE__), ... | <?php
require_once 'minim/plugins/tests/tests.php';
require_once 'minim/minim.php';
class Minim_TestCase extends TestCase
{
function test_minim_get_plugin()
{
$minim = new Minim();
$this->assertTrue($minim !== minim());
$minim->plugin_paths = array(
build_path(dirname(__FIL... |
Include codegen package in distribution. | # -*- coding: utf-8 -*-
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='apalala@gmail.com',
packages=['grako', 'grako.codegen', ... | # -*- coding: utf-8 -*-
from setuptools import setup
try:
from Cython.Build import cythonize
except ImportError:
CYTHON = False
else:
CYTHON = True
setup(
name='grako',
version='3.1.3-rc.1',
author='Juancarlo Añez',
author_email='apalala@gmail.com',
packages=['grako', 'grako.test'],
... |
Use method store instead of storePublicly | <?php
namespace Canvas\Http\Controllers;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
class MediaController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @return mixed
*/
public function store()
... | <?php
namespace Canvas\Http\Controllers;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
class MediaController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @return mixed
*/
public function store()
... |
Create "Register configurations" method and move config codes | <?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Indicates if loading of the provider is deferred
*
* @var bool
*/
protected $defer = false;
/**
* Register th... | <?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Indicates if loading of the provider is deferred
*
* @var bool
*/
protected $defer = false;
/**
* Register th... |
Modify indicator list query.
Format indicator queries.
Corrected missing { for getIndicatorToUpdate | import gql from "graphql-tag";
class IndicatorRepository {
static getListPage(pageNumber, pageSize) {
return gql`
{
allIndicators{
nodes {
id
name
indicatorTypeByIndicatorTypeId {
name
}
indicatorGroupByIndicatorGro... | import gql from "graphql-tag";
class IndicatorRepository {
static getListPage(pageNumber, pageSize) {
return gql`{
allIndicators{
nodes {
id
name
description
executionOrder
flagActive
createdDate
updatedDate
indicatorTy... |
Update last seen date when connecting through socket.io | 'use strict';
/*
* Socket.io related things go !
*/
import { log, LOG_TYPES } from './log';
import { decodeJWT } from './JWT';
import models from '../models';
const User = models.User;
const EVENT_TYPES = {
DISCONNECT : 'disconnect',
CONNECTION : 'connection',
TOKEN_VALID ... | 'use strict';
/*
* Socket.io related things go !
*/
import { log, LOG_TYPES } from './log';
import { decodeJWT } from './JWT';
const EVENT_TYPES = {
DISCONNECT : 'disconnect',
CONNECTION : 'connection',
TOKEN_VALID : 'token_valid',
TOKEN_INVALID : 'token_invalid',
CONTACT_O... |
Abort with appropriate status codes in the decorator | from functools import wraps
from flask import session, redirect, url_for, request, abort
from alexandria import mongo
def not_even_one(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if mongo.Books.find_one() is None:
return redirect(url_for('upload'))
return f(*args, **kwarg... | from functools import wraps
from flask import session, redirect, url_for, request, abort
from alexandria import mongo
def not_even_one(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if mongo.Books.find_one() is None:
return redirect(url_for('upload'))
return f(*args, **kwarg... |
Fix bug in isOnTarget BandBangController | package com.team254.frc2015.subsystems.controllers;
import com.team254.lib.util.Controller;
public class BangBangFinishLineController extends Controller {
private double m_position;
private double m_goal;
private double m_tolerance;
private double m_direction = 0.0;
public BangBangFinishLineCont... | package com.team254.frc2015.subsystems.controllers;
import com.team254.lib.util.Controller;
public class BangBangFinishLineController extends Controller {
private double m_position;
private double m_goal;
private double m_tolerance;
private double m_direction = 0.0;
public BangBangFinishLineCont... |
Fix the description of DecompilationPhase.__init__(). | #
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Phase of a decompilation."""
class DecompilationPhase:
"""Phase of a decompilation."""
def __init__(self, name, part, description, completion):
... | #
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Phase of a decompilation."""
class DecompilationPhase:
"""Phase of a decompilation."""
def __init__(self, name, part, description, completion):
... |
Increase timeout of clean_duplicate_nodes job | import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
... | import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
... |
Use related_name etc to avoid code
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk> | from rest_framework import serializers, viewsets
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from takeyourmeds.reminder.models import Reminder
class ReminderTimeField(serializers.RelatedField):
def to_representa... | from rest_framework import serializers, viewsets
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from takeyourmeds.reminder.models import Reminder, ReminderTime
class ReminderTimeField(serializers.RelatedField):
def... |
Fix syntax error which causes redeclaration of a variable. | 'use strict';
var expect = require('chai').expect,
config = require('../../../config/config');
describe('config', function () {
describe('getConfig', function () {
var configDirectory = '../../../config/';
describe('existing configuration', function () {
var testCases = [
... | 'use strict';
var expect = require('chai').expect,
config = require('../../../config/config');
describe('config', function () {
describe('getConfig', function () {
var configDirectory = '../../../config/';
describe('existing configuration', function () {
var testCases = [
... |
Add path in test to src | import unittest
import sys
sys.path.append('../src')
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
... | import unittest
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
... |
Fix values sent to CloudWatch for requests and allocations. Check that CloudWatch is available and change timer to 50 seconds. | var async = require('async');
var context;
var publishTimer;
function publishToDashboard() {
async.waterfall([
function(callback) {
context.consuler.getKeyValue(context.keys.request, function(result) {
callback(null, result);
});
},
function(requests... | var async = require('async');
var context;
var publishTimer;
function publishToDashboard() {
async.waterfall([
function(callback) {
context.consuler.getKeyValue(context.keys.request, function(result) {
callback(null, result);
});
},
function(requests... |
Make sure we're checking ints to ints. | import stomp
import urlparse
import json
urlparse.uses_netloc.append('tcp')
class ZKillboardStompListener(object):
def __init__(self, bot):
self.bot = bot
self.conn = None
def on_error(self, headers, message):
pass
def on_message(self, headers, message):
kill = json.load... | import stomp
import urlparse
import json
urlparse.uses_netloc.append('tcp')
class ZKillboardStompListener(object):
def __init__(self, bot):
self.bot = bot
self.conn = None
def on_error(self, headers, message):
pass
def on_message(self, headers, message):
kill = json.load... |
Add a test for the multi-location Rsync::fromPath. | <?php
use AspectMock\Test as test;
use Robo\Robo;
class RsyncTest extends \Codeception\TestCase\Test
{
/**
* @var \CodeGuy
*/
protected $guy;
// tests
public function testRsync()
{
verify(
(new \Robo\Task\Remote\Rsync())
->fromPath('src/')
... | <?php
use AspectMock\Test as test;
use Robo\Robo;
class RsyncTest extends \Codeception\TestCase\Test
{
/**
* @var \CodeGuy
*/
protected $guy;
// tests
public function testRsync()
{
verify(
(new \Robo\Task\Remote\Rsync())
->fromPath('src/')
... |
Support seminars in addition to lectures and labs | from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstr... | from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstr... |
Fix "AppRegistryNotReady: Models aren't loaded yet" | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
import django
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'django.db.backends.postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'django.db.bac... | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
import django
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'django.db.backends.postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'django.db.bac... |
Add unique identifier in front of the label | 'use strict';
// convert an experiment, an array of spectra, to a chart
var types=require('./types.js');
module.exports=function (experiments, channels, index) {
var channels = channels || 'RGBWZE'
if (! Array.isArray(experiments)) experiments=[experiments];
var chart = {
type: "chart",
... | 'use strict';
// convert an experiment, an array of spectra, to a chart
var types=require('./types.js');
module.exports=function (experiments, channels, index) {
var channels = channels || 'RGBWZE'
if (! Array.isArray(experiments)) experiments=[experiments];
var chart = {
type: "chart",
... |
Add registration of world + protection cmds
Signed-off-by: Ollie <caf5c3fc6dbe0c347eab97fff2fea94d86d406b9@live.co.uk> | package com.volumetricpixels.vitals.main;
import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;
import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vita... | package com.volumetricpixels.vitals.main;
import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;
import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vita... |
Fix URLs in footer for children pages | import React, {Component, PropTypes} from "react"
import SVGIcon from "../SVGIcon"
import requireRaw from "../requireRaw"
export default class Footer extends Component {
static contextTypes = {
file: PropTypes.object.isRequired,
}
static defaultProps = {
playground: true,
}
static propTypes = {
... | import React, {Component, PropTypes} from "react"
import SVGIcon from "../SVGIcon"
import requireRaw from "../requireRaw"
export default class Footer extends Component {
static contextTypes = {
file: PropTypes.object.isRequired,
}
static defaultProps = {
plagryound: true,
}
static propTypes = {
... |
Fix units on wallet info screen | 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lod... | 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lod... |
Change the behaviour of the markdown text processor so it follows better whitespace boundary rules | <?php
namespace App\Helpers\BBCode\Processors;
class MarkdownTextProcessor extends Processor {
function Process($result, $text, $scope) {
/*
* Like everything else here, this isn't exactly markdown, but it's close.
* _underline_
* /italics/
* *bold*
* ~strik... | <?php
namespace App\Helpers\BBCode\Processors;
class MarkdownTextProcessor extends Processor {
function Process($result, $text, $scope) {
/*
* Like everything else here, this isn't exactly markdown, but it's close.
* _underline_
* /italics/
* *bold*
* ~strik... |
Fix an issue that caused unnecessary code to end up in the transpiled file. | var clone= require('clone');
var paths = require('./build/paths');
var webpackConfig = clone(require('./webpack.config.js'));
// Add istanbul-instrumenter to webpack configuration
webpackConfig.module.loaders.push(
{
test: /\.js$/,
exclude: /(node_modules|test)/,
loader: 'babel-istanbul-lo... | var paths = require('./build/paths');
var webpackConfig = require('./webpack.config.js');
// Add istanbul-instrumenter to webpack configuration
webpackConfig.module.loaders.push(
{
test: /\.js$/,
exclude: /(node_modules|test)/,
loader: 'babel-istanbul-loader'
}
);
// The main configu... |
Rename a variable in TrackingTreeNodeDecocator | package hu.webarticum.treeprinter.decorator;
import hu.webarticum.treeprinter.TreeNode;
public class TrackingTreeNodeDecorator extends AbstractTreeNodeDecorator {
public final TrackingTreeNodeDecorator parent;
public final int index;
public TrackingTreeNodeDecorator(TreeNode baseNode) {
... | package hu.webarticum.treeprinter.decorator;
import hu.webarticum.treeprinter.TreeNode;
public class TrackingTreeNodeDecorator extends AbstractTreeNodeDecorator {
public final TrackingTreeNodeDecorator parent;
public final int index;
public TrackingTreeNodeDecorator(TreeNode baseNode) {
... |
Add some comments in dockerfile | 'use strict';
// Development specific configuration
// ==================================
module.exports = {
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI || 'mongodb://localhost:27017/easydownload-dev'
},
itemCron: '*/5 * * * * *',
thingCron: '*/10 * * * * *',
esCron: '*/20 * *... | 'use strict';
// Development specific configuration
// ==================================
module.exports = {
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI || 'mongodb://localhost:27017/easydownload-dev'
},
itemCron: '*/5 * * * * *',
thingCron: '*/10 * * * * *',
esCron: '*/20 * *... |
Integrate improvement by JProffitt71 to properly support Jade view extend/include | define(['./module', '_'], function (views, _) {
'use strict';
var templates = {};
var jade = require('jade'),
fs = require('fs'),
path = require('path');
fs.readdir(path.resolve('./views'), function(err, files) {
console.log("Found %d files", files.length);
_.each(fi... | define(['./module', '_'], function (views, _) {
'use strict';
var templates = {};
var jade = require('jade'),
fs = require('fs'),
path = require('path');
fs.readdir(path.resolve('./views'), function(err, files) {
console.log("Found %d files", files.length);
_.each(fi... |
Use addProvider method instead of constructor | <?php
namespace DisposableEmailChecker\Tests;
use DisposableEmailChecker\Checker;
use DisposableEmailChecker\Provider\ChainProvider;
use DisposableEmailChecker\Provider\InMemoryProvider;
class CheckerTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider validResults
*/
public function test... | <?php
namespace DisposableEmailChecker\Tests;
use DisposableEmailChecker\Checker;
use DisposableEmailChecker\Provider\ChainProvider;
use DisposableEmailChecker\Provider\InMemoryProvider;
class CheckerTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider validResults
*/
public function test... |
Fix old media from not being removed | <?php namespace Torann\MediaSort\Disks;
use File;
use Config;
use Storage;
use Exception;
abstract class AbstractDisk {
/**
* The current media object being processed.
*
* @var \Torann\MediaSort\Manager
*/
public $media;
/**
* Storage configurations.
*
* @var array
... | <?php namespace Torann\MediaSort\Disks;
use File;
use Config;
use Storage;
use Exception;
abstract class AbstractDisk {
/**
* The current media object being processed.
*
* @var \Torann\MediaSort\Manager
*/
public $media;
/**
* Storage configurations.
*
* @var array
... |
Clear the status only when the timeout is valid | 'use strict';
import { StatsCollector } from './lib/stats';
export default function(RED) {
class DeviceStatsNode {
constructor(n) {
RED.nodes.createNode(this, n);
this.name = n.name;
this.mem = n.mem;
this.nw = n.nw;
this.load = n.load;
this.hostname = n.hostname;
this... | 'use strict';
import { StatsCollector } from './lib/stats';
export default function(RED) {
class DeviceStatsNode {
constructor(n) {
RED.nodes.createNode(this, n);
this.name = n.name;
this.mem = n.mem;
this.nw = n.nw;
this.load = n.load;
this.hostname = n.hostname;
this... |
Convert rows to list in EVL CEG parser
It needs to access cells directly | from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"age... | from datetime import datetime
import itertools
from tests.support.test_helpers import d_tz
def ceg_volumes(rows):
def ceg_keys(rows):
return [
"_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr",
"relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent",
"age... |
Allow web command to be used with a non-existent environment | <?php
namespace Platformsh\Cli\Command;
use Platformsh\Cli\Service\Url;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class WebCommand extends CommandBase
{
protected function configure()
{
$this
->setName('web')
->s... | <?php
namespace Platformsh\Cli\Command;
use Platformsh\Cli\Service\Url;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class WebCommand extends CommandBase
{
protected function configure()
{
$this
->setName('web')
->s... |
Store created assert and reuse.
This makes it clearer when asserts need to be created and is more efficient. | define('parsley/factory/constraint', [
'parsley/utils'
], function (ParsleyUtils) {
var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) {
var assert = {};
if (!new RegExp('ParsleyField').test(ParsleyUtils.get(parsleyField, '__class__')))
throw new Error('Par... | define('parsley/factory/constraint', [
'parsley/utils'
], function (ParsleyUtils) {
var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) {
if (!new RegExp('ParsleyField').test(ParsleyUtils.get(parsleyField, '__class__')))
throw new Error('ParsleyField or ParsleyF... |
Use function name with bind | define([
'jquery',
'underscore',
'backbone',
'app',
'text!templates/auth/signUpTemplate.html'
], function($, _, Backbone, app, signUpTemplate){
var SignUpView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
_.bindAll(this, 'onSignupAttempt', 'render');
// Listen for ... | define([
'jquery',
'underscore',
'backbone',
'app',
'text!templates/auth/signUpTemplate.html'
], function($, _, Backbone, app, signUpTemplate){
var SignUpView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
_.bindAll(this);
// Listen for session logged_in state chang... |
Fix bug in serving partial css files | var task = function(gulp, config) {
'use strict';
gulp.task('browserSync', function() {
var path = require('path');
var fs = require('fs');
var browserSync = require('browser-sync').create();
var html5Regex = new RegExp('\/'+config.name+'\/(.*)$');
browserSync.init({
server: {
//... | var task = function(gulp, config) {
'use strict';
gulp.task('browserSync', function() {
var path = require('path');
var fs = require('fs');
var browserSync = require('browser-sync').create();
var html5Regex = new RegExp('\/'+config.name+'\/(.*)$');
browserSync.init({
server: {
... |
Trim NID and make it uppercase & combine dummy email inline | <?php
namespace App\Services;
use App\Student;
use App\User;
use Carbon\Carbon;
class UserService
{
/**
* 尋找使用者,若找不到,則建立使用者並綁定
*
* @param Student $student
* @return User
*/
public function findOrCreateAndBind(Student $student)
{
$user = $student->user;
if (!$user)... | <?php
namespace App\Services;
use App\Student;
use App\User;
use Carbon\Carbon;
class UserService
{
/**
* 尋找使用者,若找不到,則建立使用者並綁定
*
* @param Student $student
* @return User
*/
public function findOrCreateAndBind(Student $student)
{
$user = $student->user;
if (!$user)... |
Fix custom widget to raise correct exception type. | """
General purpose formish extensions.
"""
from formish import validation, widgets, Form
from convertish.convert import ConvertError
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class Approximat... | """
General purpose formish extensions.
"""
from formish import validation, widgets, Form
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_templat... |
Fix use of 'json' instead of 'j'
This bug was created when switching from simplejson to json module,
due to python 2.5->2.7 migration. Any variables named 'json' needed
to be renamed, and this is an instance that was missed. | import os
import models
import config
import time
from hashlib import md5
import json
import serverinfo
from google.appengine.ext import webapp
"""
{
"info": {
"name": "<name>",
"start_utc": <long>
},
"command": {
"command": "<command name>",
"<arg0 name>": "<arg0 value>",... | import os
import models
import config
import time
from hashlib import md5
import json
import serverinfo
from google.appengine.ext import webapp
"""
{
"info": {
"name": "<name>",
"start_utc": <long>
},
"command": {
"command": "<command name>",
"<arg0 name>": "<arg0 value>",... |
Add classifier type to the base class | class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
def get_key(self, classification_type, classifier, key... | class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
def get_key(self, classifier, key, default=None):
... |
Add id to navigation bar and removed unnecessary spacer | Ext.define('SenchaFront.view.Main', {
extend: 'Ext.NavigationView',
xtype: 'main',
requires: [
'Ext.plugin.ListSwipeAction',
'Ext.dataview.List'
],
config: {
ui: 'sencha',
fullscreen: true,
id: 'navigationView',
items: [
{
t... | Ext.define('SenchaFront.view.Main', {
extend: 'Ext.NavigationView',
xtype: 'main',
requires: [
'Ext.plugin.ListSwipeAction',
'Ext.dataview.List'
],
config: {
ui: 'sencha',
fullscreen: true,
id: 'navigationView',
items: [
{
t... |
Use 'params' instead of 'parameters' | // ==UserScript==
// @name Slickdeals Don't Track Me!
// @version 1.1
// @description Replaces outgoing Slickdeals tracking links with direct links.
// @match http://slickdeals.net/f/*
// @namespace https://github.com/gg/slickdeals-dont-track-me
// @author Gregg Gajic <https://github.com/gg>
// @licen... | // ==UserScript==
// @name Slickdeals Don't Track Me!
// @version 1.1
// @description Replaces outgoing Slickdeals tracking links with direct links.
// @match http://slickdeals.net/f/*
// @namespace https://github.com/gg/slickdeals-dont-track-me
// @author Gregg Gajic <https://github.com/gg>
// @licen... |
Update skip condition for tests | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from simplesqlite import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_... |
Use container names, rather than hostnames, for virtual ethernet interface names
Container names are guaranteed to be unique, but hostnames are not | import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{name}'.format(name=self.name)
veth_host_name =... | import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
veth... |
Use a function to chain sendCommands method | var Q = require('q'),
mpd = require('mpd'),
EventEmitter = require('events').EventEmitter,
winston = require('winston');
exports.create = function (port, logger) {
var client;
var logger = logger || winston;
var ready = Q.defer();
function connect(mpdClient) {
client = mpdClient || ... | var Q = require('q'),
mpd = require('mpd'),
EventEmitter = require('events').EventEmitter,
winston = require('winston');
exports.create = function (port, logger) {
var client;
var logger = logger || winston;
var ready = Q.defer();
function connect(mpdClient) {
client = mpdClient || ... |
Make sure all properties are set during insert and errors are logged properly | import sqlite3 from 'sqlite3';
import { createLogObject } from './csv.js';
const SQL_PROPERTIES = [
'event_id', 'date', 'id', 'name', 'type', 'value', 'battery', 'dark', 'daylight'
]
const SQL = `
INSERT INTO log (${SQL_PROPERTIES.join(", ")})
VALUES (${SQL_PROPERTIES.map(v => `\$${v}`).join(", ")})
`;
e... | import sqlite3 from 'sqlite3';
import { createLogObject } from './csv.js';
const SQL = `
INSERT INTO log (event_id, date, id, name, type, value, battery, dark, daylight)
VALUES ($event_id, $date, $id, $name, $type, $value, $battery, $dark, $daylight)
`;
export default class SQLiteLogger {
constructor(dbU... |
Add Moksha Hub version requirement
New features of statscache require a moksha installation with corresponding
support, or else it won't run at all. | """ Setup file for statscache """
from setuptools import setup
def get_description():
with open('README.rst', 'r') as f:
return ''.join(f.readlines()[2:])
requires = [
'fedmsg',
'moksha.hub>=1.4.6',
'fedmsg_meta_fedora_infrastructure',
'sqlalchemy',
]
tests_require = [
'nose',
'... | """ Setup file for statscache """
from setuptools import setup
def get_description():
with open('README.rst', 'r') as f:
return ''.join(f.readlines()[2:])
requires = [
'fedmsg',
'fedmsg_meta_fedora_infrastructure',
'sqlalchemy',
]
tests_require = [
'nose',
'freezegun'
]
setup(
... |
Fix empty void when user has no tags for tags' index view | @extends('layout')
@section('body')
<div class="wrapper spacing-top-large spacing-bottom-large">
<div class="box">
<div class="section">
<div class="row">
<div class="column align-middle">
<span class="color-dark">@lang('general.tags')... | @extends('layout')
@section('body')
<div class="wrapper spacing-top-large spacing-bottom-large">
<div class="box">
<div class="section">
<div class="row">
<div class="column align-middle">
<span class="color-dark">@lang('general.tags')... |
Clean up module loading printing | import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.module... | import os, sys
from glob import glob
import GlobalVars
def LoadFunction(path, loadAs=''):
loadType = 'l'
name = path
src = __import__('Functions.' + name, globals(), locals(), [])
if loadAs != '':
name = loadAs
if name in GlobalVars.functions:
loadType = 'rel'
del sys.module... |
Add method to remove logged messages | <?php
namespace PicoFeed;
use DateTime;
use DateTimeZone;
/**
* Logging class
*
* @author Frederic Guillot
* @package picofeed
*/
class Logging
{
/**
* List of messages
*
* @static
* @access private
* @var array
*/
private static $messages = array();
/**
* Defaul... | <?php
namespace PicoFeed;
use DateTime;
use DateTimeZone;
/**
* Logging class
*
* @author Frederic Guillot
* @package picofeed
*/
class Logging
{
/**
* List of messages
*
* @static
* @access private
* @var array
*/
private static $messages = array();
/**
* Defaul... |
Update init command to not hang. | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class Init extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mangapie:init';
/**
* The console command de... | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class Init extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mangapie:init';
/**
* The console command de... |
Set logging level to INFO | import logging
from time import time, sleep
from .net_utils import *
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def target_scaner(interface, min_interval=30):
old_peers = {}
while True:
begin_time = time()
peers = {}
for ip, mac in arp_scaner():
... | import logging
from time import time, sleep
from .net_utils import *
logger = logging.getLogger(__name__)
def target_scaner(interface, min_interval=30):
old_peers = {}
while True:
begin_time = time()
peers = {}
for ip, mac in arp_scaner():
peers[ip] = mac
if ip... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.