text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Fix line continuation indent level. | """SOAP client."""
from __future__ import print_function
import requests
from rinse import ENVELOPE_XSD
from rinse.util import SCHEMA
from rinse.response import RinseResponse
class SoapClient(object):
"""Rinse SOAP client."""
__session = None
def __init__(self, url, debug=False, **kwargs):
"""S... | """SOAP client."""
from __future__ import print_function
import requests
from rinse import ENVELOPE_XSD
from rinse.util import SCHEMA
from rinse.response import RinseResponse
class SoapClient(object):
"""Rinse SOAP client."""
__session = None
def __init__(self, url, debug=False, **kwargs):
"""S... |
Enable node.js to support both http and https | const https = require("https"),
http = require("http"),
zlib = require("zlib"),
fs = require("fs"),
path = require("path"),
isURL = require("is-url");
var langdata = require('../common/langdata.json')
function getLanguageData(req, res, cb){
var lang = req.options.lang,
lang... | const http = require("http"),
zlib = require("zlib"),
fs = require("fs"),
path = require("path"),
isURL = require("is-url");
var langdata = require('../common/langdata.json')
function getLanguageData(req, res, cb){
var lang = req.options.lang,
langfile = lang + '.traineddata.gz';... |
Add quotes so all params are strings | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... |
Fix new route after new ember-data | (function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEm... | (function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEm... |
Use a fixed thumbnail size rather then a relative scale. | """An overview window showing thumbnails of the image set.
"""
from __future__ import division
import math
from PySide import QtCore, QtGui
class ThumbnailWidget(QtGui.QLabel):
ThumbnailSize = QtCore.QSize(128, 128)
def __init__(self, image):
super(ThumbnailWidget, self).__init__()
pixmap =... | """An overview window showing thumbnails of the image set.
"""
from __future__ import division
import math
from PySide import QtCore, QtGui
class ThumbnailWidget(QtGui.QLabel):
def __init__(self, image, scale):
super(ThumbnailWidget, self).__init__()
pixmap = image.getPixmap()
size = sca... |
Update avoider's use of BBCServices | var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = routes;
function routes(app, radiodan, bbcServices) {
var avoidPlayer = radiodan.player.get("avoider"),
mainPlayer = radiodan.player.get("main"),
announcePlayer = radiodan.player.get("announcer")... | var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = routes;
function routes(app, radiodan, bbcServices) {
var avoidPlayer = radiodan.player.get("avoider"),
mainPlayer = radiodan.player.get("main"),
announcePlayer = radiodan.player.get("announcer")... |
Improve naive bayes unit test. | import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
... | import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ... |
Remove commented out debug print lines | # -*- coding: utf-8 -*-
from helpers import HTTPEventHandler
import looping
import buffer_event
class StatusClient(HTTPEventHandler):
def __init__(self, server, sock, address, request_parser):
HTTPEventHandler.__init__(self, server, sock, address, request_parser,
204, b'... | # -*- coding: utf-8 -*-
from helpers import HTTPEventHandler
import looping
import buffer_event
class StatusClient(HTTPEventHandler):
def __init__(self, server, sock, address, request_parser):
HTTPEventHandler.__init__(self, server, sock, address, request_parser,
204, b'... |
Fix bug when starting pmdr multiple times |
var Pomodoro = Backbone.Model.extend({
defaults: {
isStarted: false,
duration: 25 * 60,
remainingSeconds: null
},
initialize: function() {
this.listenTo(this, 'finished', this.finish);
},
start: function(duration){
if (duration) {
this.set('dur... |
var Pomodoro = Backbone.Model.extend({
defaults: {
isStarted: false,
duration: 25 * 60,
remainingSeconds: null
},
initialize: function() {
this.listenTo(this, 'finished', this.finish);
},
start: function(duration){
if (duration) {
this.set('dur... |
Fix PSR-4 fix for Composer deprecation
Composer:
Deprecation Notice: Class Sly\Sly\NotificationPusher\Adapter\ApnsAPI located in ./vendor/sly/notification-pusher/src/Sly/NotificationPusher/Adapter/ApnsAPI.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in /vendor/... | <?php
/**
* Created by PhpStorm.
* User: seyfer
* Date: 09.08.17
* Time: 17:03
*/
namespace Sly\NotificationPusher\Adapter;
use Sly\NotificationPusher\Adapter\BaseAdapter;
use Sly\NotificationPusher\Model\PushInterface;
/**
* Class ApnsAPI
* @package Sly\Sly\NotificationPusher\Adapter
*
* todo: implement w... | <?php
/**
* Created by PhpStorm.
* User: seyfer
* Date: 09.08.17
* Time: 17:03
*/
namespace Sly\Sly\NotificationPusher\Adapter;
use Sly\NotificationPusher\Adapter\BaseAdapter;
use Sly\NotificationPusher\Model\PushInterface;
/**
* Class ApnsAPI
* @package Sly\Sly\NotificationPusher\Adapter
*
* todo: impleme... |
Remove fake_button stuff from js | var bind_sortable = function() {
$('.sortable').sortable({
dropOnEmpty: true,
stop: function(evt, ui) {
var data = $(this).sortable('serialize', {attribute: 'data-sortable'});
$.ajax({
... | var bind_sortable = function() {
$('.sortable').sortable({
dropOnEmpty: true,
stop: function(evt, ui) {
var data = $(this).sortable('serialize', {attribute: 'data-sortable'});
$.ajax({
... |
Fix issue where first selection in detail pane after refresh would not be possible |
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
if (!rangy.initialized) rangy.init();
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
var e = rangy.createRange();
e.setStart(range.startContainer, range.start... |
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
if (!rangy.initialized) rangy.init();
var e = rangy.createRange();
e.setStart(range.startContainer, rang... |
Save descriptor into field so can start parsing other elkements | package org.realityforge.arez.processor;
import javax.annotation.Nonnull;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.T... | package org.realityforge.arez.processor;
import javax.annotation.Nonnull;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.T... |
Fix typo in the script | #!/usr/bin/python
# vim : set fileencoding=utf-8 :
#
# mergeSegToCtm.py
#
# Enhance the CTM file by adding extra fields with the diarisation
# information
#
# First argument is the seg file
# Second argument is the ctm file
#
import sys
with open(sys.argv[1], 'r', encoding='iso-8859-1') as seg:
with open(sys.arg... | #!/usr/bin/python
# vim : set fileencoding=utf-8 :
#
# mergeSegToCtm.py
#
# Enhance the Bck file by adding extra fields with the diarisation
# information
#
import sys
with open(sys.argv[1], 'r', encoding='iso-8859-1') as seg:
with open(sys.argv[2], 'r', encoding='iso-8859-1') as ctm:
# For each frame, ... |
Use the Github API repo sorting.
The Github API can sort by pushed time, no need to do it manually.
http://developer.github.com/v3/repos/#list-user-repositories
This is both more efficient, Github does the sorting, but it also
fixes a bug. Because the list of results are paginated, if you have
more than a page's wor... | var github = (function(){
function escapeHtml(str) {
return $('<div/>').text(str).html();
}
function render(target, repos){
var i = 0, fragment = '', t = $(target)[0];
for(i = 0; i < repos.length; i++) {
fragment += '<li><a href="'+repos[i].html_url+'">'+repos[i].name+'</a><p>'+escapeHtml(repos... | var github = (function(){
function escapeHtml(str) {
return $('<div/>').text(str).html();
}
function render(target, repos){
var i = 0, fragment = '', t = $(target)[0];
for(i = 0; i < repos.length; i++) {
fragment += '<li><a href="'+repos[i].html_url+'">'+repos[i].name+'</a><p>'+escapeHtml(repos... |
Change the logout form the verb GET to the verb POST (and only)
Signed-off-by: Henrique Vicente <d390f26e2f50ad5716a9c69c58de1f5df9730e3b@gmail.com> | /*global angular */
(function () {
'use strict';
angular.module('auth', ['Facebook', 'config'])
.config(['FacebookProvider', 'config', function (FacebookProvider, config) {
FacebookProvider.init(config.facebook.id);
}])
.factory('userService', function ($http, $window, $roo... | /*global angular */
(function () {
'use strict';
angular.module('auth', ['Facebook', 'config'])
.config(['FacebookProvider', 'config', function (FacebookProvider, config) {
FacebookProvider.init(config.facebook.id);
}])
.factory('userService', function ($http, $window, $roo... |
DEV: Add long description for upload. | from __future__ import print_function
from setuptools import setup
from os.path import join, dirname, abspath
import sys
long_description = ''
if 'upload' in sys.argv or '--long-description' in sys.argv:
with open('README.rst') as f:
long_description = f.read()
def main():
reqs_file = join(dirname(... | from __future__ import print_function
from setuptools import setup
from os.path import join, dirname, abspath
def main():
reqs_file = join(dirname(abspath(__file__)), 'requirements.txt')
with open(reqs_file) as f:
requirements = [req.strip() for req in f.readlines()]
setup(
name='pgconten... |
Fix event listener test after propagation change | <?php
/*
* Copyright (c)
* Kirill chEbba Chebunin <iam@chebba.org>
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*/
namespace Che\EventBand\Tests;
use Che\EventBand\PublishEventListener;
use PHPUnit_Framework_TestCase as TestCase;
use Symfony\Compone... | <?php
/*
* Copyright (c)
* Kirill chEbba Chebunin <iam@chebba.org>
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*/
namespace Che\EventBand\Tests;
use Che\EventBand\PublishEventListener;
use PHPUnit_Framework_TestCase as TestCase;
use Symfony\Compone... |
Remove my dumb logging statement | import React from 'react';
import ReactDom from 'react-dom';
import { Link } from 'react-router';
import _ from 'lodash';
import client from '../../common/store/Contentful';
import marked from 'marked';
import styles from "./style.css";
export default class HomePage extends React.Component {
constructor(props) {
... | import React from 'react';
import ReactDom from 'react-dom';
import { Link } from 'react-router';
import _ from 'lodash';
import client from '../../common/store/Contentful';
import marked from 'marked';
import styles from "./style.css";
export default class HomePage extends React.Component {
constructor(props) {
... |
Support for paginator adaptor < zf 2.4 | <?php
/**
* @author Vanvelthem Sébastien
*/
namespace Soluble\FlexStore\Helper;
use Soluble\FlexStore\Exception;
use Zend\Paginator\Paginator as ZendPaginator;
class Paginator extends ZendPaginator
{
/**
*
* @param integer $totalRows
* @param integer $limit
* @param integer $offset
*... | <?php
/**
* @author Vanvelthem Sébastien
*/
namespace Soluble\FlexStore\Helper;
use Soluble\FlexStore\Exception;
use Zend\Paginator\Paginator as ZendPaginator;
class Paginator extends ZendPaginator
{
/**
*
* @param integer $totalRows
* @param integer $limit
* @param integer $offset
... |
Update tests: replace fs with util | var utilPath = require('../../../lib/file/path');
var getRealPkgSrc = require('../../../lib/file/get-real-pkg-src');
var expect = require('expect');
var runtimePath = require('../../util').runtimePath;
describe('Get real paths of the package\'s files', function () {
var optG = {src: runtimePath};
function T(pkg... | var utilPath = require('../../../lib/file/path');
var getRealPkgSrc = require('../../../lib/file/get-real-pkg-src');
var expect = require('expect');
var fs = require('fs');
describe('Get real paths of the package\'s files', function () {
var optG = {src: './runtime'};
var root = fs.realpathSync(optG.src) + '/';
... |
Remove comments that don't make sense | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo... | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo... |
Update pycodestyle requirement from <2.4.0,>=2.3.0 to >=2.3.0,<2.6.0
Updates the requirements on [pycodestyle](https://github.com/PyCQA/pycodestyle) to permit the latest version.
- [Release notes](https://github.com/PyCQA/pycodestyle/releases)
- [Changelog](https://github.com/PyCQA/pycodestyle/blob/master/CHANGES.txt)... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.1",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.1",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... |
Implement creating an import record each time a customer imports data | <?php
namespace vr\core\disposable;
use Yii;
use yii\base\BaseObject;
/**
* Class FileBeingUploaded
* @package vr\core\disposable
* @property string filename
*/
class FileBeingUploaded extends BaseObject implements IDisposable
{
/**
* @var
*/
private $_filename;
/**
* @var
*/
... | <?php
namespace vr\core\disposable;
use Yii;
use yii\base\BaseObject;
/**
* Class FileBeingUploaded
* @package vr\core\disposable
* @property string filename
*/
class FileBeingUploaded extends BaseObject implements IDisposable
{
/**
* @var
*/
private $_filename;
/**
* @var
*/
... |
Update Setup command to create the cache dir | <?php
namespace HeyDoc\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class SetupCommand extends Command
{
protected function configure()
{
$this
->setName('setup')... | <?php
namespace HeyDoc\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class SetupCommand extends Command
{
protected function configure()
{
$this
->setName('setup')... |
Remove 1.7.2 and add 1.11/1.12 | <?php
use Illuminate\Database\Seeder;
class MinecraftVersionsSeeder extends Seeder
{
private $versionsByType = [
'PC' => [
5 => '1.7.10',
47 => '1.8',
107 => '1.9',
210 => '1.10',
315 => '1.11',
335 => '1.12',
],
'P... | <?php
use Illuminate\Database\Seeder;
class MinecraftVersionsSeeder extends Seeder
{
private $versionsByType = [
'PC' => [
4 => '1.7.2',
5 => '1.7.10',
47 => '1.8',
107 => '1.9',
210 => '1.10',
],
'PE' => [
]
];
... |
Fix so the Subscribe button sends the right podcast ID | $(function() {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does... | $(function() {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does... |
Replace breadcrumb data-vocabulary.org microdata with schema.org | <?php
$navItems = $controller->getNavItems(true);
?>
<?php if (count($navItems) > 1): ?>
<nav aria-label="breadcrumb">
<ol class="breadcrumb" itemscope itemtype="http://schema.org/BreadcrumbList">
<?php foreach ($navItems as $i => $ni): ?>
<?php if (!$ni->isCurrent): ?>
... | <?php
$navItems = $controller->getNavItems(true);
?>
<?php if (count($navItems) > 1): ?>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<?php foreach ($navItems as $ni): ?>
<?php if (!$ni->isCurrent): ?>
<li class="breadcrumb-item" itemscope itemtype="... |
Add extension to DI configuration | <?php
namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link h... | <?php
namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link h... |
Update to not use newer ES6 function so we can support Node 0.12 | // modules
var assert = require('assert')
var _ = require('underscore')
var fs = require('fs');
var S = require('string');
var passmarked = require('passmarked');
var pluginFunc = require('../lib/rules/lint/prettify');
describe('lint', function(){
describe('#prettify', function... | // modules
var assert = require('assert')
var _ = require('underscore')
var fs = require('fs');
var S = require('string');
var passmarked = require('passmarked');
var pluginFunc = require('../lib/rules/lint/prettify');
describe('lint', function(){
describe('#prettify', function... |
Refactor to follow style guidelines | import Ember from 'ember';
import ModalMixin from '../mixins/sl-modal';
/**
* @module components
* @class sl-simple-modal
*/
export default Ember.Component.extend( ModalMixin, {
// -------------------------------------------------------------------------
// Dependencies
// ---------------------------... | import Ember from 'ember';
import ModalMixin from '../mixins/sl-modal';
/**
* @module components
* @class sl-simple-modal
*/
export default Ember.Component.extend( ModalMixin, {
// -------------------------------------------------------------------------
// Dependencies
// ---------------------------... |
Fix a bug when providing messages for validation rules in Factory class | <?php namespace App\Components\Validation\Sirius;
use App\Components\Validation\FactoryInterface;
use Sirius\Validation\Validator;
/**
* A Sirius Validator factory
*
* @author Benjamin Ulmer
* @link http://github.com/remluben/slim-boilerplate
*/
class SiriusValidatorFactory implements FactoryInterface
{
/**... | <?php namespace App\Components\Validation\Sirius;
use App\Components\Validation\FactoryInterface;
use Sirius\Validation\Validator;
/**
* A Sirius Validator factory
*
* @author Benjamin Ulmer
* @link http://github.com/remluben/slim-boilerplate
*/
class SiriusValidatorFactory implements FactoryInterface
{
/**... |
Update for janeway's monkey patch. | from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the jo... | from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the jo... |
Add a redirect on successful update of settings. |
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_unicode
from mezzanine.settings.models import Setting
from mezzanine.settings.forms import Setting... |
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_unicode
from mezzanine.settings.models import Setting
from mezzanine.settings.forms import Setting... |
Allow images in EXTRACTs, etc. | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive ... | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive ... |
Add cors headers to dev server responses | const path = require('path');
module.exports = {
entry: [
path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'),
path.resolve(process.cwd(), 'src/theme/assets/main.js')
],
output: {
publicPath: 'http://localhost:8080/_assets/',
filename: '[name].js',
chunk... | const path = require('path');
module.exports = {
entry: [
path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'),
path.resolve(process.cwd(), 'src/theme/assets/main.js')
],
output: {
publicPath: 'http://localhost:8080/_assets/',
filename: '[name].js',
chunk... |
Correct config for console environment | <?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstr... | <?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstr... |
fix: Correct padding on array aggregations
This was incorrectly building padding based on a single row. | import re
from sqlalchemy.sql import func
from sqlalchemy.types import String, TypeDecorator
# https://bitbucket.org/zzzeek/sqlalchemy/issues/3729/using-array_agg-around-row-function-does
class ArrayOfRecord(TypeDecorator):
_array_regexp = re.compile(r"^\{(\".+?\")*\}$")
_chunk_regexp = re.compile(r'"(.*?)"... | import re
from sqlalchemy.sql import func
from sqlalchemy.types import String, TypeDecorator
# https://bitbucket.org/zzzeek/sqlalchemy/issues/3729/using-array_agg-around-row-function-does
class ArrayOfRecord(TypeDecorator):
_array_regexp = re.compile(r"^\{(\".+?\")*\}$")
_chunk_regexp = re.compile(r'"(.*?)"... |
Change redux dev tool to redux dev tool extension | // Redux
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
// import createLogger from 'redux-logger';
// import Immutable from 'immutable';
import rootReducer from '../reducers';
// const __DEV__ = process.env.NODE_ENV === 'production' ? false : true;
const finalCreateSto... | // Redux
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import Immutable from 'immutable';
import rootReducer from '../reducers';
const __DEV__ = process.env.NODE_ENV === 'production' ? false : true;
const finalCreateStore = comp... |
Add period after middle name of users. | <br>
<br>
<div class="row">
<?php foreach ($query as $row): { ?>
<div class="col-lg-5">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object dp img-circle" src="http://placehold.it/700x400" style="width: 100px;height:100px;">
</a>
... | <br>
<br>
<div class="row">
<?php foreach ($query as $row): { ?>
<div class="col-lg-5">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object dp img-circle" src="http://placehold.it/700x400" style="width: 100px;height:100px;">
</a>
... |
Fix bug, set notify_email to always after create portal user | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... |
Disable the effects in the config by default | package com.hea3ven.twintails.conf;
import java.io.File;
import java.util.List;
import com.hea3ven.twintails.TwinTailsMod;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.even... | package com.hea3ven.twintails.conf;
import java.io.File;
import java.util.List;
import com.hea3ven.twintails.TwinTailsMod;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.even... |
Return empty dict if not defined rather than error | import json
import os
import sys
from server_common.ioc_data_source import IocDataSource
from server_common.mysql_abstraction_layer import SQLAbstraction
from server_common.utilities import print_and_log, SEVERITY
def register_ioc_start(ioc_name, pv_database=None, prefix=None):
"""
A helper function to regis... | import json
import os
import sys
from server_common.ioc_data_source import IocDataSource
from server_common.mysql_abstraction_layer import SQLAbstraction
from server_common.utilities import print_and_log, SEVERITY
def register_ioc_start(ioc_name, pv_database=None, prefix=None):
"""
A helper function to regis... |
Convert plugin to use Symfony events | <?php
namespace Grav\Plugin;
use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Uri;
use Grav\Common\Taxonomy;
class RandomPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents() {
return [
'onAfterInitPlugins' => ['onAfte... | <?php
namespace Grav\Plugin;
use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Registry;
use Grav\Common\Uri;
use Grav\Common\Taxonomy;
class RandomPlugin extends Plugin
{
/**
* @var bool
*/
protected $active = false;
/**
* @var Uri
*/
protected $uri;
/... |
Fix site title h1 only for frontpage | <?php
/**
* Site branding & logo
*
* @package air-light
*/
namespace Air_Light;
?>
<div class="site-branding">
<?php if ( is_front_page() ) : ?>
<h1 class="site-title">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<span class="screen-reader-text"><... | <?php
/**
* Site branding & logo
*
* @package air-light
*/
namespace Air_Light;
?>
<div class="site-branding">
<?php if ( is_front_page() && is_home() ) : ?>
<h1 class="site-title">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<span class="screen-r... |
Update ViewConfig generator test to follow new ComponentSchema
Summary:
NOTE: Flow and Jest won't pass on this diff. Sandcastle, should, however, be green on D24236405 (i.e: the tip of this stack).
Changelog: [Internal]
(Note: this ignores all push blocking failures!)
Reviewed By: PeteTheHeat
Differential Revision... | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+react_native
* @flow strict-local
* @format
*/
'use strict';
const fixtures = require('../__test_fixtures__/f... | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+react_native
* @flow strict-local
* @format
*/
'use strict';
const fixtures = require('../__test_fixtures__/f... |
Change unused 'let' to 'const' | export const updateElementInWorkspace = (workspace, payload) => {
const { selectionState } = workspace
if(!selectionState.dragStarted) {
return workspace
}
const { currentMousePosition } = payload
const {
elementId,
startElementPosition,
startMousePosition
} = selectionState
const elemen... | export const updateElementInWorkspace = (workspace, payload) => {
const { selectionState } = workspace
if(!selectionState.dragStarted) {
return workspace
}
const { currentMousePosition } = payload
const {
elementId,
startElementPosition,
startMousePosition
} = selectionState
const elemen... |
Fix encoding of email content | # -*- encoding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from django.conf import settings
def send_text(sender, receiver, subject, body):
msg = MIMEText(body, _charset='utf-8')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
msg["Accept-Language"] = "zh-CN"... | # -*- encoding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from django.conf import settings
def send_text(sender, receiver, subject, body):
msg = MIMEText(body, _charset='utf-8')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
msg["Accept-Language"] = "zh-CN"... |
Fix wordon filtering when calculating the value | class Letter(object):
_values = {
'#': 0, # Wildcard
'ENIOA': 1,
'SDTR': 2,
'MLKPBG': 3,
'ZVUFJH': 4,
'CW': 5,
'XY': 8,
'Q': 10
}
def __init__(self, letter):
self.letter = letter[-1]
self.wordon = letter[0] == '!'
self... | class Letter(object):
_values = {
'#': 0, # Wildcard
'ENIOA': 1,
'SDTR': 2,
'MLKPBG': 3,
'ZVUFJH': 4,
'CW': 5,
'XY': 8,
'Q': 10
}
def __init__(self, letter):
self.letter = letter[-1]
self.wordon = letter[0] == '!'
self... |
Increase timeout for the sake of iPhone tests. | var windowTest = require('./windowTest');
var elmTest = require('./elmTest');
var locationTest = require('./locationTest');
var storageTest = require('./storageTest');
module.exports = function (browser) {
var title =
browser.desiredCapabilities.browserName + "-" +
browser.desiredCapabilities.versi... | var windowTest = require('./windowTest');
var elmTest = require('./elmTest');
var locationTest = require('./locationTest');
var storageTest = require('./storageTest');
module.exports = function (browser) {
var title =
browser.desiredCapabilities.browserName + "-" +
browser.desiredCapabilities.versi... |
Add size constraint to molecularProfileIds in molecular data endpoint | package org.cbioportal.web.parameter;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Size;
import java.util.List;
import java.io.Serializable;
public class MolecularDataMultipleStudyFilter implements Serializable {
@Size(min = 1, max = PagingConstants.MAX_PAGE_SIZE)
priva... | package org.cbioportal.web.parameter;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Size;
import java.util.List;
import java.io.Serializable;
public class MolecularDataMultipleStudyFilter implements Serializable {
@Size(min = 1, max = PagingConstants.MAX_PAGE_SIZE)
priva... |
Add missing facebook and google verif codes | """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for ... | """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for ... |
Add span content as content attribute
This allows styles to use it in CSS `.foo[content*=bar]` selectors. | "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "... | "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "... |
Make admin configuration files overridable. | <?php
namespace Darvin\BotDetectorBundle\DependencyInjection;
use Darvin\BotDetectorBundle\Entity\DetectedBot;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Compon... | <?php
namespace Darvin\BotDetectorBundle\DependencyInjection;
use Darvin\BotDetectorBundle\Entity\DetectedBot;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Compon... |
Use StringBuilder instead of StringBuffer. | /*
* Copyright 2007 Open Source Applications Foundation
*
* 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 a... | /*
* Copyright 2007 Open Source Applications Foundation
*
* 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 a... |
Fix regexp for theme changes | /*******************************
Default Paths
*******************************/
module.exports = {
base : '',
theme : './src/theme.config',
docs : {
source : '../docs/server/files/release/',
output : '../docs/release/'
},
// files cleaned after install
setupFiles: [
'./src/theme.... | /*******************************
Default Paths
*******************************/
module.exports = {
base : '',
theme : './src/theme.config',
docs : {
source : '../docs/server/files/release/',
output : '../docs/release/'
},
// files cleaned after install
setupFiles: [
'./src/theme.... |
Use ls instead of test
Older versions of Android do not ship with test, and so pulling
screenshots always fails. This changes the method for testing
the existence of metadata.xml to use ls instead, which is
available on all Android versions. | #!/usr/bin/env python
#
# Copyright (c) 2014-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#... | #!/usr/bin/env python
#
# Copyright (c) 2014-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#... |
Remove declaration of dependency on simplejson | #!/usr/bin/env python
from distutils.core import setup
def readfile(fname):
with open(fname) as f:
content = f.read()
return content
setup(name='sockjs-cyclone',
version='1.0.2',
author='Flavio Grossi',
author_email='flaviogrossi@gmail.com',
description='SockJS python server... | #!/usr/bin/env python
from distutils.core import setup
def readfile(fname):
with open(fname) as f:
content = f.read()
return content
setup(name='sockjs-cyclone',
version='1.0.2',
author='Flavio Grossi',
author_email='flaviogrossi@gmail.com',
description='SockJS python server... |
Correct UK and EU Widgets.js URLs | <?php
// Be sure your webserver is configured to never display the contents of this file under any circumstances.
// The secret_key value below should be protected and never shared with anyone.
$amazonpay_config = array(
'merchant_id' => '', // Merchant/SellerID
'access_key' => '', //... | <?php
// Be sure your webserver is configured to never display the contents of this file under any circumstances.
// The secret_key value below should be protected and never shared with anyone.
$amazonpay_config = array(
'merchant_id' => '', // Merchant/SellerID
'access_key' => '', //... |
Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer. | """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" o... | """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" o... |
Fix way of declare method in a object. | const InventoryError = require('../../errors').InventoryError
const models = require('./')
const Payment = models.payments
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('pokemons', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, {
class... | const InventoryError = require('../../errors').InventoryError
const models = require('./')
const Payment = models.payments
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('pokemons', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, {
class... |
Replace @ with , otherwise there is blank output from ansible-lint | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provi... | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provi... |
Remove int typehint.
Maybe passing parameter like ‘123’… | <?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <i@overtrue.me>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EasyWeChat\Applications\WeWork\Department;
use EasyWeChat\Kernel\BaseClient;
/**
* This is WeWork... | <?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <i@overtrue.me>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EasyWeChat\Applications\WeWork\Department;
use EasyWeChat\Kernel\BaseClient;
/**
* This is WeWork... |
Add log message if data we can't parse appears
If the datum isn't numeric and doesn't match the 'no data' pattern,
something has gone horribly wrong. | # -*- coding: utf-8 -*-
import string
def sanitise_string(messy_str):
"""Whitelist characters in a string"""
valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
return u''.join(char for char in messy_str if char in valid_chars).strip()
class Service(object):
def __init__(self, numeri... | # -*- coding: utf-8 -*-
import string
def sanitise_string(messy_str):
"""Whitelist characters in a string"""
valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
return u''.join(char for char in messy_str if char in valid_chars).strip()
class Service(object):
def __init__(self, numeri... |
Move to more appropriate place | <?php
namespace GnuCash\Models\Tests;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit_Framework_TestCase;
abstract class EloquentTestCase extends PHPUnit_Framework_TestCase
{
protected $connection = 'gnucash_... | <?php
namespace GnuCash\Models\Tests;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit_Framework_TestCase;
abstract class EloquentTestCase extends PHPUnit_Framework_TestCase
{
protected $connection = 'gnucash_... |
Set some default connection information to maintain consistency for the dataCollector | <?php
namespace Leezy\PheanstalkBundle;
use Pheanstalk_Pheanstalk;
class ConnectionLocator
{
private $connections;
private $info;
private $default;
public function __construct()
{
$this->connections = array();
}
/**
* @return array
*/
public function getCon... | <?php
namespace Leezy\PheanstalkBundle;
use Pheanstalk_Pheanstalk;
class ConnectionLocator
{
private $connections;
private $info;
private $default;
public function __construct()
{
$this->connections = array();
}
/**
* @return array
*/
public function getCon... |
Add validation event handling for grid binders | define(['override', 'jquery',], function(override, $) {
"use strict";
return function(grid, pluginOptions) {
override(grid, function($super) {
return {
init: function init() {
$super.init.apply(this, arguments);
this.container.on("mous... | define(['override', 'jquery',], function(override, $) {
"use strict";
return function(grid, pluginOptions) {
override(grid, function($super) {
return {
init: function init() {
$super.init.apply(this, arguments);
this.container.on("mous... |
Add .apply() to inventory loading to refresh ng-repeat | myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
inventoryService.loadInventories()
.then(function(inventories) {
console.log("Loaded stored inventories: ", inventories);
$scope.inventories = inventories;
$scop... | myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
inventoryService.loadInventories()
.then(function(inventories) {
console.log("Loaded stored inventories: ", inventories);
$scope.inventories = inventories;
});
$... |
Bump version for UDF/blob support | from setuptools import setup
### Add find_packages function, see
# https://wiki.python.org/moin/Distutils/Cookbook/AutoPackageDiscovery
import os
def is_package(path):
return (
os.path.isdir(path) and
os.path.isfile(os.path.join(path, '__init__.py'))
)
def find_packages(path=".", base="",... | from setuptools import setup
### Add find_packages function, see
# https://wiki.python.org/moin/Distutils/Cookbook/AutoPackageDiscovery
import os
def is_package(path):
return (
os.path.isdir(path) and
os.path.isfile(os.path.join(path, '__init__.py'))
)
def find_packages(path=".", base="",... |
Allow one last call to process before stopping | import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
self.is_stopping = False
def run(self):
while True:
got_task = Fals... | import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
def run(self):
while True:
got_task = False
data = None
... |
Fix Client crash on server | package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMes... | package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMes... |
Add default to max_places in proposal form | # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
clas... | # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
clas... |
Make query pass and change structure of results | <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Organisms with given ids
*/
class Organisms extends \WebService {
/**
* @param $querydata[ids] array of organism ids
* @returns array of organisms
*/
public function execute($querydata) {
global $db;
... | <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Organisms with given ids
*/
class Organisms extends \WebService {
/**
* @param $querydata[ids] array of organism ids
* @returns array of organisms
*/
public function execute($querydata) {
global $db;
... |
Add a method to draw a screen space aligned (untextured) quad | package com.rabenauge.gl;
import android.opengl.GLU;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
/*
* A class for various static helper methods.
*/
public class Helper {
// Vertices and texture coordinates for rendering a bitmap in order LR, LL, UL, UR.
private s... | package com.rabenauge.gl;
import android.opengl.GLU;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
/*
* A class for various static helper methods.
*/
public class Helper {
// Vertices and texture coordinates for rendering a bitmap in order LR, LL, UL, UR.
private s... |
Add empty results to make Select2 happy | <?
include '../scat.php';
$term= $_REQUEST['term'];
$products= array();
if (!$term) {
die_jsonp([ 'error' => "Need to supply some search terms.",
'results' => [] ]);
}
$products= Model::factory('Product')
->select("product.*")
->select("department.name", "department_name")
... | <?
include '../scat.php';
$term= $_REQUEST['term'];
$products= array();
if (!$term) {
die_jsonp("Need to supply some search terms.");
}
$products= Model::factory('Product')
->select("product.*")
->select("department.name", "department_name")
->select("department.slug", "depa... |
Move signal ignore to run | from multiprocessing import Process, Value
import os
import config
import servo
import signal
class ServoProcess(Process):
def __init__(self):
print '----> Checking servo driver...'
if not os.path.exists('/dev/servoblaster'):
raise Exception('Servo driver was not found. Is servoblaster ... | from multiprocessing import Process, Value
import os
import config
import servo
import signal
class ServoProcess(Process):
def __init__(self):
signal.signal(signal.SIGINT, signal.SIG_IGN)
print '----> Checking servo driver...'
if not os.path.exists('/dev/servoblaster'):
raise Ex... |
Make the list of period dynamic | /* global process */
'use strict';
function config() {
var periodFormat = '{0}-{1}';
var firstHandledYear = 2007;
var lastHandledPeriod = 2017;
var currentPeriod = periodFormat.replace('{0}', lastHandledPeriod).replace('{1}', lastHandledPeriod + 1);
var availablesPeriod = [];
for (var i = las... | /* global process */
'use strict';
function config() {
return {
port: process.env.PORT || 5000,
downloadImages: false,
paths: {
tableData: './data/{0}/{1}/table.json',
scorersData: './data/{0}/{1}/scorers.json',
assistsData: './data/{0}/{1}/assists.json',... |
Refactor send_message to remove completion block | from http_client import HttpClient
from models.message import ReceivedMessage
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message):
response, error = self.cli... | from http_client import HttpClient
from models.message import ReceivedMessage
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completio... |
Remove 1 sec timeout used in testing | <?php
namespace GitlabXMPPHook\XMPP;
use XMPPHP_XMPP as Xmpp;
use GitlabXMPPHook\Exception;
class XMPPClient
{
protected $connection;
public function __construct($scope)
{
if (is_null($scope->host) || is_null($scope->port) || is_null($scope->username) || is_null($scope->password))
... | <?php
namespace GitlabXMPPHook\XMPP;
use XMPPHP_XMPP as Xmpp;
use GitlabXMPPHook\Exception;
class XMPPClient
{
protected $connection;
public function __construct($scope)
{
if (is_null($scope->host) || is_null($scope->port) || is_null($scope->username) || is_null($scope->password))
... |
Add method to get the most appropriate DataView | from restlib2.resources import Resource
from avocado.models import DataContext, DataView
class BaseResource(Resource):
param_defaults = {}
def get_params(self, request):
params = request.GET.copy()
for param, default in self.param_defaults.items():
params.setdefault(param, default... | from restlib2.resources import Resource
from avocado.models import DataContext
class BaseResource(Resource):
param_defaults = {}
def get_params(self, request):
params = request.GET.copy()
for param, default in self.param_defaults.items():
params.setdefault(param, default)
... |
Return the order details URL from email body.
There is currently no Agile API method that will return the order
details for an activity so the URL from the email must be used in
conjunction with a web scraper to get the relevant details. | import requests
from base64 import urlsafe_b64decode
from credentials import label_id, url1, url2
from gmailauth import refresh
# access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:2d'}
r = requ... | import requests
from credentials import label_id
from gmailauth import refresh
access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:3d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users... |
Sort redis restore so that output is consistent | <?php
namespace PHPSW\Command\Redis;
use Knp\Command\Command,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface,
Symfony\Component\Finder\Finder;
class RestoreCommand extends Command
{
protected function configure()
{
$this->setName('redis:re... | <?php
namespace PHPSW\Command\Redis;
use Knp\Command\Command,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface,
Symfony\Component\Finder\Finder;
class RestoreCommand extends Command
{
protected function configure()
{
$this->setName('redis:re... |
Use LocationChoiceProvider in enikshay location view | from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import Choi... | from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.models import SQLLocation
from corehq.apps.userreports.reports.filters.choice_prov... |
Rename one test so it actually gets run. | import os
import morepath
from webtest import TestApp as Client
import pytest
from .fixtures import template
def setup_module(module):
morepath.disable_implicit()
def test_template_fixture():
config = morepath.setup()
config.scan(template)
config.commit()
c = Client(template.App())
response... | import os
import morepath
from webtest import TestApp as Client
import pytest
from .fixtures import template
def setup_module(module):
morepath.disable_implicit()
def test_template():
config = morepath.setup()
config.scan(template)
config.commit()
c = Client(template.App())
response = c.get... |
Use highlighted taxonomies instead of top level taxonomies | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Ro... | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Ro... |
Fix coverage to cover all files | module.exports = function (config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'],
files: [
// Angular libraries
'lib/angular.js',
'lib/angular-mocks.js',
// Application files
'js/app.js',
'js/services/*.js',... | module.exports = function (config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'],
files: [
// Angular libraries
'lib/angular.js',
'lib/angular-mocks.js',
// Application files
'js/app.js',
'js/services/*.js',... |
[Maintenance] Adjust variable names to interfaces | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\DependencyInjection;
use Symfony\Compon... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\DependencyInjection;
use Symfony\Compon... |
Fix the config to have names of managers | <?php
namespace Mcfedr\QueueManagerBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http:/... | <?php
namespace Mcfedr\QueueManagerBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http:/... |
Use old array syntax for Autocomplete | <?php
/* vim: set shiftwidth=2 expandtab softtabstop=2: */
namespace Boris;
class Autocompletion {
private $symbols = [];
public function __construct() {
}
public function complete($status)
{
$chunk = substr($status['line'], 0, $status['cursor']);
/**
* Verify if we ar... | <?php
/* vim: set shiftwidth=2 expandtab softtabstop=2: */
namespace Boris;
class Autocompletion {
private $symbols = [];
public function __construct() {
}
public function complete($status)
{
$chunk = substr($status['line'], 0, $status['cursor']);
/**
* Verify if we ar... |
Make goLayerVisibility a directive of type A | goog.provide('go_layervisibility_directive');
goog.require('go');
goog.require('goog.asserts');
/**
* Directive to control the visibility of a layer. To be used with
* a checkbox like element. Requires ngModel.
*
* Usage:
* <input type="checkbox" ng-model="layervisible" go-layer-visibility="layer">
*/
goModule... | goog.provide('go_layervisibility_directive');
goog.require('go');
goog.require('goog.asserts');
goModule.directive('goLayerVisibility', [
/**
* @return {angular.Directive} The directive specs.
*/
function() {
return {
restrict: 'E',
template: '<input type="checkbox" ng-model="l.visible"/>',... |
Use current host and port for communicating with websocket | 'use strict';
$(function() {
var conn;
var msg = $("#msg");
var log = $("#log");
var hostAndPort = location.hostname+(location.port ? ':'+location.port: '');
var webSocketAddr = "ws://" + hostAndPort + "/ws";
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop =... | 'use strict';
$(function() {
var conn;
var msg = $("#msg");
var log = $("#log");
var webSocketAddr = "ws://0.0.0.0:4001/ws"
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
... |
Make the drush command recognize the custom alias name. | <?php
namespace CommerceGuys\Platform\Cli\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DrushCommand extends PlatformCommand
{
protected function configure()
{
$this
->setName('drush')
->setDescription... | <?php
namespace CommerceGuys\Platform\Cli\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DrushCommand extends PlatformCommand
{
protected function configure()
{
$this
->setName('drush')
->setDescription... |
Change development status to Beta | from setuptools import setup
import io
import os
def read(fname, encoding='utf-8'):
here = os.path.dirname(__file__)
with io.open(os.path.join(here, fname), encoding=encoding) as f:
return f.read()
setup(
name='pretext',
version='0.0.3',
description='Use doctest with bytes, str & unicode... | from setuptools import setup
import io
import os
def read(fname, encoding='utf-8'):
here = os.path.dirname(__file__)
with io.open(os.path.join(here, fname), encoding=encoding) as f:
return f.read()
setup(
name='pretext',
version='0.0.3',
description='Use doctest with bytes, str & unicode... |
Fix RawPostDataException on request.body access.
Django's HttpRequest class doesn't like the `request.body` to be accessed more than one time. Upon the second attempt to read from `request.body`, Django throws a `RawPostDataException`. Since the previous code in this spot was conditional upon a `hasattr(request, 'bo... | from __future__ import absolute_import
from django.conf import settings
from raygun4py import raygunprovider
class Provider(object):
def __init__(self):
config = getattr(settings, 'RAYGUN4PY_CONFIG', {})
apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None))
self.se... | from __future__ import absolute_import
from django.conf import settings
from raygun4py import raygunprovider
class Provider(object):
def __init__(self):
config = getattr(settings, 'RAYGUN4PY_CONFIG', {})
apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None))
self.se... |
Fix event binding selector in unified mode | import {mapValues} from 'lodash';
import shallowEquals from 'shallow-equal/objects';
import arrayShallowEquals from 'shallow-equal/arrays';
// Simplified version of reselect
export const createSelector = (select, inputEquals = arrayShallowEquals) => {
let lastInput = null;
let lastResult = null;
return (.... | import {mapValues} from 'lodash';
import shallowEquals from 'shallow-equal/objects';
// Simplified version of reselect
const createSelector = (select, inputEquals) => {
let lastInput = null;
let lastResult = null;
return (...input) => {
if (!lastInput || !inputEquals(lastInput, input)) {
... |
Fix a bug where user-agents could specify their own session ID. | # encoding: utf-8
from __future__ import unicode_literals
from web.auth import authenticate, deauthenticate
from web.core import config, url, session
from web.core.http import HTTPFound
from brave.api.client import API
log = __import__('logging').getLogger(__name__)
class AuthenticationMixIn(object):
def aut... | # encoding: utf-8
from __future__ import unicode_literals
from web.auth import authenticate, deauthenticate
from web.core import config, url
from web.core.http import HTTPFound
from brave.api.client import API
log = __import__('logging').getLogger(__name__)
class AuthenticationMixIn(object):
def authorize(se... |
Use markdown as README format | #!/usr/bin/env python
import os
import setuptools
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setuptools.setup(
name='alerta',
version=read('VERSION'),
description='Alerta unified command-line tool and SDK',
long_description=read('README.md'),
... | #!/usr/bin/env python
import setuptools
with open('VERSION') as f:
version = f.read().strip()
with open('README.md') as f:
readme = f.read()
setuptools.setup(
name='alerta',
version=version,
description='Alerta unified command-line tool and SDK',
long_description=readme,
url='http://gith... |
Add date and time info | package com.arinerron.forux.core;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Logger {
public static int PRINT_TO_CONSOLE = 0;
public static int PRINT_TO_FILE = 1;
public static int PRINT_TO_CONSOLE_AND_FILE = 2;
private Game game = null;
private int type = Logg... | package com.arinerron.forux.core;
public class Logger {
public static int PRINT_TO_CONSOLE = 0;
public static int PRINT_TO_FILE = 1;
public static int PRINT_TO_CONSOLE_AND_FILE = 2;
private Game game = null;
private int type = Logger.PRINT_TO_CONSOLE_AND_FILE;
public Logger(Game game)... |
Add heredoc sql interpolation test | // SYNTAX TEST "Packages/php-grammar/PHP.tmLanguage"
<?php
$double_quotes = "SELECT * FROM tbl";
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'SELECT * FROM tbl';
// ^ source.sql keyword
// ... | // SYNTAX TEST "Packages/php-grammar/PHP.tmLanguage"
<?php
$double_quotes = "SELECT * FROM tbl";
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'SELECT * FROM tbl';
// ^ source.sql keyword
// ... |
Fix all specs failing due to strict types being enabled | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Addressing\Comparator;
use Sylius\Component\Addr... | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Addressing\Comparator;
use Sylius\Component\Addr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.