text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Make namespaces more clear in input_helpers.py
import importlib import warnings import distutils.version as dv def check_versions(minimum_versions): """Raises an ImportError if a dependent package is not installed and at the required version number, or provides a warning if the version of the dependent package cannot be found.""" for module_name i...
import importlib import warnings from distutils.version import LooseVersion def check_versions(minimum_versions): """Raises an ImportError if a dependent package is not installed and at the required version number, or provides a warning if the version of the dependent package cannot be found.""" for ...
Convert ValueError -> ValidationError in ValuesListField
import six from swimlane.exceptions import ValidationError from .base import MultiSelectField class ValuesListField(MultiSelectField): field_type = 'Core.Models.Fields.ValuesListField, Core' supported_types = six.string_types def __init__(self, *args, **kwargs): """Map names to IDs for use in f...
import six from .base import MultiSelectField class ValuesListField(MultiSelectField): field_type = 'Core.Models.Fields.ValuesListField, Core' supported_types = six.string_types def __init__(self, *args, **kwargs): """Map names to IDs for use in field rehydration""" super(ValuesListFiel...
Add 2nd parameter to create that's generated for requires that allows you to overwrite context.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ refines: 'foam.core.Requires', flags: ['swift'], requires: [ 'foam.swift.Argument', 'foam.swift.Method', ], properties: [ { name: 'swiftReturns', exp...
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ refines: 'foam.core.Requires', flags: ['swift'], requires: [ 'foam.swift.Argument', 'foam.swift.Method', ], properties: [ { name: 'swiftReturns', exp...
Fix unicode error on py2
# -*- coding: utf-8 -*- from __future__ import print_function import os import codecs import kombu from kombulogger import default_broker_url, default_queue_name class KombuLogServer(object): log_format = u'{host}\t{level}\t{message}' def __init__(self, url=None, queue=None): url = url or defaul...
# -*- coding: utf-8 -*- from __future__ import print_function import os import codecs import kombu from kombulogger import default_broker_url, default_queue_name class KombuLogServer(object): log_format = '{host}\t{level}\t{message}' def __init__(self, url=None, queue=None): url = url or default...
Remove deprecated parameter size in UploadedFile constructor call.
<?php namespace Vanio\DomainBundle\Model; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File as SymfonyFile; use Symfony\Component\HttpFoundation\File\UploadedFile; class FileToUpload extends UploadedFile { /** @var bool */ private $temporary = false; public funct...
<?php namespace Vanio\DomainBundle\Model; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File as SymfonyFile; use Symfony\Component\HttpFoundation\File\UploadedFile; class FileToUpload extends UploadedFile { /** @var bool */ private $temporary = false; public funct...
Hide progress bar when socket connection is lost
'use strict'; angular.module('sgApp') .controller('AppCtrl', function($scope, ngProgress) { // ngProgress do not respect styles assigned via CSS if we do not pass empty parameters // See: https://github.com/VictorBjelkholm/ngProgress/issues/33 ngProgress.height(''); ngProgress.color(''); ...
'use strict'; angular.module('sgApp') .controller('AppCtrl', function($scope, ngProgress) { // ngProgress do not respect styles assigned via CSS if we do not pass empty parameters // See: https://github.com/VictorBjelkholm/ngProgress/issues/33 ngProgress.height(''); ngProgress.color(''); ...
Refactor imports to be less verbose
import pytest try: from unittest import mock except ImportError: import mock from slackelot import SlackNotificationError, send_message def test_send_message_success(): """Returns True if response.status_code == 200""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'s...
import pytest import mock from slackelot.slackelot import SlackNotificationError, send_message def test_send_message_success(): """Returns True if response.status_code == 200""" with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response: webh...
CWAP-212: Fix documentation for the feature release toggle definitions document.
{ channels: { view: [ 'view-feature-release-toggle-definitions', 'view-config' ], add: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], replace: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], remove: [ 'remove-feature-release-toggle-definitions', 'remove-config' ] }, ty...
{ channels: { view: [ 'view-feature-release-toggle-definitions', 'view-config' ], add: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], replace: [ 'edit-feature-release-toggle-definitions', 'edit-config' ], remove: [ 'remove-feature-release-toggle-definitions', 'remove-config' ] }, ty...
Remove testing dir from interface doc generation. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1390 ead46cd0-7350-4e37-8683-fc4c6f79bf00
#!/usr/bin/env python """Script to auto-generate interface docs. """ # stdlib imports import os import sys #***************************************************************************** if __name__ == '__main__': nipypepath = os.path.abspath('..') sys.path.insert(1,nipypepath) # local imports from inte...
#!/usr/bin/env python """Script to auto-generate interface docs. """ # stdlib imports import os import sys #***************************************************************************** if __name__ == '__main__': nipypepath = os.path.abspath('..') sys.path.insert(1,nipypepath) # local imports from inte...
Add an example with a country lookup
'use strict'; var React = require('react'); var Table = require('./table.jsx'); var App = React.createClass({ render() { var countries = { 'de': 'Germany', 'fi': 'Finland', 'se': 'Sweden' }; var config = { columns: [ { ...
'use strict'; var React = require('react'); var Table = require('./table.jsx'); var App = React.createClass({ render() { var config = { columns: [ { property: 'name', editable: true, header: 'Name', }...
Remove some Python 2 syntax.
from django.template import loader from django.template.backends.django import Template as DjangoTemplate try: from django.template.backends.jinja2 import Template as Jinja2Template except ImportError: # Most likely Jinja2 isn't installed, in that case just create a class since # we always want it to be fal...
from django.template import loader from django.template.backends.django import Template as DjangoTemplate try: from django.template.backends.jinja2 import Template as Jinja2Template except ImportError: # Most likely Jinja2 isn't installed, in that case just create a class since # we always want it to be fal...
Add changelings to the character creation section
// Category View // ============= // Includes file dependencies define([ "jquery", "backbone", "text!../templates/character-create-view.html", "text!../templates/werewolf-create-view.html" ], function( $, Backbone, character_create_view_html , werewolf_create_view_html ) { // Extends Backbone.View v...
// Category View // ============= // Includes file dependencies define([ "jquery", "backbone", "text!../templates/character-create-view.html", "text!../templates/werewolf-create-view.html" ], function( $, Backbone, character_create_view_html , werewolf_create_view_html ) { // Extends Backbone.View v...
Drop existing products table before creation
# Create a database import sqlite3 import csv from datetime import datetime import sys reload(sys) sys.setdefaultencoding('utf8') class createDB(): def readCSV(self, filename): try: conn = sqlite3.connect('databaseForTest.db') print 'DB Creation Successful!' cur = ...
# Create a database import sqlite3 import csv from datetime import datetime import sys reload(sys) sys.setdefaultencoding('utf8') class createDB(): def readCSV(self, filename): try: conn = sqlite3.connect('databaseForTest.db') print 'DB Creation Successful!' cur = ...
Make dict updates more dense
# Import python libs import logging # Import salt libs import salt.utils log = logging.getLogger(__name__) def held(name): ''' Set package in 'hold' state, meaning it will not be upgraded. name The name of the package, e.g., 'tmux' ''' ret = {'name': name, 'changes': {}, 'result': False...
# Import python libs import logging # Import salt libs import salt.utils log = logging.getLogger(__name__) def held(name): ''' Set package in 'hold' state, meaning it will not be upgraded. name The name of the package, e.g., 'tmux' ''' ret = {'name': name} state = __salt__['pkg.get_...
Include the baseApp when running onAppend function
(function () { module.exports = function (onCreate, onAppend) { var baseApp; return { /** * Array of properties to be copied from main app to sub app */ merged: ['view engine', 'views'], /** * Array of properties to be co...
(function () { module.exports = function (onCreate, onAppend) { var baseApp; return { /** * Array of properties to be copied from main app to sub app */ merged: ['view engine', 'views'], /** * Array of properties to be co...
Fix loading the typeahead js in the search widget
<?php namespace Frontend\Modules\Search\Widgets; /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Core\Engine\Form as Fron...
<?php namespace Frontend\Modules\Search\Widgets; /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Core\Engine\Form as Fron...
Allow passing Celery configuration under the project's config
import os import logbook from .base import SubsystemBase _logger = logbook.Logger(__name__) class TasksSubsystem(SubsystemBase): NAME = 'tasks' def activate(self, flask_app): from ..celery.app import celery_app self._config = self.project.config.get('celery', {}) # ensure critica...
import os import logbook from .base import SubsystemBase _logger = logbook.Logger(__name__) class TasksSubsystem(SubsystemBase): NAME = 'tasks' def activate(self, flask_app): from ..celery.app import celery_app self._config = self.project.config.get('celery', {}) # ensure critica...
Allow keyless entry command to have no event.
package com.openxc.measurements; import java.util.Locale; import com.openxc.units.KeylessEntryCode; import com.openxc.units.State; public class KeylessEntryProgrammingCommand extends BaseMeasurement< State<KeylessEntryProgrammingCommand.Command>> { public final static String ID = "keyless_entry_command";...
package com.openxc.measurements; import java.util.Locale; import com.openxc.units.KeylessEntryCode; import com.openxc.units.State; public class KeylessEntryProgrammingCommand extends BaseMeasurement< State<KeylessEntryProgrammingCommand.Command>> { public final static String ID = "keyless_entry_command";...
Remove references to unused library
'use strict'; /*! around | https://github.com/tofumatt/around HTML5 Foursquare Client */ // Require.js shortcuts to our libraries. require.config({ paths: { async_storage: 'lib/async_storage', backbone: 'lib/backbone', brick: 'lib/brick', 'coffee-script': 'lib/coffee-script', ...
'use strict'; /*! around | https://github.com/tofumatt/around HTML5 Foursquare Client */ // Require.js shortcuts to our libraries. require.config({ paths: { async_storage: 'lib/async_storage', backbone: 'lib/backbone', brick: 'lib/brick', 'coffee-script': 'lib/coffee-script', ...
Fix cache dir in Kernel
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\Sec...
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\Sec...
Fix the line length in the updated tx rejection code.
<?php namespace DigiTickets\VerifoneWebService\Message\NonSessionBased; use DigiTickets\VerifoneWebService\Message\AbstractRemoteResponse; class PurchaseResponse extends AbstractRemoteResponse { const REJECTED_RESULTS = ['REFERRAL', 'DECLINED', 'COMMSDOWN']; private $tokenId; /** * Return the error...
<?php namespace DigiTickets\VerifoneWebService\Message\NonSessionBased; use DigiTickets\VerifoneWebService\Message\AbstractRemoteResponse; class PurchaseResponse extends AbstractRemoteResponse { const REJECTED_RESULTS = ['REFERRAL', 'DECLINED', 'COMMSDOWN']; private $tokenId; /** * Return the error...
Correct model reference in comments.
# encoding: utf-8 from django.views.generic import ListView from .viewmixins import OrderByMixin, PaginateMixin, SearchFormMixin class BaseListView(PaginateMixin, OrderByMixin, SearchFormMixin, ListView): """ Defines a base list view that supports pagination, ordering and basic search. Supports a fi...
# encoding: utf-8 from django.views.generic import ListView from .viewmixins import OrderByMixin, PaginateMixin, SearchFormMixin class BaseListView(PaginateMixin, OrderByMixin, SearchFormMixin, ListView): """ Defines a base list view that supports pagination, ordering and basic search. Supports a fi...
Create onLoginPressed function and add to render function
import React, { Component } from 'react'; import { StyleSheet, Text, View, TextInput, TouchableHighlight, } from 'react-native'; class Login extends Component{ constructor(){ super(); this.state = { name: "", username: "", password_digest: "", location: "", bio: "", ...
import React, { Component } from 'react'; import { StyleSheet, Text, View, TextInput, TouchableHighlight, } from 'react-native'; class Login extends Component{ constructor(){ super(); this.state = { name: "", username: "", password_digest: "", location: "", bio: "", ...
Stop sub totals being appended
(function () { 'use strict'; moj.Modules.SubTotal = { el: '.js-SubTotal', init: function () { _.bindAll(this, 'render', 'showSummary', 'calculate'); this.cacheEls(); this.bindEvents(); moj.log('init'); }, bindEvents: function () { this.$sets.on('keyup', 'input[type=n...
(function () { 'use strict'; moj.Modules.SubTotal = { el: '.js-SubTotal', init: function () { _.bindAll(this, 'render', 'showSummary', 'calculate'); this.cacheEls(); this.bindEvents(); moj.log('init'); }, bindEvents: function () { this.$sets.on('keyup', 'input[type=n...
[IMP] Add warehouse_id to existing onchange.
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ...
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ...
Make the array functions indicate if anything happened
<?php /* * This file is part of StyleCI. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace StyleCI\Config; /** * This is the array helper class. * * @author Graham Campbell <graham@a...
<?php /* * This file is part of StyleCI. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace StyleCI\Config; /** * This is the array helper class. * * @author Graham Campbell <graham@a...
Test for any RTI element on the POI model Previously RTI would be added, now it defaults to []
define(['moxie.conf', 'underscore', 'today/views/CardView', 'hbs!today/templates/rti'], function(conf, _, CardView, rtiTemplate) { var RTI_REFRESH = 60000; // 1 minute var RTICard = CardView.extend({ initialize: function() { this.model.on('change', this.render, this); }, ...
define(['moxie.conf', 'underscore', 'today/views/CardView', 'hbs!today/templates/rti'], function(conf, _, CardView, rtiTemplate) { var RTI_REFRESH = 60000; // 1 minute var RTICard = CardView.extend({ initialize: function() { this.model.on('change', this.render, this); }, ...
Add console email read function
<?php namespace RoyallTheFourth\QuickList\Common; use Respect\Validation\Validator; use Symfony\Component\Yaml\Yaml; function iterableToArray(iterable $iter): array { $out = []; foreach ($iter as $el) { $out[] = $el; } return $out; } function config(): array { return Yaml::parse(file_ge...
<?php namespace RoyallTheFourth\QuickList\Common; use Symfony\Component\Yaml\Yaml; function iterableToArray(iterable $iter): array { $out = []; foreach ($iter as $el) { $out[] = $el; } return $out; } function config(): array { return Yaml::parse(file_get_contents(__DIR__ . '/../config/c...
Load the analytics and mongoose only in the production mode.
"use strict"; const isProduction = process.env.NODE_ENV === "production"; module.exports = { metadata: { siteTitle: "Bloggify" , description: "We make publishing easy." , domain: isProduction ? "https://bloggify.org" : "http://localhost:8080" , twitter: "Bloggify" } , theme: { ...
"use strict"; const isProduction = process.env.NODE_ENV === "production"; module.exports = { metadata: { siteTitle: "Bloggify" , description: "We make publishing easy." , domain: isProduction ? "https://bloggify.org" : "http://localhost:8080" , twitter: "Bloggify" } , theme: { ...
Set default value for "versioned" to false.
<?php return [ /* |---------------------------------------------------------------- | Asset containers. |---------------------------------------------------------------- | | Asset containers to be loaded. | */ "containers" => array( "images" => [ "print_pattern" ...
<?php return [ /* |---------------------------------------------------------------- | Asset containers. |---------------------------------------------------------------- | | Asset containers to be loaded. | */ "containers" => array( "images" => [ "print_pattern" ...
Add stub for creating job definitions. Add back snapshot uploading prior to job submission
// dependencies ------------------------------------------------------------ import aws from '../libs/aws'; import scitran from '../libs/scitran'; // handlers ---------------------------------------------------------------- /** * Jobs * * Handlers for job actions. */ let handlers = { /** * Create J...
// dependencies ------------------------------------------------------------ import aws from '../libs/aws'; // handlers ---------------------------------------------------------------- /** * Jobs * * Handlers for job actions. */ let handlers = { /** * Describe Job Definitions */ describeJobDef...
[SimpleJobSchedule] Add base key to redis backed time keeper
<?php declare(strict_types=1); namespace Issei\SimpleJobSchedule\TimeKeeper; use Issei\SimpleJobSchedule\TimeKeeperInterface; use Predis\Client as Redis; /** * @author Issei Murasawa <issei.m7@gmail.com> */ class RedisTimeKeeper implements TimeKeeperInterface { /** * @var Redis */ private $redis...
<?php declare(strict_types=1); namespace Issei\SimpleJobSchedule\TimeKeeper; use Issei\SimpleJobSchedule\TimeKeeperInterface; use Predis\Client as Redis; /** * @author Issei Murasawa <issei.m7@gmail.com> */ class RedisTimeKeeper implements TimeKeeperInterface { /** * @var Redis */ private $redis...
Remove navigator user agent as it causes the app to break
'use strict'; import * as types from '../actions/actionTypes'; import config from '../config'; const initialState = { isFetching: true, question: '', latest: '' }; export default function main(state = initialState, action = {}) { switch (action.type) { case types.GET_LATEST: r...
'use strict'; import * as types from '../actions/actionTypes'; import config from '../config'; window.navigator.userAgent = "react-native"; const initialState = { isFetching: true, question: '', latest: '' }; export default function main(state = initialState, action = {}) { switch (action.type) { ...
Speed up showing favorite icons
function getFavoriteTeams() { var cookieName = "tba-favorite-teams"; var storedFavoriteTeams = $.cookie(cookieName); console.log(storedFavoriteTeams); if (storedFavoriteTeams == null) { // Set cookie expiration var date = new Date(); date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 minutes ...
function getFavoriteTeams() { var cookieName = "tba-favorite-teams"; var storedFavoriteTeams = $.cookie(cookieName); console.log(storedFavoriteTeams); if (storedFavoriteTeams == null) { // Set cookie expiration var date = new Date(); date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 minutes ...
Update namespaces for beta 8 Refs flarum/core#1235.
<?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\Auth\Facebook\Listener; use Flarum\Frontend\Event\Rendering; use Illuminate\Con...
<?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\Auth\Facebook\Listener; use Flarum\Event\ConfigureWebApp; use Illuminate\Contra...
Add tags and filters into the context
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.parser = parse.Parser(raw) self.nodelist = self.parser() code = ast.Expression( body=ast.GeneratorExp( elt=ast.Call( func=ast.Name(id='str'...
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.parser = parse.Parser(raw) self.nodelist = self.parser() code = ast.Expression( body=ast.GeneratorExp( elt=ast.Call( func=ast.Name(id='str'...
Exclude files in .travis folder from testExecutableFiles test
<?php namespace Concrete\Tests\File; use PHPUnit_Framework_TestCase; class ExecutableFilesTest extends PHPUnit_Framework_TestCase { public function testExecutableFiles() { if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Testing executable files requires a Posix environment'); ...
<?php namespace Concrete\Tests\File; use PHPUnit_Framework_TestCase; class ExecutableFilesTest extends PHPUnit_Framework_TestCase { public function testExecutableFiles() { if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Testing executable files requires a Posix environment'); ...
Remove "function()" from database-files. Why was it inserted in the first place?
var esformatter = require('esformatter'); var stringify = require("json-literal").stringify; var fs = require("fs"); var path = require("path"); /** * Class that writes an object to a file (using the `json-literal` module) * @param {*} `data` the javascript object, * @constructor */ function Writer(data) { var...
var esformatter = require('esformatter'); var stringify = require("json-literal").stringify; var fs = require("fs"); var path = require("path"); /** * Class that writes an object to a file (using the `json-literal` module) * @param {*} `data` the javascript object, * @constructor */ function Writer(data) { var...
Enable dark mode in Telescope
<?php namespace App\Providers; use Laravel\Telescope\Telescope; use Illuminate\Support\Facades\Gate; use Laravel\Telescope\IncomingEntry; use Laravel\Telescope\TelescopeApplicationServiceProvider; class TelescopeServiceProvider extends TelescopeApplicationServiceProvider { /** * Register any application ser...
<?php namespace App\Providers; use Laravel\Telescope\Telescope; use Illuminate\Support\Facades\Gate; use Laravel\Telescope\IncomingEntry; use Laravel\Telescope\TelescopeApplicationServiceProvider; class TelescopeServiceProvider extends TelescopeApplicationServiceProvider { /** * Register any application ser...
Add the futures lib backport as a dependency.
from setuptools import setup, find_packages from lighthouse import __version__ classifiers = [] with open("classifiers.txt") as fd: classifiers = fd.readlines() setup( name="lighthouse", version=__version__, description="Service discovery tool focused on ease-of-use and resiliency", author="Wil...
from setuptools import setup, find_packages from lighthouse import __version__ classifiers = [] with open("classifiers.txt") as fd: classifiers = fd.readlines() setup( name="lighthouse", version=__version__, description="Service discovery tool focused on ease-of-use and resiliency", author="Wil...
Fix wrong path in readme
from setuptools import setup version = "0.10.2" setup( name="setuptools-rust", version=version, author="Nikolay Kim", author_email="fafhrd91@gmail.com", url="https://github.com/PyO3/setuptools-rust", keywords="distutils setuptools rust", description="Setuptools rust extension plugin", ...
from setuptools import setup version = "0.10.2" setup( name="setuptools-rust", version=version, author="Nikolay Kim", author_email="fafhrd91@gmail.com", url="https://github.com/PyO3/setuptools-rust", keywords="distutils setuptools rust", description="Setuptools rust extension plugin", ...
Enable context provider for TraceErrorsMiddleware
import logging from paste.deploy.converters import asbool log = logging.getLogger(__name__) def _turbogears_backlash_context(environ): tgl = environ.get('tg.locals') return {'request':getattr(tgl, 'request', None)} def ErrorHandler(app, global_conf, **errorware): """ErrorHandler Toggle If debug ...
import logging from paste.deploy.converters import asbool log = logging.getLogger(__name__) def _turbogears_backlash_context(environ): tgl = environ.get('tg.locals') return {'request':getattr(tgl, 'request', None)} def ErrorHandler(app, global_conf, **errorware): """ErrorHandler Toggle If debug ...
Add state saving to Tally
package com.stevescodingblog.androidapps.tally; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.prefs.Preferen...
package com.stevescodingblog.androidapps.tally; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { int _tally = 1; @Override protected void onCreate(Bundle savedInstan...
Revert "set only forEach globally for Array.prototyp if not exists (ie8 fallback)" This reverts commit 6c9d18931103e20f5be97250352fc14fd678d990. Reason is that admin is broken with this commit (no menu is shown).
var _ = require('underscore'); _.extend(Array.prototype, { //deprecated! -> forEach (ist auch ein JS-Standard!) each: function(fn, scope) { _.each(this, fn, scope); }, //to use array.forEach directly forEach: function(fn, scope) { _.forEach(this, fn, scope); } }); if (typeof A...
var _ = require('underscore'); if (typeof Array.prototype.forEach != 'function') { Array.prototype.forEach = function (fn, scope) { _.forEach(this, fn, scope); }; } //source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { ...
Add log function for compatibility with Console API
'use strict'; var catchErrors = require('./lib/catchErrors'); var log = require('./lib/log'); var transportConsole = require('./lib/transports/console'); var transportFile = require('./lib/transports/file'); var transportRemote = require('./lib/transpo...
'use strict'; var catchErrors = require('./lib/catchErrors'); var log = require('./lib/log'); var transportConsole = require('./lib/transports/console'); var transportFile = require('./lib/transports/file'); var transportRemote = require('./lib/transpo...
Print http start to beginning
#!/usr/bin/env node 'use strict'; var config = require('./config'); var http = require('http'); var ip = require('ip'); var exec = require('child_process').exec; var createHandler = require('github-webhook-handler'); var handler = createHandler({ secret: config.SECRET, path: co...
#!/usr/bin/env node 'use strict'; var config = require('./config'); var http = require('http'); var ip = require('ip'); var exec = require('child_process').exec; var createHandler = require('github-webhook-handler'); var handler = createHandler({ secret: config.SECRET, path: co...
Remove commented out logged decorator
import urlparse import celery import requests from celery.utils.log import get_task_logger from django.conf import settings from framework.tasks import app as celery_app logger = get_task_logger(__name__) class VarnishTask(celery.Task): abstract = True max_retries = 5 def get_varnish_servers(): # TODO...
import urlparse import celery import requests from celery.utils.log import get_task_logger from django.conf import settings from framework.tasks import app as celery_app logger = get_task_logger(__name__) class VarnishTask(celery.Task): abstract = True max_retries = 5 def get_varnish_servers(): # TODO...
Use finally so connection is also closed on exception.
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.conf...
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.conf...
Add min task to release.
var exec = require('child_process').exec; module.exports = function(grunt) { grunt.initConfig({ qunit: ['./test/index.html'], lint: ['supermodel.js', './test/*.js'], min: { 'supermodel.min.js': 'supermodel.js' }, watch: { default: { files: ['supermodel.js', 'test/index.html',...
var exec = require('child_process').exec; module.exports = function(grunt) { grunt.initConfig({ qunit: ['./test/index.html'], lint: ['supermodel.js', './test/*.js'], watch: { default: { files: ['supermodel.js', 'test/index.html', 'test/**/*.js'], tasks: 'default' } }, ...
CRM-2906: Refresh attachment grid after click on attachment link on email
/*jslint nomen: true*/ /*global define*/ define([ 'jquery', 'underscore', 'orotranslation/js/translator', 'backbone', 'oroui/js/messenger', 'oroui/js/app/views/base/view', 'oroui/js/mediator' ], function ($, _, __, Backbone, messenger, BaseView, mediator) { 'use strict'; var EmailAt...
/*jslint nomen: true*/ /*global define*/ define([ 'jquery', 'underscore', 'orotranslation/js/translator', 'backbone', 'oroui/js/messenger', 'oroui/js/app/views/base/view' ], function ($, _, __, Backbone, messenger, BaseView) { 'use strict'; var EmailAttachmentLink; /** * @expo...
Convert currency name to currency iso code
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics...
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics...
Update view after updating template
<?php EngineBlock_ApplicationSingleton::getInstance()->flushLog('Showing feedback page with message: ' . $layout->title); ?> <div class="l-overflow"> <table class="comp-table"> <thead></thead> <tbody> <?php if (!empty($_SESSION['feedbackInfo']) && is_array($_SESSION['feedbackI...
<?php $log = EngineBlock_ApplicationSingleton::getInstance()->getLog(); $log->log('Showing feedback page with message: ' . $layout->title, EngineBlock_Log::INFO); $log->getQueueWriter()->flush('feedback page shown'); ?> <div class="l-overflow"> <table class="comp-table"> <thead></thead> <tbod...
Update filter. Review by @nicolaasdiebaas
from setuptools import setup, find_packages setup( name="seed-stage-based-messaging", version="0.1", url='http://github.com/praekelt/seed-stage-based-messaging', license='BSD', author='Praekelt Foundation', author_email='dev@praekeltfoundation.org', packages=find_packages(), include_pac...
from setuptools import setup, find_packages setup( name="seed-stage-based-messaging", version="0.1", url='http://github.com/praekelt/seed-stage-based-messaging', license='BSD', author='Praekelt Foundation', author_email='dev@praekeltfoundation.org', packages=find_packages(), include_pac...
Update redis commands toTree tests
'use strict'; var RedisCommands = require('../js/service/redis-commands'), should = require('should'); describe('RedisCommands', function () { // TODO: fix RedisCommands to fit these tests describe('To tree', function () { var redisCommands = new RedisCommands(); it('Should conv...
'use strict'; var RedisCommands = require('../js/service/redis-commands'), should = require('should'); describe('RedisCommands', function () { // TODO: fix RedisCommands to fit these tests describe('To tree', function () { var redisCommands = new RedisCommands(); it('Should conv...
Fix test failure in MPI
import hoomd import io import numpy def test_table_pressure(simulation_factory, two_particle_snapshot_factory): """Test that write.table can log MD pressure values.""" thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All()) snap = two_particle_snapshot_factory() if snap.communicator.rank...
import hoomd import io import numpy def test_table_pressure(simulation_factory, two_particle_snapshot_factory): """Test that write.table can log MD pressure values.""" thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All()) snap = two_particle_snapshot_factory() if snap.communicator.rank...
Fix 1010 upgrade step (setBatchID -> setBatch)
import logging from Acquisition import aq_base from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def addBatches(tool): """ """ portal = aq_parent(aq_inner(tool)) portal_catalog = getToolByName(portal, 'portal_catalog') setup = port...
import logging from Acquisition import aq_base from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def addBatches(tool): """ """ portal = aq_parent(aq_inner(tool)) portal_catalog = getToolByName(portal, 'portal_catalog') setup = port...
tools/scyllatop: Use 'erase' to clear the screen The 'clear' function explicitly clears the screen and repaints it which causes really annoying flicker. Use 'erase' to make scyllatop more pleasant on the eyes. Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com>
import time import curses import curses.panel import logging class Base(object): def __init__(self, window): lines, columns = window.getmaxyx() self._window = curses.newwin(lines, columns) self._panel = curses.panel.new_panel(self._window) def writeStatusLine(self, measurements): ...
import time import curses import curses.panel import logging class Base(object): def __init__(self, window): lines, columns = window.getmaxyx() self._window = curses.newwin(lines, columns) self._panel = curses.panel.new_panel(self._window) def writeStatusLine(self, measurements): ...
Update management command for various changes
from django.core.management.base import BaseCommand from django.db.models import Prefetch from mla_game.apps.transcript.tasks import update_transcript_stats from ...models import ( Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection, ) class Command(BaseCommand): help = '''Find all Transcripts with...
from django.core.management.base import BaseCommand from django.db.models import Prefetch from mla_game.apps.transcript.tasks import update_transcript_stats from ...models import ( Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection, ) class Command(BaseCommand): help = '''Find all Transcripts with...
Fix className var in initDefinition
var checkValidator = function( validator, fieldName, className ) { if (!Match.test( validator, Match.OneOf(Astro.FieldValidator, [Astro.FieldValidator]) )) { throw new TypeError( 'The validator for the "' + fieldName + '" field in the "' + className + '" class schema has to be a ' + ...
var checkValidator = function( validator, fieldName, className ) { if (!Match.test( validator, Match.OneOf(Astro.FieldValidator, [Astro.FieldValidator]) )) { throw new TypeError( 'The validator for the "' + fieldName + '" field in the "' + className + '" class schema has to be a ' + ...
Allow new user AJAX call to accept HTTP status code instead of manual code
angular.module('dataGoMain') .controller('WelcomeController', ['$scope', '$http', 'dataGoAPI', '$rootScope',function($scope, $http, dataGoAPI, $rootScope){ console.log('in HomeCtrl'); $scope.registerUser = registerUser; $scope.loginEmail = ''; $scope.loginPassword = ''; $scop...
angular.module('dataGoMain') .controller('WelcomeController', ['$scope', '$http', 'dataGoAPI', '$rootScope',function($scope, $http, dataGoAPI, $rootScope){ console.log('in HomeCtrl'); $scope.registerUser = registerUser; $scope.loginEmail = ''; $scope.loginPassword = ''; $scop...
Add a proper License PyPI classifier
import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a y...
import re from setuptools import setup with open('mashdown/__init__.py') as f: version = re.search( r'(?<=__version__ = \')\d\.\d\.\d(?=\')', f.read() ).group() with open('README.rst') as f: readme = f.read() setup( name=u'mashdown', version=version, description=u'Splits a y...
Add utility method to check between the two different publish message forms
package de.innoaccel.wamp.server.message; import java.util.List; public class PublishMessage implements Message { private String topicURI; private Object event; private boolean excludeMe; private List<String> exclude; private List<String> eligable; public PublishMessage(String topicURI, O...
package de.innoaccel.wamp.server.message; import java.util.List; public class PublishMessage implements Message { private String topicURI; private Object event; private boolean excludeMe; private List<String> exclude; private List<String> eligable; public PublishMessage(String topicURI, O...
Replace getPage() with getPageOrRoot() to make tests work again
<?php class Kwf_Component_View_Helper_ComponentWithMaster extends Kwf_Component_View_Helper_Component { public function componentWithMaster(array $componentWithMaster) { $last = array_pop($componentWithMaster); $component = $last['data']; if ($last['type'] == 'master') { $i...
<?php class Kwf_Component_View_Helper_ComponentWithMaster extends Kwf_Component_View_Helper_Component { public function componentWithMaster(array $componentWithMaster) { $last = array_pop($componentWithMaster); $component = $last['data']; if ($last['type'] == 'master') { $i...
Sort on imdb rating if filmtipset ratings are the same.
from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) ...
from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) ...
Update namespaces for beta 8 Refs flarum/core#1235.
<?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\Auth\Twitter\Listener; use Flarum\Frontend\Event\Rendering; use Illuminate\Cont...
<?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\Auth\Twitter\Listener; use Flarum\Event\ConfigureWebApp; use Illuminate\Contrac...
Allow Connection.send to take unicode message
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host...
import asyncio from .message import Message class Connection: """ Communicates with an IRC network. Incoming data is transformed into Message objects, and sent to `listeners`. """ def __init__(self, *, listeners, host, port, ssl=True): self.listeners = listeners self.host = host...
Fix in CPU requirement naming
/** * Author: Milica Kadic * Date: 2/3/15 * Time: 3:03 PM */ 'use strict'; angular.module('registryApp.cliche') .constant('rawJob', { inputs: {}, allocatedResources: { cpu: 0, mem: 0 } }) .constant('rawTool', { 'id': '', 'class': 'CommandL...
/** * Author: Milica Kadic * Date: 2/3/15 * Time: 3:03 PM */ 'use strict'; angular.module('registryApp.cliche') .constant('rawJob', { inputs: {}, allocatedResources: { cpu: 0, mem: 0 } }) .constant('rawTool', { 'id': '', 'class': 'CommandL...
Use interface TestListener instead of deprecated abstract class BaseTestListener
<?php namespace { use PHPUnit\Framework\TestListener; use PHPUnit\Framework\TestListenerDefaultImplementation; use PHPUnit\Framework\TestSuite; use Symfony\Component\Process\Process; final class PhpUnitStartServerListener implements TestListener { use TestListenerDefaultImplementation...
<?php namespace { use PHPUnit\Framework\BaseTestListener; use PHPUnit\Framework\TestSuite; use Symfony\Component\Process\Process; final class PhpUnitStartServerListener extends BaseTestListener { /** * @var string */ private $suiteName; /** * @v...
Fix bad reference to host node Also store the host as a instance property to avoid calling into Attribute every scroll
/*jshint browser:true, yui:true */ YUI.add("plugin-lazy-images", function(Y) { "use strict"; var plugins = Y.namespace("Plugins"), LazyImages; LazyImages = Y.Base.create("lazyImages", Y.Plugin.Base, [], { // Y.Base lifecycle fns initializer : function() { var ho...
/*jshint browser:true, yui:true */ YUI.add("plugin-lazy-images", function(Y) { "use strict"; var plugins = Y.namespace("Plugins"), LazyImages; LazyImages = Y.Base.create("lazyImages", Y.Plugin.Base, [], { // Y.Base lifecycle fns initializer : function() { var ho...
FIx bug when the dep names regexp doesn't have a match
(function (ng) { 'use strict'; /** * Angular.js utility for cleaner dependency injection. */ var $inject = function (cls, self, args) { var i; var key; var str; var func; var depNames = []; var deps = []; var l = cls.$inject.length; // Inject all dependencies into the self ...
(function (ng) { 'use strict'; /** * Angular.js utility for cleaner dependency injection. */ var $inject = function (cls, self, args) { var i; var key; var str; var func; var depNames = []; var deps = []; var l = cls.$inject.length; // Inject all dependencies into the self ...
Use the git status command for building the files-list
<?php namespace GrumPHP\Locator; use GitElephant\Repository; use GitElephant\Status\Status; use GitElephant\Status\StatusFile; /** * Class Git * * @package GrumPHP\Locator */ class ChangedFiles implements LocatorInterface { const PATTERN_ALL = '/(.*)/'; const PATTERN_PHP = '/(.*)\.php$/i'; /** ...
<?php namespace GrumPHP\Locator; use GitElephant\Objects\Diff\Diff; use GitElephant\Objects\Diff\DiffObject; use GitElephant\Repository; /** * Class Git * * @package GrumPHP\Locator */ class ChangedFiles implements LocatorInterface { const PATTERN_ALL = '/(.*)/'; const PATTERN_PHP = '/(.*)\.php$/i'; ...
Return the function again from the hook decorator The decorator variant of hook registration did not return anything, meaning that the decorated function would end up being `None`. This was not noticed, as the functions are rarely called manually, as opposed to being invoked via the hook.
from django.conf import settings try: from importlib import import_module except ImportError: # for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7) from django.utils.importlib import import_module _hooks = {} def register(hook_name, fn=None): """ Register hook for ``...
from django.conf import settings try: from importlib import import_module except ImportError: # for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7) from django.utils.importlib import import_module _hooks = {} def register(hook_name, fn=None): """ Register hook for ``...
Update LinkedIn PYMK script to work with new page Addresses https://greasyfork.org/en/forum/discussion/27748/missing-url
// ==UserScript== // @name LinkedIn hide email contacts from "People You May Know" // @namespace http://mathemaniac.org // @version 1.2.0 // @description Hides those annoying email contacts from PYMK // @match https://www.linkedin.com/mynetwork* // @copyright 2015-2017, Sebastian Paaske Tørholm // @req...
// ==UserScript== // @name LinkedIn hide email contacts from "People You May Know" // @namespace http://mathemaniac.org // @version 1.1.0 // @description Hides those annoying email contacts from PYMK // @match http://www.linkedin.com/people/pymk* // @match https://www.linkedin.com/people/pymk* // @...
Add classifier for Python 3.7.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="django-pgallery", version=__import__("pgallery").__version__, description="Photo gallery app for PostgreSQL and Django.", long_description=read("...
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="django-pgallery", version=__import__("pgallery").__version__, description="Photo gallery app for PostgreSQL and Django.", long_description=read("...
Add whitespace to trigger travis
from setuptools import setup, find_packages, Command version = __import__('eemeter').get_version() long_description = "Standard methods for calculating energy efficiency savings." class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass...
from setuptools import setup, find_packages, Command version = __import__('eemeter').get_version() long_description = "Standard methods for calculating energy efficiency savings." class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass...
Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@326640 91177308-0d34-0410-b5e6-96231b3b80d8
"""Test that the clang modules cache directory can be controlled.""" from __future__ import print_function import unittest2 import os import time import platform import shutil import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ObjCMo...
"""Test that the clang modules cache directory can be controlled.""" from __future__ import print_function import unittest2 import os import time import platform import shutil import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ObjCMo...
Fix issue with dropping a file into a log entry
/* * jQuery File Upload Plugin JS Example 5.0.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://creativecommons.org/licenses/MIT/ */ /*jslint nomen: false */ /*global $ */ $(function () { // Initializ...
/* * jQuery File Upload Plugin JS Example 5.0.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://creativecommons.org/licenses/MIT/ */ /*jslint nomen: false */ /*global $ */ $(function () { // Initializ...
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
# -*- coding: utf-8 -*- from django.test import Client from django.http import SimpleCookie from webtest import TestResponse from django_webtest.compat import urlparse class DjangoWebtestResponse(TestResponse): """ WebOb's Response quacking more like django's HttpResponse. This is here to make more django...
# -*- coding: utf-8 -*- from django.test import Client from django.http import SimpleCookie from webtest import TestResponse from django_webtest.compat import urlparse class DjangoWebtestResponse(TestResponse): """ WebOb's Response quacking more like django's HttpResponse. This is here to make more django...
Remove more obsolete code in v2
import sys from threading import local def debug():# pragma no cover def pm(etype, value, tb): import pdb, traceback try: from IPython.ipapi import make_session; make_session() from IPython.Debugger import Pdb sys.stderr.write('Entering post-mortem IPDB shell\n'...
import sys from threading import local def debug(): def pm(etype, value, tb): # pragma no cover import pdb, traceback try: from IPython.ipapi import make_session; make_session() from IPython.Debugger import Pdb sys.stderr.write('Entering post-mortem IPDB shell\n'...
Use stable ids for the RecyclerView adapter
package com.appyvet.rangebarsample; import android.app.Activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; impo...
package com.appyvet.rangebarsample; import android.app.Activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; impo...
Revert Promise to Ember.Promise change
import Ember from 'ember'; // global Promise export default Ember.Controller.extend({ possibleTypes: Ember.computed.map('model.type', m => m), assignedLots: Ember.computed.map('model.lots', m => m), candidateLots: Ember.computed('possibleTypes.@each.lots', { set(key, value) { return valu...
import Ember from 'ember'; export default Ember.Controller.extend({ possibleTypes: Ember.computed.map('model.type', m => m), assignedLots: Ember.computed.map('model.lots', m => m), candidateLots: Ember.computed('possibleTypes.@each.lots', { set(key, value) { return value; }, ...
Make inbetween tag releases 'dev', not 'post'.
#!/usr/bin/env python # Source: https://github.com/Changaco/version.py from os.path import dirname, isdir, join import re from subprocess import CalledProcessError, check_output PREFIX = '' tag_re = re.compile(r'\btag: %s([0-9][^,]*)\b' % PREFIX) version_re = re.compile('^Version: (.+)$', re.M) def get_version():...
#!/usr/bin/env python # Source: https://github.com/Changaco/version.py from os.path import dirname, isdir, join import re from subprocess import CalledProcessError, check_output PREFIX = '' tag_re = re.compile(r'\btag: %s([0-9][^,]*)\b' % PREFIX) version_re = re.compile('^Version: (.+)$', re.M) def get_version():...
Fix a bug where query strings would 404
/* Sets up a connect server to work from the /build folder. May also set up a livereload server at some point. */ var fs = require("fs"); var path = require("path"); var url = require("url"); module.exports = function(grunt) { grunt.loadNpmTasks("grunt-contrib-connect"); grunt.config.merge({ connect: { ...
/* Sets up a connect server to work from the /build folder. May also set up a livereload server at some point. */ var fs = require("fs"); var path = require("path"); module.exports = function(grunt) { grunt.loadNpmTasks("grunt-contrib-connect"); grunt.config.merge({ connect: { dev: { optio...
Allow for missing directories in $PATH
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the ...
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the ...
Add theme prop to SimpleSelect instance
const PropTypes = require('prop-types'); const React = require('react'); const Button = require('./Button'); const SimpleSelect = require('./SimpleSelect'); class HeaderMenu extends React.Component { static propTypes = { buttonIcon: PropTypes.string, buttonText: PropTypes.string.isRequired, items: PropTy...
const PropTypes = require('prop-types'); const React = require('react'); const Button = require('./Button'); const SimpleSelect = require('./SimpleSelect'); class HeaderMenu extends React.Component { static propTypes = { buttonIcon: PropTypes.string, buttonText: PropTypes.string.isRequired, items: PropTy...
Move the ParentTaxonPrefixPreview logic to the bottom The functions are hoisted anyway.
(function (Modules) { "use strict"; Modules.ParentTaxonPrefixPreview = function () { this.start = function(el) { var $parentSelectEl = $(el).find('select.js-parent-taxon'); var $pathPrefixEl = $(el).find('.js-path-prefix-hint'); function getParentPathPrefix(callback) { var parentTaxo...
(function (Modules) { "use strict"; Modules.ParentTaxonPrefixPreview = function () { this.start = function(el) { var $parentSelectEl = $(el).find('select.js-parent-taxon'); var $pathPrefixEl = $(el).find('.js-path-prefix-hint'); updateBasePathPreview(); $parentSelectEl.change(updateBas...
Add better exception handling on invalid json
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): ...
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): ...
Insert date when email was received Sometimes we receive email reports like "this is happening right now" and there is no date/time included. So if we process emails once per hour - we don't have info about event time. Additional field `extra.email_received` in the mail body collector would help.
# -*- coding: utf-8 -*- """ Uses the common mail iteration method from the lib file. """ from .lib import MailCollectorBot class MailBodyCollectorBot(MailCollectorBot): def init(self): super().init() self.content_types = getattr(self.parameters, 'content_types', ('plain', 'html')) if isi...
# -*- coding: utf-8 -*- """ Uses the common mail iteration method from the lib file. """ from .lib import MailCollectorBot class MailBodyCollectorBot(MailCollectorBot): def init(self): super().init() self.content_types = getattr(self.parameters, 'content_types', ('plain', 'html')) if isi...
Load template from `cherrypy.request.template` in handler.
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filenam...
import cherrypy from mako.lookup import TemplateLookup class Tool(cherrypy.Tool): _lookups = {} def __init__(self): cherrypy.Tool.__init__(self, 'before_handler', self.callable, priority=40) def callable(self, filenam...
Set mode = edit in project activity
package mozilla.org.webmaker.activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import org.json.JSONException; import mozilla.org.webmaker.R; import mozilla.org.webmaker.WebmakerActivity; import mozilla.org.webmaker.router.Router; public class Project extends WebmakerActivit...
package mozilla.org.webmaker.activity; import android.view.Menu; import android.view.MenuItem; import org.json.JSONException; import mozilla.org.webmaker.R; import mozilla.org.webmaker.WebmakerActivity; import mozilla.org.webmaker.router.Router; public class Project extends WebmakerActivity { public Project() {...
Fix submodules for the "no-prebuilt install from npm" case
var path = require("path"); var rootDir = path.join(__dirname, "../.."); var exec = require(path.join(rootDir, "./utils/execPromise")); module.exports = function getStatus() { return exec("git submodule status", { cwd: rootDir}) .then(function(stdout) { if (!stdout) { // In the case where we pull f...
var path = require("path"); var rootDir = path.join(__dirname, "../.."); var exec = require(path.join(rootDir, "./utils/execPromise")); module.exports = function getStatus() { return exec("git submodule status", { cwd: rootDir}) .then(function(stdout) { function getStatusPromiseFromLine(line) { var...
Use clear() instead of manually deleting all elements in the body
#!/usr/bin/env python from __future__ import print_function import sys import argparse from lxml import etree NS = {'x': 'http://www.w3.org/1999/xhtml', 'mml':'http://www.w3.org/1998/Math/MathML'} body_xpath = etree.XPath('//x:body', namespaces=NS) math_xpath = etree.XPath("//mml:math", namespaces=NS) def ...
#!/usr/bin/env python from __future__ import print_function import sys import argparse from lxml import etree NS = {'x': 'http://www.w3.org/1999/xhtml', 'mml':'http://www.w3.org/1998/Math/MathML'} body_xpath = etree.XPath('//x:body', namespaces=NS) math_xpath = etree.XPath("//mml:math", namespaces=NS) def ...
Use raw command method to run all commands in wrapper
# -*- coding: utf-8 -*- import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist...
# -*- coding: utf-8 -*- import subprocess class SessionExists(Exception): description = "Session already exists." pass class ServerConnectionError(Exception): description = "tmux server is not currently running." pass class SessionDoesNotExist(Exception): description = "Session does not exist...
Throw exception if curl call fails
<?php class Twocheckout_Api_Requester { public $apiBaseUrl; private $user; private $pass; function __construct() { $this->user = Twocheckout::$user; $this->pass = Twocheckout::$pass; $this->apiBaseUrl = Twocheckout::$apiBaseUrl; } function do_call($...
<?php class Twocheckout_Api_Requester { public $apiBaseUrl; private $user; private $pass; function __construct() { $this->user = Twocheckout::$user; $this->pass = Twocheckout::$pass; $this->apiBaseUrl = Twocheckout::$apiBaseUrl; } function do_call($...
Fix to Travis build script.
# -*- coding: utf-8 -*- import os from travispy import travispy from travispy import TravisPy def main(): restarted = [] building = [] for domain in [travispy.PUBLIC, travispy.PRIVATE]: print "Enumerate repos on ", domain conn = TravisPy.github_auth(os.environ['GITHUB_KEY'], domain) ...
# -*- coding: utf-8 -*- import os from travispy import travispy from travispy import TravisPy def main(): restarted = [] building = [] for domain in [travispy.PUBLIC, travispy.PRIVATE]: print "Enumerate repos on ", domain conn = TravisPy.github_auth(os.environ['GITHUB_KEY'], domain) ...
Remove IF EXISTS from DROP TABLE when resetting the db.
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE categories ''') db.execute(''' DROP TABLE articles ''') db.execute(''' ...
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE IF EXISTS categories ''') db.execute(''' DROP TABLE IF EXISTS articles ''') ...
Fix regexp to detect markdown file (URL with GET parameters)
window.addEventListener('load', function load(event) { window.removeEventListener('load', load, false); MarkdownViewer.init(); }, false); if (!MarkdownViewer) { var MarkdownViewer = { init: function() { var appcontent = document.getElementById('appcontent'); if (appcontent) appcontent.addEventListene...
window.addEventListener('load', function load(event) { window.removeEventListener('load', load, false); MarkdownViewer.init(); }, false); if (!MarkdownViewer) { var MarkdownViewer = { init: function() { var appcontent = document.getElementById('appcontent'); if (appcontent) appcontent.addEventListene...
Fix Queued states to be pending instead of paused
package com.novoda.downloadmanager.lib; public class PublicFacingStatusTranslator { public int translate(int status) { switch (status) { case DownloadStatus.SUBMITTED: case DownloadStatus.PENDING: case DownloadStatus.QUEUED_DUE_CLIENT_RESTRICTIONS: case Down...
package com.novoda.downloadmanager.lib; public class PublicFacingStatusTranslator { public int translate(int status) { switch (status) { case DownloadStatus.SUBMITTED: case DownloadStatus.PENDING: return DownloadManager.STATUS_PENDING; case DownloadStatu...
Use previews in ranger fzf
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifie...
from ranger.api.commands import Command class fzf_select(Command): """ :fzf_select Find a file using fzf. With a prefix argument select only directories. See: https://github.com/junegunn/fzf """ def execute(self): import subprocess import os.path if self.quantifie...
Update JS regex to strip trigger words
(function(env){ "use strict"; env.ddg_spice_gifs = function (api_result) { if (!api_result || !api_result.data || !api_result.data.length){ return Spice.failed("gifs"); } var searchTerm = DDG.get_query().replace(/gifs?|giphy/ig,'').trim(); Spice.add({ ...
(function(env){ "use strict"; env.ddg_spice_gifs = function (api_result) { if (!api_result || !api_result.data || !api_result.data.length){ return Spice.failed("gifs"); } var searchTerm = DDG.get_query().replace(/gifs?/i,'').trim(); Spice.add({ id: 'gi...