text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
Optimize package for dev and prod | import webpack from 'webpack'
import path from 'path'
const production = process.env.NODE_ENV === 'production'
module.exports = {
devtool: 'cheap-module-source-map',
watch: !production,
module: {
noParse: ['ws'],
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)... | import webpack from 'webpack';
import path from 'path';
const production = process.env.NODE_ENV === 'production';
module.exports = {
devtool: 'source-map',
watch: !production,
module: {
noParse: ['ws'],
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
... |
Allow multiple SSH keys per file | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import sys
from . import util
class SSHKey(object):
@staticmethod
def rebuild_authorized_keys():
lines = []
ssh_dir = os.path.expanduser('~/.ssh')
util.mkdir_p(os.path.join(ssh_dir, 'authorized_keys.d'))
for name i... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import sys
from . import util
class SSHKey(object):
@staticmethod
def rebuild_authorized_keys():
lines = []
ssh_dir = os.path.expanduser('~/.ssh')
util.mkdir_p(os.path.join(ssh_dir, 'authorized_keys.d'))
for name i... |
Disable flake8 warning on `__version__` import | from trakt.core.errors import ERRORS
from trakt.core.exceptions import RequestError, ClientError, ServerError
from trakt.client import TraktClient
from trakt.helpers import has_attribute
from trakt.version import __version__ # NOQA
from six import add_metaclass
__all__ = [
'Trakt',
'RequestError',
'Clie... | from trakt.core.errors import ERRORS
from trakt.core.exceptions import RequestError, ClientError, ServerError
from trakt.client import TraktClient
from trakt.helpers import has_attribute
from trakt.version import __version__
from six import add_metaclass
__all__ = [
'Trakt',
'RequestError',
'ClientError'... |
Add @xstate/vue to publishable packages | const { exec } = require('@actions/exec');
const getWorkspaces = require('get-workspaces').default;
async function execWithOutput(command, args, options) {
let myOutput = '';
let myError = '';
return {
code: await exec(command, args, {
listeners: {
stdout: data => {
myOutput += data.... | const { exec } = require('@actions/exec');
const getWorkspaces = require('get-workspaces').default;
async function execWithOutput(command, args, options) {
let myOutput = '';
let myError = '';
return {
code: await exec(command, args, {
listeners: {
stdout: data => {
myOutput += data.... |
Disable union wrap for clickhouse | from .enums import Dialects
from .queries import (
Query,
QueryBuilder,
)
class MySQLQuery(Query):
"""
Defines a query class for use with MySQL.
"""
@classmethod
def _builder(cls):
return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False)
class Vertic... | from .enums import Dialects
from .queries import (
Query,
QueryBuilder,
)
class MySQLQuery(Query):
"""
Defines a query class for use with MySQL.
"""
@classmethod
def _builder(cls):
return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False)
class Vertic... |
Add missing file from merge | package com.moac.android.opensecretsanta.util;
import com.moac.android.opensecretsanta.database.DatabaseManager;
import com.moac.android.opensecretsanta.model.ContactMethod;
import com.moac.android.opensecretsanta.model.Member;
import java.util.List;
public class NotifyUtils {
public static boolean containsSend... | package com.moac.android.opensecretsanta.util;
import com.moac.android.opensecretsanta.database.DatabaseManager;
import com.moac.android.opensecretsanta.model.ContactMode;
import com.moac.android.opensecretsanta.model.Member;
import java.util.List;
public class NotifyUtils {
public static boolean containsSendab... |
Fix name of parameter `disabledCategories` | # -*- coding: utf-8 -*-
import requests
def get_languages(api_url):
r = requests.get(api_url + "languages")
return r.json()
def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None,
enabled_rules=None, disabled_rules=None,
enabled_categories=None, disabled_categor... | # -*- coding: utf-8 -*-
import requests
def get_languages(api_url):
r = requests.get(api_url + "languages")
return r.json()
def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None,
enabled_rules=None, disabled_rules=None,
enabled_categories=None, disabled_categor... |
Fix C++ accelerator constructor invocation | import numpy as np
import pandas as pd
from typing import Tuple, List
from queryexpander.semantic_similarity import CppSemanticSimilarity
class QueryExpander:
def __init__(self, vocabulary_path: str, vocabulary_length: int, sums_cache_file: str, centroids_file_path: str):
self._words: List[str] = pd.read... | import numpy as np
import pandas as pd
from typing import Tuple, List
from queryexpander.semantic_similarity import CppSemanticSimilarity
class QueryExpander:
def __init__(self, vocabulary_path: str, vocabulary_length: int, sums_cache_file: str, centroids_file_path: str):
self._words: List[str] = pd.read... |
Fix typo in log message | 'use strict';
const winston = require('winston');
const Twitter = require('twitter');
const cache = require('./cache');
const parse = require('./parse');
const uniq = require('uniq');
const searchTerm = 't.d3fc.io';
const client = new Twitter({
consumer_key: process.env.consumer_key,
consumer_secret: process.env... | 'use strict';
const winston = require('winston');
const Twitter = require('twitter');
const cache = require('./cache');
const parse = require('./parse');
const uniq = require('uniq');
const searchTerm = 't.d3fc.io';
const client = new Twitter({
consumer_key: process.env.consumer_key,
consumer_secret: process.env... |
Allow delete operation in NEW state
- nc-1148 | from __future__ import unicode_literals
from rest_framework import mixins
from nodeconductor.core.models import SynchronizableMixin, SynchronizationStates
from nodeconductor.core.exceptions import IncorrectStateException
class ListModelMixin(mixins.ListModelMixin):
def __init__(self, *args, **kwargs):
i... | from __future__ import unicode_literals
from rest_framework import mixins
from nodeconductor.core.models import SynchronizableMixin, SynchronizationStates
from nodeconductor.core.exceptions import IncorrectStateException
class ListModelMixin(mixins.ListModelMixin):
def __init__(self, *args, **kwargs):
i... |
Add environment output on application boot. | (function () {
'use strict';
// Initialise RequireJS module loader
require.config({
urlArgs: 'm=' + (new Date()).getTime(),
baseUrl: '/app/',
paths: {
// RequireJS extensions
text: '../lib/text/text',
// Vendor libraries
knockout: '..... | (function () {
'use strict';
// Initialise RequireJS module loader
require.config({
urlArgs: 'm=' + (new Date()).getTime(),
baseUrl: '/app/',
paths: {
// RequireJS extensions
text: '../lib/text/text',
// Vendor libraries
knockout: '..... |
Add some basic error handling | import { ReactiveVar } from 'meteor/reactive-var';
export class Result {
constructor({
observer,
defaultValue = {}
} = {}) {
this.observer = observer;
this._isReady = new ReactiveVar(false);
this._errors = new ReactiveVar();
this._var = new ReactiveVar(defaultVa... | import { ReactiveVar } from 'meteor/reactive-var';
export class Result {
constructor({
observer,
defaultValue = {}
} = {}) {
this.observer = observer;
this._isReady = new ReactiveVar(false);
this._errors = new ReactiveVar();
this._var = new ReactiveVar(defaultVa... |
Fix 'You must call one of in() or append() methods before iterating over a Finder.' | <?php
namespace Tienvx\Bundle\MbtBundle;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Tienvx\Bundle\MbtBund... | <?php
namespace Tienvx\Bundle\MbtBundle;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Tienvx\Bundle\MbtBund... |
Update path and file references | <?php
/**
* @file
* Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginRulesActionGenerator extends Generator
{
/**
* Generator Plugin RulesAction
* @param $module
* @param $class_name
* @param $label
* @param $plugin_i... | <?php
/**
* @file
* Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginRulesActionGenerator extends Generator
{
/**
* Generator Plugin RulesAction
* @param $module
* @param $class_name
* @param $label
* @param $plugin_i... |
Stop using ord with ints | """
Test mujoco viewer.
"""
import unittest
from mujoco_py import mjviewer, mjcore
class MjLibTest(unittest.TestCase):
xml_path = 'tests/models/cartpole.xml'
def setUp(self):
self.width = 100
self.height = 100
self.viewer = mjviewer.MjViewer(visible=False,
... | """
Test mujoco viewer.
"""
import unittest
from mujoco_py import mjviewer, mjcore
class MjLibTest(unittest.TestCase):
xml_path = 'tests/models/cartpole.xml'
def setUp(self):
self.width = 100
self.height = 100
self.viewer = mjviewer.MjViewer(visible=False,
... |
Use http scheme to reduce test times | # -*- coding: UTF-8 -*-
from geopy.geocoders import Teleport
from test.geocoders.util import GeocoderTestBase
class TeleportTestCaseUnitTest(GeocoderTestBase):
def test_user_agent_custom(self):
geocoder = Teleport(
user_agent='my_user_agent/1.0'
)
self.assertEqual(geocoder.hea... | # -*- coding: UTF-8 -*-
from geopy.geocoders import Teleport
from test.geocoders.util import GeocoderTestBase
class TeleportTestCaseUnitTest(GeocoderTestBase):
def test_user_agent_custom(self):
geocoder = Teleport(
user_agent='my_user_agent/1.0'
)
self.assertEqual(geocoder.hea... |
Use PHP 8 throw expression | <?php
declare(strict_types = 1);
/**
* /src/Form/DataTransformer/RoleTransformer.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Form\DataTransformer;
use App\Entity\Role;
use App\Resource\RoleResource;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form... | <?php
declare(strict_types = 1);
/**
* /src/Form/DataTransformer/RoleTransformer.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Form\DataTransformer;
use App\Entity\Role;
use App\Resource\RoleResource;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form... |
Check for null values when setting primitives. | package com.datasift.client.pylon;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PylonParametersData {
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_EMPTY)
protected String interval;
@JsonProperty
@JsonInclude(JsonInclu... | package com.datasift.client.pylon;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PylonParametersData {
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_EMPTY)
protected String interval;
@JsonProperty
@JsonInclude(JsonInclu... |
Fix refs to body of sconsole | # Import third party libs
import urwid
# Import sconsole libs
import sconsole.cmdbar
import sconsole.static
FOOTER = [
('title', 'Salt Console'), ' ',
('key', 'UP'), ' ',
('key', 'DOWN'), ' ']
class Manager(object):
def __init__(self, opts):
self.opts = opts
self.cmdba... | # Import third party libs
import urwid
# Import sconsole libs
import sconsole.cmdbar
import sconsole.static
FOOTER = [
('title', 'Salt Console'), ' ',
('key', 'UP'), ' ',
('key', 'DOWN'), ' ']
class Manager(object):
def __init__(self, opts):
self.opts = opts
self.cmdba... |
Remove unnecessary dependency on ordereddict | from setuptools import setup, find_packages
import os
requires = [
'Flask==0.9',
'elasticsearch',
'PyJWT==0.1.4',
'iso8601==0.1.4',
]
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
n... | from setuptools import setup, find_packages
import sys
import os
requires = [
'Flask==0.9',
'elasticsearch',
'PyJWT==0.1.4',
'iso8601==0.1.4',
]
if sys.version_info < (2, 7):
requires.append('ordereddict==1.1')
def read(*paths):
"""Build a file path from *paths* and return the contents."""
... |
issue-1809: Fix issue hiding zero-balance categories in move money menu | import { Feature } from 'toolkit/extension/features/feature';
import { isCurrentRouteBudgetPage } from 'toolkit/extension/utils/ynab';
export class RemoveZeroCategories extends Feature {
shouldInvoke() {
return isCurrentRouteBudgetPage();
}
invoke() {
let coverOverbudgetingCategories = $('.modal-budget-... | import { Feature } from 'toolkit/extension/features/feature';
import { isCurrentRouteBudgetPage } from 'toolkit/extension/utils/ynab';
export class RemoveZeroCategories extends Feature {
shouldInvoke() {
return isCurrentRouteBudgetPage();
}
invoke() {
let coverOverbudgetingCategories = $('.modal-budget-... |
Fix trouble about the output filename | import logging
import subprocess
class Tcpdump:
def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None):
self._interface = interface
self._buffer_size = buffer_size
self._pcap_size = pcap_size
self._pcap_timeout = pcap_timeout
... | import logging
import subprocess
class Tcpdump:
def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None):
self._interface = interface
self._buffer_size = buffer_size
self._pcap_size = pcap_size
self._pcap_timeout = pcap_timeout
... |
Move "Add message" button to top | import React, {Component} from 'react';
import io from 'socket.io-client';
import './App.css';
class App extends Component {
state = {messages: []};
socket = io('http://localhost:8080');
componentDidMount() {
this.socket
.on('connect', () => {
//console.log('CONNECT')... | import React, {Component} from 'react';
import io from 'socket.io-client';
import './App.css';
class App extends Component {
state = {messages: []};
socket = io('http://localhost:8080');
componentDidMount() {
this.socket
.on('connect', () => {
//console.log('CONNECT')... |
Fix access level for setLogTag | <?php
/**
* @license MIT
* @copyright 2017 Tim Gunter
*/
namespace Kaecyra\AppCommon\Log\Tagged;
/**
* Tagged log trait
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package app-common
*/
trait TaggedLogTrait {
/**
* Log tag
* @var string|Callable
*/
protected $logTag = null;
... | <?php
/**
* @license MIT
* @copyright 2017 Tim Gunter
*/
namespace Kaecyra\AppCommon\Log\Tagged;
/**
* Tagged log trait
*
* @author Tim Gunter <tim@vanillaforums.com>
* @package app-common
*/
trait TaggedLogTrait {
/**
* Log tag
* @var string|Callable
*/
protected $logTag = null;
... |
Fix regression in D-01186, introduced by B-03523
The solution for B-03523 incorrectly tests when the status is set to "DOWN".
It appears to be testings if the service is visible to the public OR if the status is "DOWN".
This ends up exposing non-public services to anonymous, thereby re-introducing D-01186.
Change the... | app.filter('dashboardServices', function () {
var reduceArray = function (arr, condition1, condition2) {
var resultingArr = [];
if (condition1) {
angular.forEach(arr, function (el) {
if (el[condition2]) {
resultingArr.push(el);
}
... | app.filter('dashboardServices', function () {
var reduceArray = function (arr, condition1, condition2) {
var resultingArr = [];
if (condition1) {
angular.forEach(arr, function (el) {
if (el[condition2] || el.status === 'DOWN') {
resultingArr.push(el);... |
Increase size of category field. | from django.db import models
class Position(models.Model):
job_id = models.CharField(max_length=25, unique=True)
title = models.CharField(max_length=100)
requisition_id = models.PositiveIntegerField()
category = models.CharField(max_length=50)
job_type = models.CharField(max_length=10)
locatio... | from django.db import models
class Position(models.Model):
job_id = models.CharField(max_length=25, unique=True)
title = models.CharField(max_length=100)
requisition_id = models.PositiveIntegerField()
category = models.CharField(max_length=35)
job_type = models.CharField(max_length=10)
locatio... |
Add warning on niceb5y mirror | import React, { Component } from 'react'
export default class extends Component {
render() {
return (
<div className="block pt-3 pb-5 text-center">
<div className="row">
<div className="col-12">
<h1>
Ubuntu JE
<a className="text-takasuki" href="http... | import React, { Component } from 'react'
export default class extends Component {
render() {
return (
<div className="block pt-3 pb-5 text-center">
<div className="row">
<div className="col-12">
<h1>
Ubuntu JE
<a className="text-takasuki" href="http... |
Add client-side JS files to JSHint task | module.exports = function(grunt) {
require('matchdep').filter('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
jshint: {
all: [
'*.js',
'lib/**/*.js',
'app/js/**/*.js'
],
options: {
... | module.exports = function(grunt) {
require('matchdep').filter('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
jshint: {
all: [
'*.js',
'lib/**/*.js'
],
options: {
}
},
// ## //
... |
Change session cookie ttl to 1 month | <?php
namespace BNETDocs\Libraries;
use CarlBennett\MVC\Libraries\Router;
use CarlBennett\MVC\Libraries\Session as BaseSession;
class Session extends BaseSession {
const COOKIE_NAME = 'uid';
const LOGIN_TTL = 2592000; // 1 month
public static function checkLogin(Router &$router) {
// Check if logged i... | <?php
namespace BNETDocs\Libraries;
use CarlBennett\MVC\Libraries\Router;
use CarlBennett\MVC\Libraries\Session as BaseSession;
class Session extends BaseSession {
const COOKIE_NAME = 'uid';
const LOGIN_TTL = 86400; // 1 day
public static function checkLogin(Router &$router) {
// Check if logged in by... |
Use sure in project tools cases | import sure
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Projec... | from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mix... |
Fix metadata addition when the results are empty | <?php
/*
* This file is part of Packagist.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
* Nils Adermann <naderman@naderman.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Packagist\WebBundle\Controller;
use Sym... | <?php
/*
* This file is part of Packagist.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
* Nils Adermann <naderman@naderman.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Packagist\WebBundle\Controller;
use Sym... |
Fix a target window of keyboard shortcuts for tab | chrome.commands.onCommand.addListener(function(command) {
var callback;
if ( command === "show-next-tab" ) {
callback = function(tabs) {
var tab = tabs[0];
chrome.tabs.query({ windowId: tab.windowId, index: tab.index + 1 }, function(tabs) {
var tab = tabs[0];
chrome.tabs.update(tab.i... | chrome.commands.onCommand.addListener(function(command) {
var callback;
if ( command === "show-next-tab" ) {
callback = function(tabs) {
var tab = tabs[0];
chrome.tabs.query({ windowId: tab.windowId, index: tab.index + 1 }, function(tabs) {
var tab = tabs[0];
chrome.tabs.update(tab.i... |
Simplify the construction of change events and make them protected | package org.realityforge.replicant.client;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* An event indicating that an imitation has changed.
*/
public final class EntityChangeEvent
{
private final EntityChangeType _type;
private final Object _object;
private final String _name;
pri... | package org.realityforge.replicant.client;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* An event indicating that an imitation has changed.
*/
public final class EntityChangeEvent
{
private final EntityChangeType _type;
private final Object _object;
private final String _name;
pri... |
Fix cdr timezone test issue | package org.asteriskjava.manager.event;
import static org.junit.Assert.assertEquals;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
public class CdrEventTest
{
CdrEvent cdrEvent;
TimeZone defaultTimeZone;
@Before
public void setUp()
{
... | package org.asteriskjava.manager.event;
import static org.junit.Assert.assertEquals;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
public class CdrEventTest
{
CdrEvent cdrEvent;
TimeZone defaultTimeZone;
@Before
public void setUp()
{
cdrEvent = new CdrEvent(... |
Add light service and unit tests | 'use strict';
exports.seed = function (knex, Promise) {
return Promise.join(
// Deletes ALL existing entries
knex('lights').del(),
// Inserts seed entries
knex('lights').insert({
id: 1,
name: 'Lounge',
enabled: 1,
device: 1,
... | 'use strict';
exports.seed = function (knex, Promise) {
return Promise.join(
// Deletes ALL existing entries
knex('lights').del(),
// Inserts seed entries
knex('lights').insert({
id: 1,
name: 'Lounge',
enabled: 1,
device: 1,
... |
Fix linting paths to match previous refactor | module.exports = function (grunt) {
'use strict';
grunt.initConfig({
jshint: {
options: grunt.file.readJSON('.jshintrc'),
gruntfile: 'Gruntfile.js',
bin: [ 'cli.js', 'yoyo.js' ],
test: {
options: {
globals: {
describe: true,
it: true,
... | module.exports = function (grunt) {
'use strict';
grunt.initConfig({
jshint: {
options: grunt.file.readJSON('.jshintrc'),
gruntfile: 'Gruntfile.js',
bin: {
src: [
'bin/*.js',
'bin/yo'
]
},
test: {
options: {
globals: {
... |
Simplify code pertaining to running all testscases in controller | <?php
class TestrunController extends ControllerBase {
public $environment = 'test';
public function create( $name = '' ) {
require_once 'models/test/base.php';
require_once 'models/test/functional.php';
require_once 'models/test/withfixtures.php';
i... | <?php
class TestrunController extends ControllerBase {
public $environment = 'test';
public function create( $name = '' ) {
$all = $name == '';
if ( $all ) {
set_time_limit( 360 );
}
require_once 'models/test/base.php';
r... |
Add tentative fix to isFinished using magnitudes rather than the pos/neg values | package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* Rotates the Robot without PID values
*/
public class DrivetrainRotateNoPIDCommand extends Command {
private double degrees;
private double startAngle;
public DrivetrainRotateNoPIDCommand(double _degr... | package edu.stuy.commands;
import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* Rotates the Robot without PID values
*/
public class DrivetrainRotateNoPIDCommand extends Command {
private double degrees;
private double startAngle;
public DrivetrainRotateNoPIDCommand(double _degr... |
Add some print statements for debugging. | from __future__ import absolute_import
from datetime import datetime
from django.core.management.base import BaseCommand
from pillow_retry.models import PillowError
from corehq.apps.change_feed.producer import producer
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('pi... | from __future__ import absolute_import
from django.core.management.base import BaseCommand
from pillow_retry.models import PillowError
from corehq.apps.change_feed.producer import producer
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('pillow')
def handle(self, pi... |
Hide link if no photo | import React from 'react';
import {NavigationLink} from 'navigation-react';
import Banner from './Banner';
import Tweets from './Tweets';
export default ({tweet: {account: {id: accountId, name, username, logo},
id, text, photo, time, retweets, likes, replies}}) => (
<div>
<Banner title="Tweet" />
<div cla... | import React from 'react';
import {NavigationLink} from 'navigation-react';
import Banner from './Banner';
import Tweets from './Tweets';
export default ({tweet: {account: {id: accountId, name, username, logo},
id, text, photo, time, retweets, likes, replies}}) => (
<div>
<Banner title="Tweet" />
<div cla... |
Add CSRF token to JS POST header | var csrftoken = $('input[name=csrf_token]').attr('value');
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
}
});
$(function () {
$('#single').sub... | $(function () {
$('#single').submit(function (event) {
event.preventDefault();
$(':submit').button('loading')
$.post('/thread', {
submission: $('input[name="submission"]').val(),
email: $('input[name="email"]').val()
})
.done(function (data) {
... |
Update job when job detail clicked | minerva.views.JobsPanel = minerva.View.extend({
initialize: function () {
var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum;
var columns = columnEnum.COLUMN_STATUS_ICON |
columnEnum.COLUMN_TITLE;
this.jobListWidget = new girder.views.jobs_JobListWid... | minerva.views.JobsPanel = minerva.View.extend({
initialize: function () {
var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum;
var columns = columnEnum.COLUMN_STATUS_ICON |
columnEnum.COLUMN_TITLE;
this.jobListWidget = new girder.views.jobs_JobListWid... |
Add error function to remove duplicate code | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def error(message):
print(message)
sys.exit(1)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
... | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argumen... |
Remove superfluous string from format variable | 'use strict';
var request = require('request');
var opts = parseOptions(process.argv[2]);
request(opts, function (err, res, body) {
if (err) throw new Error(err);
var format = '[%s]: %s %s %s';
for (var i = 0; i < body.length; i++) {
/*
* TODO return something like this as JSON
... | 'use strict';
var request = require('request');
var opts = parseOptions(process.argv[2]);
request(opts, function (err, res, body) {
if (err) throw new Error(err);
var format = '[%s]: %s %s %s %s';
for (var i = 0; i < body.length; i++) {
/*
* TODO return something like this as JSON
... |
Add warning when server handler task queue is full | __all__ = [
'SocketServer',
]
import errno
import logging
from g1.asyncs.bases import servers
from g1.asyncs.bases import tasks
LOG = logging.getLogger(__name__)
LOG.addHandler(logging.NullHandler())
class SocketServer:
def __init__(self, socket, handler, max_connections=0):
self._socket = socket
... | __all__ = [
'SocketServer',
]
import errno
import logging
from g1.asyncs.bases import servers
from g1.asyncs.bases import tasks
LOG = logging.getLogger(__name__)
LOG.addHandler(logging.NullHandler())
class SocketServer:
def __init__(self, socket, handler, max_connections=0):
self._socket = socket
... |
Add reference to CollectionItems by singular collection name, if possible | <?php namespace TightenCo\Jigsaw;
use Exception;
use TightenCo\Jigsaw\IterableObject;
class ViewData extends IterableObject
{
private $data;
private $globals = ['extends', 'section', 'content', 'link'];
public $item;
public static function withCollectionItem($data, $collectionName, $itemName)
{
... | <?php namespace TightenCo\Jigsaw;
use Exception;
use TightenCo\Jigsaw\IterableObject;
class ViewData extends IterableObject
{
private $data;
private $globals = ['extends', 'section', 'content', 'link'];
public $item;
public static function withCollectionItem($data, $collectionName, $itemName)
{
... |
Fix level 1 phpstan issues | <?php declare(strict_types=1);
namespace League\Container\Inflector;
use Generator;
use League\Container\ContainerAwareTrait;
class InflectorAggregate implements InflectorAggregateInterface
{
use ContainerAwareTrait;
/**
* @var \League\Container\Inflector\Inflector[]
*/
protected $inflectors =... | <?php declare(strict_types=1);
namespace League\Container\Inflector;
use Generator;
use League\Container\ContainerAwareTrait;
class InflectorAggregate implements InflectorAggregateInterface
{
use ContainerAwareTrait;
/**
* @var \League\Container\Inflector[]
*/
protected $inflectors = [];
... |
Fix syntax to work with php 5.3 | <?php
namespace Phive\Twig\Extensions\Deferred;
class DeferredExtension extends \Twig_Extension
{
/**
* @var \Twig_Environment
*/
protected $environment;
/**
* @var array
*/
private $blocks = array();
/**
* {@inheritdoc}
*/
public function initRuntime(\Twig_Envi... | <?php
namespace Phive\Twig\Extensions\Deferred;
class DeferredExtension extends \Twig_Extension
{
/**
* @var \Twig_Environment
*/
protected $environment;
/**
* @var array
*/
private $blocks = array();
/**
* {@inheritdoc}
*/
public function initRuntime(\Twig_Envi... |
AP-6: Fix check for email and password. | <?php
namespace Application\Module {
class User extends \Application\Module {
public function Index() {
return $this->Login();
}
public function Login() {
$Request = $this->getRequest();
$User = $this->getModel("User");
if (isset($Request['A... | <?php
namespace Application\Module {
class User extends \Application\Module {
public function Index() {
return $this->Login();
}
public function Login() {
$Request = $this->getRequest();
$User = $this->getModel("User");
if (isset($Request['A... |
Write new users to database. | (function () {
'use strict';
angular.module('j.point.me').controller('FirstController', ['$scope', '$firebase', '$firebaseAuth', '$window',
function ($scope, $firebase, $firebaseAuth, $window) {
var ref = new Firebase("https://jpointme.firebaseio.com/");
var auth = $firebaseAut... | (function () {
'use strict';
angular.module('j.point.me').controller('FirstController', ['$scope', '$firebase', '$firebaseAuth', '$window',
function ($scope, $firebase, $firebaseAuth, $window) {
var ref = new Firebase("https://jpointme.firebaseio.com/");
var auth = $firebaseAut... |
Update user creation method in register serializer. | from rest_framework import serializers
from django.core import exceptions
from django.contrib.auth import password_validation
from user.models import User
class CaptchaSerializer(serializers.Serializer):
OPERATION_CHOICES = (
('+', '+'),
('-', '-'),
# ('/', '/'),
# ('*', '*'),
... | from rest_framework import serializers
from django.core import exceptions
from django.contrib.auth import password_validation
from user.models import User
class CaptchaSerializer(serializers.Serializer):
OPERATION_CHOICES = (
('+', '+'),
('-', '-'),
# ('/', '/'),
# ('*', '*'),
... |
Fix simpletag -> simple_tag
Fix imports |
from django import template
from ..processors import find_processor, AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] = AssetRegistry()
con... |
from django import template
from damn.processors import find_processor
from damn.utils import AssetRegistry, DepNode
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AM... |
Add unsetProperty for property managers | <?php
declare(strict_types=1);
namespace LotGD\Core\Tools\Model;
/**
* Provides method and doctrine annotation for a property submodel
*/
trait PropertyManager
{
private $propertyStorage = null;
public function loadProperties()
{
if ($this->propertyStorage !== null) {
return;
... | <?php
declare(strict_types=1);
namespace LotGD\Core\Tools\Model;
/**
* Provides method and doctrine annotation for a property submodel
*/
trait PropertyManager
{
private $propertyStorage = null;
public function loadProperties()
{
if ($this->propertyStorage !== null) {
return;
... |
Fix opening files from GMail
* MOPPAND-751
Signed-off-by: ab8d0676af4d724c40f403280b143ae093b0e58d@nortal.com | package ee.ria.DigiDoc.common;
import java.io.File;
import java.io.IOException;
public class FileUtil {
/**
* Check if file path is in cache directory
*
* @param file File to check
* @return Boolean indicating if file is in the cache directory.
*/
public static File getFileInDirector... | package ee.ria.DigiDoc.common;
import java.io.File;
import java.io.IOException;
public class FileUtil {
/**
* Check if file path is in cache directory
*
* @param file File to check
* @return Boolean indicating if file is in the cache directory.
*/
public static File getFileInDirector... |
Change variable name & int comparison. | from flask import jsonify, current_app
import json
from . import status
from . import utils
from .. import models
@status.route('/_status')
def status():
api_response = utils.return_response_from_api_status_call(
models.get_api_status
)
search_api_response = utils.return_response_from_api_statu... | from flask import jsonify, current_app
import json
from . import status
from . import utils
from .. import models
@status.route('/_status')
def status():
api_response = utils.return_response_from_api_status_call(
models.get_api_status
)
search_api_response = utils.return_response_from_api_statu... |
Fix serializer to keep 'false' values | import Ember from 'ember';
import DS from 'ember-data';
// Adapted from http://springember.blogspot.com.au/2014/08/using-ember-data-restadapter-with.html
export default DS.RESTSerializer.extend({
serializeIntoHash: function(hash, type, record, options) {
var serialized = this.serialize(record, options);
... | import Ember from 'ember';
import DS from 'ember-data';
// Adapted from http://springember.blogspot.com.au/2014/08/using-ember-data-restadapter-with.html
export default DS.RESTSerializer.extend({
serializeIntoHash: function(hash, type, record, options) {
var serialized = this.serialize(record, options);
... |
Return empty response when StopIteration is raised on exhausted iterator | from django.core.urlresolvers import reverse
from avocado.events import usage
from .base import FieldBase
class FieldStats(FieldBase):
"Field Stats Resource"
def get(self, request, pk):
uri = request.build_absolute_uri
instance = request.instance
if instance.simple_type == 'number':
... | from django.core.urlresolvers import reverse
from avocado.events import usage
from .base import FieldBase
class FieldStats(FieldBase):
"Field Stats Resource"
def get(self, request, pk):
uri = request.build_absolute_uri
instance = request.instance
if instance.simple_type == 'number':
... |
Make Timeout inherit from BaseException for now. | """Client exceptions."""
class OkException(BaseException):
"""Base exception for ok.py."""
pass
# TODO(albert): extend from a base class designed for student bugs.
class Timeout(BaseException):
"""Exception for timeouts."""
_message = 'Evaluation timed out!'
def __init__(self, timeout):
"... | """Client exceptions."""
class OkException(BaseException):
"""Base exception for ok.py."""
pass
class Timeout(OkException):
"""Exception for timeouts."""
_message = 'Evaluation timed out!'
def __init__(self, timeout):
"""Constructor.
PARAMTERS:
timeout -- int; number of s... |
Fix reading in for layer_colors. | def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ign... | def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ign... |
BB-4270: Call nonexistent method in layout expression
- add exception to deteprovider decorator | <?php
namespace Oro\Component\Layout;
/**
* The data provider decorator that allows calls methods with pre-defined prefix
*/
class DataProviderDecorator
{
/**
* @var object
*/
protected $dataProvider;
/**
* @var string[]
*/
protected $methodPrefixes;
/**
* @param objec... | <?php
namespace Oro\Component\Layout;
/**
* The data provider decorator that allows calls methods with pre-defined prefix
*/
class DataProviderDecorator
{
/**
* @var object
*/
protected $dataProvider;
/**
* @var string[]
*/
protected $methodPrefixes;
/**
* @param objec... |
Move type_chack_prod module level variable and change its name to _type_check_prod | import numpy
from chainer import function
from chainer.utils import type_check
_type_check_prod = type_check.Variable(numpy.prod, 'prod')
class Reshape(function.Function):
"""Reshapes an input array without copy."""
def __init__(self, shape):
self.shape = shape
def check_type_forward(self, i... | import numpy
from chainer import function
from chainer.utils import type_check
class Reshape(function.Function):
type_check_prod = type_check.Variable(numpy.prod, 'prod')
"""Reshapes an input array without copy."""
def __init__(self, shape):
self.shape = shape
def check_type_forward(self, ... |
Introduce a more reliable id and channel for Notifications. | package com.novoda.downloadmanager;
import android.app.Notification;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v4.app.NotificationCompat;
class DownloadBatchNotification implements NotificationCreator {
private static final boolean NOT_INDETERMINATE = f... | package com.novoda.downloadmanager;
import android.app.Notification;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v4.app.NotificationCompat;
class DownloadBatchNotification implements NotificationCreator {
private static final int ID = 1;
private stati... |
Fix PHPUnit cleanup listener on suite name change | <?php declare(strict_types=1);
namespace Symplify\Tests\PHPUnit\Listener;
use Nette\Utils\FileSystem;
use Nette\Utils\Finder;
use Nette\Utils\Strings;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
use SplFileInfo;
final class ClearLogAnd... | <?php declare(strict_types=1);
namespace Symplify\Tests\PHPUnit\Listener;
use Nette\Utils\FileSystem;
use Nette\Utils\Finder;
use Nette\Utils\Strings;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
use SplFileInfo;
final class ClearLogAnd... |
Make the query of dataset name more reliable on different kind datasets
Some datasets are created at runtime, so it could be missing fields
Also prepare for dataset rename feature | import View from '../view';
import template from '../../templates/widgets/datasetInfoWidget.pug';
import '../../stylesheets/widgets/datasetInfoWidget.styl';
/**
* This widget is used to diplay minerva metadata for a dataset.
*/
const DatasetInfoWidget = View.extend({
initialize: function (settings) {
this.d... | import View from '../view';
import template from '../../templates/widgets/datasetInfoWidget.pug';
import '../../stylesheets/widgets/datasetInfoWidget.styl';
/**
* This widget is used to diplay minerva metadata for a dataset.
*/
const DatasetInfoWidget = View.extend({
initialize: function (settings) {
this.d... |
Change self.accounts to self.info for getting the cached password hash | from module.plugins.Account import Account
from module.common.json_layer import json_loads
class ReloadCc(Account):
__name__ = "ReloadCc"
__version__ = "0.1"
__type__ = "account"
__description__ = """Reload.Cc account plugin"""
__author_name__ = ("Reload Team")
__author_mail__ = ("hello... | from module.plugins.Account import Account
from module.common.json_layer import json_loads
class ReloadCc(Account):
__name__ = "ReloadCc"
__version__ = "0.1"
__type__ = "account"
__description__ = """Reload.Cc account plugin"""
__author_name__ = ("Reload Team")
__author_mail__ = ("hello... |
Change gender to represent boolean female | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAnimalTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('animal', functio... | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAnimalTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('animal', functio... |
[Test] Change testTypeInvalid: string to integer | <?php
include 'plan.php';
class PlanTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers ScalarValidator::__invoke
*/
public function testScalar()
{
$validator = plan('hello');
$result = $validator('hello');
$this->assertEquals('hello', $result);
}
/**
... | <?php
include 'plan.php';
class PlanTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers ScalarValidator::__invoke
*/
public function testScalar()
{
$validator = plan('hello');
$result = $validator('hello');
$this->assertEquals('hello', $result);
}
/**
... |
Revert setting methods as protected | <?php namespace Tait\ModelLogging;
use Tait\ModelLogging\ModelLog;
use Auth;
trait LoggableTrait
{
/**
* Get all logs for this object
*
* @return collection
*/
public function getAllLogs()
{
return ModelLog::
with('user')
->where('content_id', '=', $this... | <?php namespace Tait\ModelLogging;
use Tait\ModelLogging\ModelLog;
use Auth;
trait LoggableTrait
{
/**
* Get all logs for this object
*
* @return collection
*/
protected function getAllLogs()
{
return ModelLog::
with('user')
->where('content_id', '=', $t... |
Return DNS data in the correct format | import logging, interfaces, os, IPy
from StringIO import StringIO
class Shorewall(interfaces.IOpenMesherPlugin):
def __init__(self):
self._files = {}
def process(self, mesh):
logging.debug('Generating DNS config...')
self._files = {}
rdns = StringIO()
for r... | import logging, interfaces, os, IPy
from StringIO import StringIO
class Shorewall(interfaces.IOpenMesherPlugin):
def __init__(self):
self._files = {}
def process(self, mesh):
logging.debug('Generating DNS config...')
self._files = {}
rdns = StringIO()
for r... |
Rename var to more meaningful name | package com.fourlastor.dante.html;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import com.fourlastor.dante.parser.Block;
import com.fourlastor.dante.parser.BlockListener;
class ImgListener implements BlockL... | package com.fourlastor.dante.html;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import com.fourlastor.dante.parser.Block;
import com.fourlastor.dante.parser.BlockListener;
class ImgListener implements BlockL... |
Change names for CNR,SNR fields | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMamsurveydataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('mamsurvey... | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMamsurveydataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('mamsurvey... |
Add cancel button to note | <div class='note-form-wrapper'>
<textarea class="flight-note" name="flight[flight_note]"><?php echo $flight->getFlightNote() ? $flight->getFlightNote() : '' ?></textarea>
<button class="submit btn btn-green">Submit</button>
<button class="cancel btn btn-gray">Cancel</button>
</div>
<script type='text/javasc... | <div class='note-form-wrapper'>
<textarea class="flight-note" name="flight[flight_note]"><?php echo $flight->getFlightNote() ? $flight->getFlightNote() : '' ?></textarea>
<button type="submit" class="submit btn btn-green"><?php echo $flight->getFlightNote() ? 'Update Note' : 'Add Note' ?></button>
</div>
<scrip... |
tests: Remove reference to deleted file | var path = require('path');
var chai = require('chai');
chai.use(require('chai-fs'));
chai.should();
const ROOT_DIR = path.join(process.cwd(), '..');
describe('As a dev', function() {
describe('when testing cartridge file structure', function() {
it('then _config files should exist', function() {
... | var path = require('path');
var chai = require('chai');
chai.use(require('chai-fs'));
chai.should();
const ROOT_DIR = path.join(process.cwd(), '..');
describe('As a dev', function() {
describe('when testing cartridge file structure', function() {
it('then _config files should exist', function() {
... |
Increase coverage to match update | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
... | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
... |
Delete non-digit characters in ISBN in server side | from decimal import Decimal
import re
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from books.models import BookType, Book
from common.bookchooserwizard import BookChooserWizard
class SellWizard(BookChooserWizard):
@property
def page_title(self):
return... | from decimal import Decimal
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from books.models import BookType, Book
from common.bookchooserwizard import BookChooserWizard
class SellWizard(BookChooserWizard):
@property
def page_title(self):
return _("Sell b... |
Exclude 1.11's "unbreakable" common tag | package roycurtis.signshopexport.json;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
/** Exclusions class for blacklisting objects and fields in Gson */
public class Exclusions implements ExclusionStrategy
{
@Override
public boolean shouldSkipField(FieldAttributes f)
{
... | package roycurtis.signshopexport.json;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
/** Exclusions class for blacklisting objects and fields in Gson */
public class Exclusions implements ExclusionStrategy
{
@Override
public boolean shouldSkipField(FieldAttributes f)
{
... |
Edit gruntfile: create task less2css | module.exports = function(grunt) {
// config
grunt.initConfig({
less: {
build: {
expand: true,
cwd: 'src/less/',
src: ['**/*.less'],
dest: 'build/css/',
ext: '.css'
}
},
csslint: {
... | module.exports = function(grunt) {
// config
grunt.initConfig({
less: {
build: {
expand: true,
cwd: 'src/less/',
src: ['**/*.less'],
dest: 'build/css/',
ext: '.css'
}
},
csslint: {
... |
Remove useless logic to show page action when activate tab. | (
function () {
var isDebugging = false;
var re = /saas.hp(.*).com\/agm/;
function isAgmSite(url){
return re.test(url);
}
function onCopyClicked(tab) {
var re = /saas.hp(.*).com\//;
if (!isAgmSite(tab.url)) {
c... | (
function () {
var isDebugging = false;
var re = /saas.hp(.*).com\/agm/;
function isAgmSite(url){
return re.test(url);
}
function onCopyClicked(tab) {
var re = /saas.hp(.*).com\//;
if (!isAgmSite(tab.url)) {
c... |
Fix bug in no sha use case | from elasticsearch import Elasticsearch
from storage import Storage
class ElasticSearchStorage(Storage):
def __init__(self, config_dict):
self.db = config_dict['database']
self.host = config_dict['host']
self.port = config_dict['port']
self.username = config_dict['username']
... | from elasticsearch import Elasticsearch
from storage import Storage
class ElasticSearchStorage(Storage):
def __init__(self, config_dict):
self.db = config_dict['database']
self.host = config_dict['host']
self.port = config_dict['port']
self.username = config_dict['username']
... |
Add a sortyBy comparator to spine collection | "use strict";
/**
* Collection of spines.
**/
define([
"underscore",
"backbone"
], function(_, Backbone) {
var SpineCollection = Backbone.Collection.extend({
filterKey: null,
/**
* sortBy comparator: return the title, by which BB will sort the collection.
**/
c... | "use strict";
/**
* Collection of spines.
**/
define([
"underscore",
"backbone"
], function(_, Backbone) {
var SpineCollection = Backbone.Collection.extend({
filterKey: null,
url: function() {
var url = "_view/spines";
if (!_.isNull(this.filterKey)) {
... |
Set utf-8 as default encoding. | # -*- coding: utf-8 -*-
import scrapy
import scrapy.selector
from brasileirao.items import BrasileiraoItem
import hashlib
class ResultsSpider(scrapy.Spider):
name = "results"
start_urls = [
'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/',
]
def parse(self, response):
... | import scrapy
import scrapy.selector
from brasileirao.items import BrasileiraoItem
import hashlib
class ResultsSpider(scrapy.Spider):
name = "results"
start_urls = [
'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/',
]
def parse(self, response):
actual_round = 0
... |
Add KDE show & hide logging | # -*- coding: utf-8 -*-
# Copyright 2013 Jacek Mitręga
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law o... | # -*- coding: utf-8 -*-
# Copyright 2013 Jacek Mitręga
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law o... |
STASHDEV-6530: Update front-end code to stop using APIs removed in Stash 3.0 | define('plugin/download-archive', [
'jquery',
'aui',
'model/page-state',
'util/navbuilder',
'exports'
], function(
$,
AJS,
pageState,
navBuilder,
exports
) {
exports.onReady = function (buttonSelector) {
var $button = $(buttonSelector);
/**
* Updat... | define('plugin/download-archive', ['jquery', 'aui', 'model/page-state', 'util/navbuilder', 'exports'], function ($, AJS, pageState, navBuilder, exports) {
exports.onReady = function (buttonSelector) {
var $button = $(buttonSelector);
/**
* Update the "download archive" button's URL to targ... |
Remove _getView() usages from renderAdapter | <?php
class CM_RenderAdapter_FormField extends CM_RenderAdapter_Abstract {
public function fetch(array $params, CM_FormField_Abstract $field, CM_Form_Abstract $form, $fieldName) {
$fieldName = (string) $fieldName;
/** @var CM_FormField_Abstract $field */
$field->prepare($params);
... | <?php
class CM_RenderAdapter_FormField extends CM_RenderAdapter_Abstract {
public function fetch(array $params, CM_FormField_Abstract $field, CM_Form_Abstract $form, $fieldName) {
$fieldName = (string) $fieldName;
/** @var CM_FormField_Abstract $field */
$field->prepare($params);
... |
Add very basic date filtering | var router = require("express").Router();
var db = require("./db");
router.get("/", function (req, res) {
var start = new Date(1971, 0, 1);
if (req.query.start) {
start = new Date(req.query.start);
}
var o = {
map: function () {
if (this.parents.length === 1 && this.date >= start) {
for (... | var router = require("express").Router();
var db = require("./db");
router.get("/", function (req, res) {
var o = {
map: function () {
if (this.parents.length === 1) {
for (var i = 0; i < this.files.length; i++) {
emit(this.author,
{
additions: this.files[i].addi... |
Add SearchButton component to Header component | import React from 'react';
import styled from 'styled-components';
import theme from 'theme';
import Hamburger, { Bar } from 'components/Hamburger';
import SearchButton from 'components/SearchButton';
const Logo = styled.h1`
font-family: Poppins, sans-serif;
letter-spacing: 1px;
font-size: 30px;
margin... | import React from 'react';
import styled from 'styled-components';
import theme from 'theme';
import Hamburger, { Bar } from 'components/Hamburger';
const Logo = styled.h1`
font-family: Poppins, sans-serif;
letter-spacing: 1px;
font-size: 30px;
margin: 0;
display: inline;
flex: 0 0 calc(100% - ... |
Make Item.createEntity only call when its specifically a EntityItem, not a subclass of it. | package net.minecraftforge.common;
import java.util.UUID;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public voi... | package net.minecraftforge.common;
import java.util.UUID;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public voi... |
Allow RedirectMixin to work within flask-admin | # -*- coding: utf-8 -*-
""" Module provides mixins for issuing HTTP Status codes using the
Flask ``View``.
"""
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
howev... | # -*- coding: utf-8 -*-
""" Module provides mixins for issuing HTTP Status codes using the
Flask ``View``.
"""
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
howev... |
Enable proper websocket support in webpack proxy | const merge = require('webpack-merge');
const config = require('./webpack.config');
const host = process.env.SDF_HOST || 'localhost';
const port = process.env.SDF_PORT || '8080';
const backendHost = process.env.SDF_BACKEND_HOST || 'backend';
const backendPort = process.env.SDF_BACKEND_PORT || '3000';
module.exports ... | const merge = require('webpack-merge');
const config = require('./webpack.config');
const host = process.env.SDF_HOST || 'localhost';
const port = process.env.SDF_PORT || '8080';
const backendHost = process.env.SDF_BACKEND_HOST || 'backend';
const backendPort = process.env.SDF_BACKEND_PORT || '3000';
module.exports ... |
Add method to check is content is in another collection
Former-commit-id: b5590a20f5a01e0fbe3aa4a856e6450a12d5cf8f
Former-commit-id: 7c42e5bbf445bfffb43de66ed823417c51d6e4df
Former-commit-id: 2675c6ef54e4d1ad9118400029a8ead243f426e9 | import http from '../http';
export default class collections {
static get(collectionID) {
return http.get(`/zebedee/collectionDetails/${collectionID}`)
.then(response => {
return response;
})
}
static getAll() {
return http.get(`/zebedee/collect... | import http from '../http';
export default class collections {
static get(collectionID) {
return http.get(`/zebedee/collectionDetails/${collectionID}`)
.then(response => {
return response;
})
}
static getAll() {
return http.get(`/zebedee/collect... |
[FIX] Add Item doesn`t appears instantly | import { EventEmitter } from "events";
import dispatcher from "../dispatcher";
class BlogStore extends EventEmitter {
constructor() {
super();
//this is a kind of initial load message.
// it will be overwrite till the first GET :P
this.blogs = [
{
"id":... | import { EventEmitter } from "events";
import dispatcher from "../dispatcher";
class BlogStore extends EventEmitter {
constructor() {
super();
//this is a kind of initial load message.
// it will be overwrite till the first GET :P
this.blogs = [
{
"id":... |
Switch to stacked area graph | import _ from 'lodash';
import Highcharts from 'highcharts';
function patientsByGroupDateGraph(adapter) {
return {
scope: {
groupType: '@',
type: '@'
},
template: '<div loading="loading" class="graph"></div>',
link: function(scope, element) {
var params = {
groupType: scope.... | import _ from 'lodash';
import Highcharts from 'highcharts';
function patientsByGroupDateGraph(adapter) {
return {
scope: {
groupType: '@',
type: '@'
},
template: '<div loading="loading" class="graph"></div>',
link: function(scope, element) {
var params = {
groupType: scope.... |
Add NamedModulesPlugin to webpack config | const webpack = require('webpack')
const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'source-map',
output: {
path: path.resolve(__dirname, './dist'),
},
module: {
rules: [
... | const webpack = require('webpack')
const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'source-map',
output: {
path: path.resolve(__dirname, './dist'),
},
module: {
rules: [
... |
Change names of timing pvs |
import sirius
def get_record_names(family_name = None):
"""Return a dictionary of record names for given subsystem
each entry is another dictionary of model families whose
values are the indices in the pyaccel model of the magnets
that belong to the family. The magnet models ca be segmented,
in wh... |
import sirius
def get_record_names(family_name = None):
"""Return a dictionary of record names for given subsystem
each entry is another dictionary of model families whose
values are the indices in the pyaccel model of the magnets
that belong to the family. The magnet models ca be segmented,
in wh... |
Correct unit test assertion for XHR object | /*!
Copyright 2013 Rustici Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed t... | /*!
Copyright 2013 Rustici Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed t... |
Return array consistently from query method | <?php
namespace Rogue\Services;
use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a ... | <?php
namespace Rogue\Services;
use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a ... |
Use Django's module loading rather than __import__
__import__ doesn't deal well with dotted paths, in my instance my root url conf is in a few levels "appname.config.urls". unfortunately, for __import__ this means that just `appname` is imported, but `config.urls` is loaded and no other modules in between are usable. ... | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.utils.module_loading import import_string
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
... | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import... |
Use sys in error cases. | import sys
def format_cols(cols):
widths = [0] * len(cols[0])
for i in cols:
for idx, val in enumerate(i):
widths[idx] = max(len(val), widths[idx])
f = ""
t = []
for i in widths:
t.append("%%-0%ds" % (i,))
return " ".join(t)
def column_report(title, fields, c... | def format_cols(cols):
widths = [0] * len(cols[0])
for i in cols:
for idx, val in enumerate(i):
widths[idx] = max(len(val), widths[idx])
f = ""
t = []
for i in widths:
t.append("%%-0%ds" % (i,))
return " ".join(t)
def column_report(title, fields, cols):
l ... |
Fix race condition in purge test. | require('./harness').run();
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
var e = connection.exchange('node-purge-fanout', {type: 'fanout', confirm: true});
var q = connection.queue('node-purge-queue', fun... | require('./harness').run();
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
var e = connection.exchange('node-purge-fanout', {type: 'fanout'});
var q = connection.queue('node-purge-queue', function() {
q... |
Make into a real object instead of lots of static methods. | package net.happygiraffe.jslint;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
/**
* A command line interface to {@link JSLint}.
*
* @author dom
* @version $Id$
*/
public c... | package net.happygiraffe.jslint;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
/**
* A command line interface to {@link JSLint}.
*
* @author dom
* @version $Id$
*/
public c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.