text stringlengths 17 1.47k | positive stringlengths 673 4.43k | negative stringlengths 677 2.81k |
|---|---|---|
fix(date): Set the default date format | /**
* This is the default configuration file for the Superdesk application. By default,
* the app will use the file with the name "superdesk.config.js" found in the current
* working directory, but other files may also be specified using relative paths with
* the SUPERDESK_CONFIG environment variable or the grunt -... | /**
* This is the default configuration file for the Superdesk application. By default,
* the app will use the file with the name "superdesk.config.js" found in the current
* working directory, but other files may also be specified using relative paths with
* the SUPERDESK_CONFIG environment variable or the grunt -... |
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2. | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'django.contrib.sites', # for sitemap test
),
R... | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
... |
Add utf-8 in autopost example | import glob
import os
import sys
import time
from io import open
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
with open('pics.txt', 'r', encoding='utf8') as f:
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
ti... | import time
import sys
import os
import glob
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
with open('pics.txt', 'r') as f:
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
timeout = 24 * 60 * 60 # pics will be p... |
Add preconditions, cope with exception during file read. | package uk.ac.ebi.quickgo.ontology.metadata;
import uk.ac.ebi.quickgo.common.loader.GZIPFiles;
import uk.ac.ebi.quickgo.rest.metadata.MetaData;
import uk.ac.ebi.quickgo.rest.service.ServiceConfigException;
import com.google.common.base.Preconditions;
import java.nio.file.Path;
import java.util.List;
import static ja... | package uk.ac.ebi.quickgo.ontology.metadata;
import uk.ac.ebi.quickgo.common.loader.GZIPFiles;
import uk.ac.ebi.quickgo.rest.metadata.MetaData;
import java.nio.file.Path;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
* Populate a MetaData instance with information about the data prov... |
Add validator to initial user migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.core.validators
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
INSERT IGONRE `last insert id` after success insert | <?php
namespace Tests\AppBundle\Native;
class InsertTest extends ConnectionTestCase
{
public function testIgnore()
{
$connection = $this->getConnection();
try {
$connection->exec('
CREATE TABLE `users` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
... | <?php
namespace Tests\AppBundle\Native;
class InsertTest extends ConnectionTestCase
{
public function testIgnore()
{
$connection = $this->getConnection();
try {
$connection->exec('
CREATE TABLE `users` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
... |
Fix view count cutoff for YT | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderb... | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderb... |
FIX package in include command. | <?php
if (!defined("CMS_VERSION")) { header("HTTP/1.0 404 Not Found"); die(""); }
if (!class_exists("commandIncDualListbox")) {
class commandIncDualListbox extends driverCommand {
public static function runMe(&$params, $debug = true) {
$path = driverCommand::run('modGetPath', array('nam... | <?php
if (!defined("CMS_VERSION")) { header("HTTP/1.0 404 Not Found"); die(""); }
if (!class_exists("commandIncDualListbox")) {
class commandIncDualListbox extends driverCommand {
public static function runMe(&$params, $debug = true) {
$path = driverCommand::run('modGetPath', array('nam... |
Bump version due to failed markdown/rST conversion in README | from setuptools import setup
setup(
name = "django-safe-project",
version = "0.0.4",
author = "Matthew Reid",
author_email = "matt@nomadic-recording.com",
description = ("Start Django projects with sensitive data outside of the "
"global settings module"),
url... | from setuptools import setup
setup(
name = "django-safe-project",
version = "0.0.3",
author = "Matthew Reid",
author_email = "matt@nomadic-recording.com",
description = ("Start Django projects with sensitive data outside of the "
"global settings module"),
url... |
Convert data to unsigned 8-bit when displaying | import gtk, gobject
import numpy as N
class CameraImage(gtk.Image):
__gproperties__ = {
'data' : (gobject.TYPE_PYOBJECT,
'Image data',
'NumPy ndarray containing the data',
gobject.PARAM_READWRITE)
}
def __init__(self):
gtk.Image.__gobject_init__... | import gtk, gobject
import numpy as N
class CameraImage(gtk.Image):
__gproperties__ = {
'data' : (gobject.TYPE_PYOBJECT,
'Image data',
'NumPy ndarray containing the data',
gobject.PARAM_READWRITE)
}
def __init__(self):
gtk.Image.__gobject_init__... |
Add warning about custom logout redirection | <?php
return [
'layout' => 'ui::layouts.public.full',
'captcha' => false,
'identifier' => 'email',
'login' => [
'implementation' => \Laravolt\Auth\DefaultLogin::class,
],
'registration' => [
'enable' => true,
'status' => 'ACTIVE',
... | <?php
return [
'layout' => 'ui::layouts.public.full',
'captcha' => false,
'identifier' => 'email',
'login' => [
'implementation' => \Laravolt\Auth\DefaultLogin::class,
],
'registration' => [
'enable' => true,
'status' => 'ACTIVE',
... |
Add test to find a setting by name | <?php namespace Modules\Setting\Tests;
class EloquentSettingRepositoryTest extends BaseSettingTest
{
public function setUp()
{
parent::setUp();
}
/** @test */
public function it_creates_translated_setting()
{
// Prepare
$data = [
'core::site-name' => [
... | <?php namespace Modules\Setting\Tests;
class EloquentSettingRepositoryTest extends BaseSettingTest
{
public function setUp()
{
parent::setUp();
}
/** @test */
public function it_creates_translated_setting()
{
// Prepare
$data = [
'core::site-name' => [
... |
[FIX] website_field_autocomplete: Use search_read
* Use search_read in controller data getter, instead of custom implementation | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/fiel... | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/fiel... |
Fix code format with php-cs-fixer | <?php
namespace Cassowary\Adapter;
class RedisAdapter implements AdapterInterface
{
const BLACKLIST_KEY = 'blacklist';
/**
* @var \Redis
*/
private static $redis;
/**
* @var string
*/
private static $prefix;
/**
* @var int
*/
private static $duration;
... | <?php
namespace Cassowary\Adapter;
class RedisAdapter implements AdapterInterface
{
const BLACKLIST_KEY = 'blacklist';
/**
* @var \Redis
*/
private static $redis;
/**
* @var string
*/
private static $prefix;
/**
* @var int
*/
private static $duration;
... |
Fix Null Id, on create user Postgresql | <?php
namespace ZfcUser\Mapper;
use Zend\Stdlib\Hydrator\ClassMethods;
use ZfcUser\Entity\UserInterface as UserEntityInterface;
class UserHydrator extends ClassMethods {
/**
* Extract values from an object
*
* @param object $object
* @return array
* @throws Exception\InvalidArgumentExc... | <?php
namespace ZfcUser\Mapper;
use Zend\Stdlib\Hydrator\ClassMethods;
use ZfcUser\Entity\UserInterface as UserEntityInterface;
class UserHydrator extends ClassMethods
{
/**
* Extract values from an object
*
* @param object $object
* @return array
* @throws Exception\InvalidArgumentExce... |
:art: Fix mixins-before-declaration rule to work with latest gonzales | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'mixins-before-declarations',
'defaults': {
'exclude': [
'breakpoint',
'mq'
]
},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('include', function (node, i, parent... | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'mixins-before-declarations',
'defaults': {
'exclude': [
'breakpoint',
'mq'
]
},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('include', function (node, i, parent... |
Simplify how we determine if asset is already showing. | CMS.Views.Assets = Backbone.View.extend({
// takes CMS.Models.AssetCollection as model
initialize : function() {
this.listenTo(this.collection, 'destroy', this.handleDestroy);
this.render();
},
render: function() {
this.$el.empty();
var self = this;
_.each(this... | CMS.Views.Assets = Backbone.View.extend({
// takes CMS.Models.AssetCollection as model
initialize : function() {
this.listenTo(this.collection, 'destroy', this.handleDestroy);
this.render();
},
render: function() {
this.$el.empty();
var self = this;
_.each(this... |
Save user role when signing up | <?php
namespace app\models;
use yii\base\Model;
/**
* Signup form
*/
class SignupForm extends Model
{
public $email;
public $signup_token;
public $password;
/**
* @inheritdoc
*/
public function rules()
{
return [
['signup_token', 'trim'],
['email',... | <?php
namespace app\models;
use yii\base\Model;
/**
* Signup form
*/
class SignupForm extends Model
{
public $email;
public $signup_token;
public $password;
/**
* @inheritdoc
*/
public function rules()
{
return [
['signup_token', 'trim'],
['email',... |
Add buy card button to account page | import React, { Component } from 'react';
class AccountPage extends Component {
constructor () {
super();
}
render () {
const {
account
} = this.props;
return (
<div class="AccountPage">
<div class="header col-sm-12 centered">
... | import React, { Component } from 'react';
class AccountPage extends Component {
constructor () {
super();
}
render () {
const {
account
} = this.props;
return (
<div class="AccountPage">
<div class="header col-sm-12 centered">
... |
Clean up node_modules after updating them | "use strict";
module.exports = function (grunt) {
grunt.initConfig({
bump: {
options: {
files: ["package.json"],
commit: true,
commitMessage: "Release %VERSION%",
commitFiles: ["-a"],
createTag: true,
... | "use strict";
module.exports = function (grunt) {
grunt.initConfig({
bump: {
options: {
files: ["package.json"],
commit: true,
commitMessage: "Release %VERSION%",
commitFiles: ["-a"],
createTag: true,
... |
Fix : Drawer menu items are not centered | import React, { Component, PropTypes, View, Text, TouchableHighlight } from 'react-native';
import Icon from '../Icon';
import { TYPO } from '../config';
export default class Item extends Component {
static propTypes = {
icon: PropTypes.string,
value: PropTypes.string.isRequired,
onPress: ... | import React, { Component, PropTypes, View, Text, TouchableHighlight } from 'react-native';
import Icon from '../Icon';
import { TYPO } from '../config';
export default class Item extends Component {
static propTypes = {
icon: PropTypes.string,
value: PropTypes.string.isRequired,
onPress: ... |
Move to spec inspired test names (truth always wins.) | package com.github.mttkay.memento;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
import com.google.testing.compile.CompilationFailureException;
import com.google.testing.compile.JavaFileObjects;
import com.sun.tools.internal.xjc.util.NullStream;
import org.junit.Before;
import org.juni... | package com.github.mttkay.memento;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
import com.google.testing.compile.CompilationFailureException;
import com.google.testing.compile.JavaFileObjects;
import com.sun.tools.internal.xjc.util.NullStream;
import org.junit.Before;
import org.juni... |
Add tests for adding default and installed level packs |
describe('Game Manager', function() {
it('is an object', function() {
expect(Flown.GameManager).toBeDefined();
expect(typeof Flown.GameManager).toBe('object');
});
describe('creating a game manager', function() {
it('has a create function', function() {
expect(Flown.G... |
describe('Game Manager', function() {
it('is an object', function() {
expect(Flown.GameManager).toBeDefined();
expect(typeof Flown.GameManager).toBe('object');
});
describe('creating a game manager', function() {
it('has a create function', function() {
expect(Flown.G... |
Use modify with the orderbook | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data... | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data... |
Correct spelling of Django in requirements
It seems that using 'django' instead of 'Django' has the consequence that "pip install django_debug_toolbar" has the consequence of installing the latest version of Django, even if you already have Django installed. | from setuptools import setup, find_packages
from io import open
setup(
name='django-debug-toolbar',
version='1.3.2',
description='A configurable set of panels that display various debug '
'information about the current request/response.',
long_description=open('README.rst', encoding='ut... | from setuptools import setup, find_packages
from io import open
setup(
name='django-debug-toolbar',
version='1.3.2',
description='A configurable set of panels that display various debug '
'information about the current request/response.',
long_description=open('README.rst', encoding='ut... |
Adjust unit test for new props webpage | import DomMock from '../../helpers/dom-mock';
import jsdom from 'mocha-jsdom';
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { Portal } from '../../../portal/src/containers/Portal';
import FBLogin from '../../../portal/src/components/FBLogin';
import Sub... | import DomMock from '../../helpers/dom-mock';
import jsdom from 'mocha-jsdom';
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { Portal } from '../../../portal/src/containers/Portal';
import FBLogin from '../../../portal/src/components/FBLogin';
import Sub... |
Use instanceof to include subclasses | <?php
/**
* @package elemental
*/
class ElementalGridFieldDeleteAction extends GridFieldDeleteAction {
public function getColumnContent($gridField, $record, $columnName) {
if(!$record->canEdit()) return;
$field = new CompositeField();
if(!$record instanceof ElementVirtualLinked) {
... | <?php
/**
* @package elemental
*/
class ElementalGridFieldDeleteAction extends GridFieldDeleteAction {
public function getColumnContent($gridField, $record, $columnName) {
if(!$record->canEdit()) return;
$field = new CompositeField();
if($record->getClassName() != "ElementVirtualLinked") {
... |
Fix wrong CLI argument type | from django.core.management.base import BaseCommand
from submission.models import Article
from core.models import File
class Command(BaseCommand):
"""Dumps the text of files to the database using FileText Model"""
help = """
Dumps the text of galley files into the database, which populates the
... | from django.core.management.base import BaseCommand
from submission.models import Article
from core.models import File
class Command(BaseCommand):
"""Dumps the text of files to the database using FileText Model"""
help = """
Dumps the text of galley files into the database, which populates the
... |
Add 'tomorrow' to date range filter
As requested by CITA. | /* global moment */
(function($) {
'use strict';
var dateRangePicker = {
init: function() {
this.$picker = $('.js-date-range-picker');
this.$picker.daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Tomorrow': [moment().add(1, 'days'), moment().add(1, 'days')]... | /* global moment */
(function($) {
'use strict';
var dateRangePicker = {
init: function() {
this.$picker = $('.js-date-range-picker');
this.$picker.daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(... |
Rename caught previous exception variable | <?php
declare(strict_types = 1);
namespace EPS\PhpUri\Validator;
use EPS\PhpUri\Exception\ValidatorException;
final class AggregatedValidator implements Validator
{
/**
* @var Validator[]
*/
private $validators;
public function __construct(array $validators)
{
$this->validators = [... | <?php
declare(strict_types = 1);
namespace EPS\PhpUri\Validator;
use EPS\PhpUri\Exception\ValidatorException;
final class AggregatedValidator implements Validator
{
/**
* @var Validator[]
*/
private $validators;
public function __construct(array $validators)
{
$this->validators = [... |
Make parameterized assertion error extend assertion error | package org.junit.experimental.theories.internal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class ParameterizedAssertionError extends AssertionError {
private static final long serialVersionUID = 1L;
public ParameterizedAssertionError(Throwable targetException,
... | package org.junit.experimental.theories.internal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class ParameterizedAssertionError extends RuntimeException {
private static final long serialVersionUID = 1L;
public ParameterizedAssertionError(Throwable targetException,... |
Fix build wheels with Pandoc 2. | import os
from subprocess import call, check_output
import sys
from shutil import copy2
platform = sys.platform
def checkAndInstall():
try:
check_output('pandoc -v'.split())
except OSError:
def getFile():
from requests import get
with open(pandocFile, "wb") as file:
... | import os
from subprocess import call, check_output
import sys
from shutil import copy2
platform = sys.platform
def checkAndInstall():
try:
check_output('pandoc -v'.split())
except OSError:
cudir = os.path.abspath(os.curdir)
os.chdir(os.path.abspath(os.path.join(os.path.pardir, 'downl... |
Set fileParameterName for flow to the route used by the upload service. | Application.Services.factory("mcFlow", mcFlowService);
function mcFlowService() {
var self = this;
self.flow = new Flow(
{
target: "/api/upload/chunk",
testChunks: false,
fileParameterName: "chunkData"
}
);
function each(obj, callback, context) {
... | Application.Services.factory("mcFlow", mcFlowService);
function mcFlowService() {
var self = this;
self.flow = new Flow(
{
target: "/api/upload/chunk",
testChunks: false
}
);
function each(obj, callback, context) {
if (!obj) {
return ;
... |
Return empty array instead of null | <?php
/**
* PostRenderer.php
*
* Created By: jonathan
* Date: 24/09/2017
* Time: 22:17
*/
namespace Stati\Reader;
use Stati\Entity\Page;
use Stati\Entity\Sass;
use Symfony\Component\Finder\Finder;
use Stati\Reader\Reader;
use Symfony\Component\Yaml\Yaml;
/**
* Copies files and folders that do not start with _... | <?php
/**
* PostRenderer.php
*
* Created By: jonathan
* Date: 24/09/2017
* Time: 22:17
*/
namespace Stati\Reader;
use Stati\Entity\Page;
use Stati\Entity\Sass;
use Symfony\Component\Finder\Finder;
use Stati\Reader\Reader;
use Symfony\Component\Yaml\Yaml;
/**
* Copies files and folders that do not start with _... |
Fix type in contrib.sites.migrations for Django 2.x compatibility | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.contrib.sites.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Site',
fields=[
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.contrib.sites.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Site',
fields=[
... |
Trim repository URL
when copied/pasted from a repo hoster (google code) the URL may include trailing spaces that make the clone command fail | package hudson.plugins.git;
import java.io.Serializable;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.Que... | package hudson.plugins.git;
import java.io.Serializable;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.expor... |
Remove serializer 0.0->0 todo. Functionality is correct.
My JSON Firefox plugin hid the .0, making me think this was a
Jackson problem. However, Jackson is correctly outputting floats. | package com.indeed.proctor.service;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.indeed.proctor.common.model.Payload;
import com.indeed.proctor.common.model.TestBucket;
/**
* Representation of TestBucket intended for serialization into JSON.
*
* Mostly a rewriting of TestBucket with a few extras... | package com.indeed.proctor.service;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.indeed.proctor.common.model.Payload;
import com.indeed.proctor.common.model.TestBucket;
/**
* Representation of TestBucket intended for serialization into JSON.
*
* Mostly a rewriting of TestBucket with a few extras... |
Fix styling on flights form | import React from 'react'
export function FlightsForm({ homeFloor, value, onChange }) {
function onFlightsChanged(event) {
const flights = parseFloat(event.target.value)
onChange(flights)
}
function addFlights(flights) {
onChange(value + flights)
}
function onAddDefaultFlights() {
addFlight... | import React from 'react'
export function FlightsForm({ homeFloor, value, onChange }) {
function onFlightsChanged(event) {
const flights = parseFloat(event.target.value)
onChange(flights)
}
function addFlights(flights) {
onChange(value + flights)
}
function onAddDefaultFlights() {
addFlight... |
Fix code standards on callback | <?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace Respect\Validation\Rules;
use stdClass;
/**
* @group ... | <?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace Respect\Validation\Rules;
use stdClass;
/**
* @group ... |
Create users when they log in | import hashlib
import base64
from datetime import date
from bo import *
from database.oldauth import *
class Login(webapp.RequestHandler):
def get(self):
if self.request.get('site'):
u = User().current()
user = users.get_current_user()
site = self.request.get('site')... | import hashlib
import base64
from datetime import date
from bo import *
from database.oldauth import *
class Login(webapp.RequestHandler):
def get(self):
if self.request.get('site'):
user = users.get_current_user()
site = self.request.get('site')
oa = db.Query(OldAuth)... |
Fix crash with empty array | package handlers
import (
"io"
"encoding/json"
"strings"
"strconv"
"math/rand"
"time"
"github.com/nelsonleduc/calmanbot/handlers/models"
)
func ParseJSON(bytes []byte, path string) string {
var stuff interface{}
json.Unmarshal(bytes, &stuff)
elements := strings.Split(path, "... | package handlers
import (
"io"
"encoding/json"
"strings"
"strconv"
"math/rand"
"time"
"github.com/nelsonleduc/calmanbot/handlers/models"
)
func ParseJSON(bytes []byte, path string) string {
var stuff interface{}
json.Unmarshal(bytes, &stuff)
elements := strings.Split(path, "... |
Fix small style issue w/ assertEqual vs assertEquals | """
SoftLayer.tests.managers.object_storage_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
import SoftLayer
from SoftLayer import fixtures
from SoftLayer import testing
class ObjectStorageTests(testing.TestCase):
def set_up(self):
self.ob... | """
SoftLayer.tests.managers.object_storage_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
import SoftLayer
from SoftLayer import fixtures
from SoftLayer import testing
class ObjectStorageTests(testing.TestCase):
def set_up(self):
self.ob... |
Remove broken reference to the 'add-module-exports' Babel plugin. | var path = require('path');
module.exports = {
entry: path.resolve('./src/script/index.js'),
devtool: 'eval',
resolve: {
extensions: ['.js', '.jsx', '.less', '.json'],
alias: {
'react': path.resolve('./node_modules/react'),
'eth-lightwallet': path.resolve('./node_modules/eth-lightwallet/dist/... | var path = require('path');
module.exports = {
entry: path.resolve('./src/script/index.js'),
devtool: 'eval',
resolve: {
extensions: ['.js', '.jsx', '.less', '.json'],
alias: {
'react': path.resolve('./node_modules/react'),
'eth-lightwallet': path.resolve('./node_modules/eth-lightwallet/dist/... |
Fix url for default user image | define('app/views/user_menu', ['app/views/templated', 'md5'],
/**
* User Menu View
*
* @returns Class
*/
function (TemplatedView) {
'user strict';
return TemplatedView.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
... | define('app/views/user_menu', ['app/views/templated', 'md5'],
/**
* User Menu View
*
* @returns Class
*/
function (TemplatedView) {
'user strict';
return TemplatedView.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
... |
Remove imgur duplicates based on ID. | #!/usr/bin/env python3
"""
"imgur-album-downloader" is great, but it seems to download
albums twice, and appends their stupid ID to the end.
This script fixes both.
"""
import re
import os
import sys
IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)-(\w+)\.([A-Za-z0-9]+)')
if __name__ == '__main__':
if len(sys.argv)... | #!/usr/bin/env python3
"""
"imgur-album-downloader" is great, but it seems to download
albums twice, and appends their stupid ID to the end.
This script fixes both.
"""
import hashlib
import re
import os
import sys
IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)(?:-\w+)?\.([A-Za-z0-9]+)')
def get_hash(fn):
with op... |
Move getting the event loop out of try/except | import logging
from argparse import ArgumentParser
import asyncio
from .protocol import connect_inotify
logger = logging.getLogger(__name__)
def main():
parser = ArgumentParser()
parser.add_argument(
'-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING')
parser.... | import logging
from argparse import ArgumentParser
import asyncio
from .protocol import connect_inotify
logger = logging.getLogger(__name__)
def main():
parser = ArgumentParser()
parser.add_argument(
'-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING')
parser.... |
Allow variables at root level for yaml definitions.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1062 3942dd89-8c5d-46d7-aeed-044bccf3e60c | import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_da... | import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_da... |
Use a hamburger icon instead of back icon | /* @flow */
"use strict";
import ViewController from "$LIB/ViewController";
import {createMenuView} from "$VIEWS/MenuView";
import navigationBar from "$WIDGETS/bars/navigation";
import widgetGroup from "$WIDGETS/group";
import glyph from "$WIDGETS/glyph";
import GCS from "$LIB/grandCentralStation";
import L from "$... | /* @flow */
"use strict";
import ViewController from "$LIB/ViewController";
import {createMenuView} from "$VIEWS/MenuView";
import navigationBar from "$WIDGETS/bars/navigation";
import widgetGroup from "$WIDGETS/group";
import glyph from "$WIDGETS/glyph";
import GCS from "$LIB/grandCentralStation";
import L from "$... |
Use promise chaining during registration | (function (angular) {
'use strict';
angular
.module('movieClub.auth')
.factory('authApi', authApi);
function authApi($firebaseAuth, usersApi, firebaseRef) {
var factory = {
login: login,
logout: logout,
onAuth: onAuth,
... | (function (angular) {
'use strict';
angular
.module('movieClub.auth')
.factory('authApi', authApi);
function authApi($firebaseAuth, usersApi, firebaseRef) {
var factory = {
login: login,
logout: logout,
onAuth: onAuth,
... |
Fix outer script access to request, response property | <?php
namespace Karen;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
class Controller
{
public $request;
public $response;
protected $queue = [];
public function __construct(Request $request, Response $response)
{
$this->reques... | <?php
namespace Karen;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
class Controller
{
protected $request;
protected $response;
protected $queue = [];
public function __construct(Request $request, Response $response)
{
$this->... |
Fix infinite loop for filter | <?php
namespace Romans\Filter;
use Romans\Grammar\Grammar;
use Romans\Grammar\GrammarAwareTrait;
/**
* Int to Roman
*/
class IntToRoman
{
use GrammarAwareTrait;
/**
* Default Constructor
*
* @param Grammar $grammar Grammar Object
*/
public function __construct(Grammar $grammar = nu... | <?php
namespace Romans\Filter;
use Romans\Grammar\Grammar;
use Romans\Grammar\GrammarAwareTrait;
/**
* Int to Roman
*/
class IntToRoman
{
use GrammarAwareTrait;
/**
* Default Constructor
*
* @param Grammar $grammar Grammar Object
*/
public function __construct(Grammar $grammar = nu... |
Add option for source maps, and pass to ng-annotate. |
var ngAnnotate = require('ng-annotate'),
SourceMapSource = require('webpack-core/lib/SourceMapSource');
function ngAnnotatePlugin(options) {
this.options = options || { add: true, sourceMap: false };
}
ngAnnotatePlugin.prototype.apply = function apply(compiler) {
var options = this.options;
compiler... | var ngAnnotate = require('ng-annotate'),
SourceMapSource = require('webpack-core/lib/SourceMapSource');
function ngAnnotatePlugin(options) {
this.options = options || { add: true };
}
ngAnnotatePlugin.prototype.apply = function apply(compiler) {
var options = this.options;
compiler.plugin('compilatio... |
Add control for number of spaces in JSON output. | function Category(name) {
this.category = name;
this.features = [];
}
Category.prototype.addFeature = function(name) {
this.features.push({"name": name, "support": []});
}
if (process.argv.length < 3) {
console.log('Generate JSON representation of the SVG 2 new features Markdown file.');
console.l... | function Category(name) {
this.category = name;
this.features = [];
}
Category.prototype.addFeature = function(name) {
this.features.push({"name": name, "support": []});
}
if (process.argv.length != 3) {
console.log('Generate JSON representation of the SVG 2 new features Markdown file.');
console.... |
Make doctrine executor do left-joins by default | <?php
namespace RulerZ\Executor\DoctrineORM;
use RulerZ\Context\ExecutionContext;
use RulerZ\Result\IteratorTools;
trait FilterTrait
{
abstract protected function execute($target, array $operators, array $parameters);
/**
* {@inheritDoc}
*/
public function applyFilter($target, array $parameter... | <?php
namespace RulerZ\Executor\DoctrineORM;
use RulerZ\Context\ExecutionContext;
use RulerZ\Result\IteratorTools;
trait FilterTrait
{
abstract protected function execute($target, array $operators, array $parameters);
/**
* {@inheritDoc}
*/
public function applyFilter($target, array $parameter... |
Add failing test for formatting | # -*- coding: utf-8 -*-
import click
def test_basic_functionality(runner):
@click.command()
def cli():
"""First paragraph.
This is a very long second
paragraph and not correctly
wrapped but it will be rewrapped.
\b
This is
a paragraph
without r... | # -*- coding: utf-8 -*-
import click
def test_basic_functionality(runner):
@click.command()
def cli():
"""First paragraph.
This is a very long second
paragraph and not correctly
wrapped but it will be rewrapped.
\b
This is
a paragraph
without r... |
Define The Default Grunt Task | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: ['src/**/*.js', 'test/**/*.js'],
options: {
globals: {
_: false,
$: false,
jasmine: false,
describe: false,
it: false,
expect: false,
beforeEach: false,
... | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: ['src/**/*.js', 'test/**/*.js'],
options: {
globals: {
_: false,
$: false,
jasmine: false,
describe: false,
it: false,
expect: false,
beforeEach: false,
... |
Add sortkey to create table stmt | package org.bricolages.streaming.preflight;
import java.util.StringJoiner;
import lombok.*;
class CreateTableGenerator {
private StreamDefinitionEntry streamDef;
CreateTableGenerator(StreamDefinitionEntry streamDef) {
this.streamDef = streamDef;
}
String generate() {
val sb = new Stri... | package org.bricolages.streaming.preflight;
import java.util.StringJoiner;
import lombok.*;
class CreateTableGenerator {
private StreamDefinitionEntry streamDef;
CreateTableGenerator(StreamDefinitionEntry streamDef) {
this.streamDef = streamDef;
}
String generate() {
val sb = new Stri... |
Add SessionStore to Session Facade
Because of changes to the session facade. Fixes #37 | <?php
return array(
/*
|--------------------------------------------------------------------------
| Filename
|--------------------------------------------------------------------------
|
| The default path to the helper file
|
*/
'filename' => '_ide_helper.php',
/*
|----... | <?php
return array(
/*
|--------------------------------------------------------------------------
| Filename
|--------------------------------------------------------------------------
|
| The default path to the helper file
|
*/
'filename' => '_ide_helper.php',
/*
|----... |
Add negative positioning to hidden file input | <?php
namespace App\Form\Field;
class File extends \AzuraForms\Field\File
{
public function configure(array $config = []): void
{
parent::configure($config);
$this->options['button_text'] = $this->attributes['button_text'] ?? __('Select File');
$this->options['button_icon'] = $this->a... | <?php
namespace App\Form\Field;
class File extends \AzuraForms\Field\File
{
public function configure(array $config = []): void
{
parent::configure($config);
$this->options['button_text'] = $this->attributes['button_text'] ?? __('Select File');
$this->options['button_icon'] = $this->a... |
Add done flag to experiment. | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: ... | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: ... |
Improve metric http client to deal with missing report data list. | package io.sphere.sdk.play.metrics;
import io.sphere.sdk.http.HttpClient;
import io.sphere.sdk.http.HttpRequest;
import io.sphere.sdk.http.HttpResponse;
import play.mvc.Http;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
public class MetricHttpClient implements HttpCl... | package io.sphere.sdk.play.metrics;
import io.sphere.sdk.http.HttpClient;
import io.sphere.sdk.http.HttpRequest;
import io.sphere.sdk.http.HttpResponse;
import play.mvc.Http;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
public class MetricHttpClient implements HttpCl... |
Allow to overwrite default Laravel parameters | <?php
namespace Eusonlito\LaravelPacker;
use Illuminate\Support\ServiceProvider;
class PackerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application events.
*
* @retu... | <?php
namespace Eusonlito\LaravelPacker;
use Illuminate\Support\ServiceProvider;
class PackerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application events.
*
* @retu... |
Update test to use new name of helper for dois | from scrapi.base import helpers
class TestHelpers(object):
def test_format_one_tag(self):
single_tag = ' A single tag '
single_output = helpers.format_tags(single_tag)
assert single_output == ['a single tag']
assert isinstance(single_output, list)
def test_format_many_tags(se... | from scrapi.base import helpers
class TestHelpers(object):
def test_format_one_tag(self):
single_tag = ' A single tag '
single_output = helpers.format_tags(single_tag)
assert single_output == ['a single tag']
assert isinstance(single_output, list)
def test_format_many_tags(se... |
Remove the need for @Configuration annotation. Simplify! | package org.wildfly.swarm.swagger.runtime;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.wildfly.swarm.container.JARArchive;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.swagger.Swagge... | package org.wildfly.swarm.swagger.runtime;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.wildfly.swarm.container.JARArchive;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.container.runtime.Configuration;
import org.wildfly.swarm.j... |
Map: Move starting location a little so Wick Sports Ground is visible | (function(){
angular
.module('app')
.config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
// key: 'your api key',
v: '3.20', //defaults to latest 3.X anyhow
libraries: 'weather,geometry,visualization'
... | (function(){
angular
.module('app')
.config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
// key: 'your api key',
v: '3.20', //defaults to latest 3.X anyhow
libraries: 'weather,geometry,visualization'
... |
Remove capture group from URL reg exp.
You get the whole match anyway. And now you can more easily use the source of
the regexp as a part for constructing more complicated regular expressions.
e.g. var x = new RegExp( RegExp.url.source + "|" + RegExp.email.source, 'i' ); | // -------------------------------------------------------------------------- \\
// File: RegExp.js \\
// Module: Core \\
// Requires: Core.js ... | // -------------------------------------------------------------------------- \\
// File: RegExp.js \\
// Module: Core \\
// Requires: Core.js ... |
Fix up statsd work to support python 2.6
Format specifiers must include field specifier | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
from functools import wraps
from django_statsd.clients import statsd
logger = logging.getLogger(__name__)
def task_timer(fn):
@wraps(fn)
def __wrapped__(self, *args, **kwargs):
statsd.incr('tasks.{0}.{1}.count'.format(
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
from functools import wraps
from django_statsd.clients import statsd
logger = logging.getLogger(__name__)
def task_timer(fn):
@wraps(fn)
def __wrapped__(self, *args, **kwargs):
statsd.incr('tasks.{}.{}.count'.format(
... |
Fix exception json_decode() expects parameter 1 to be string, array given
Since Notifynder fixes Extra array is empty if you call toArray,
no longer json_decode is required.
https://github.com/fenos/Notifynder/issues/126 | <li class="news-item">
<table cellpadding="4">
<tr>
<td>
@if ($notification['body']['name'] == 'user.booked')
<span class="label label-warning">{!! Icon::calendar() !!}</span>
@endif
@if ($notification['body']['name'] == 'appointment.cancel')
<span class="label label-... | <li class="news-item">
<table cellpadding="4">
<tr>
<td>
@if ($notification['body']['name'] == 'user.booked')
<span class="label label-warning">{!! Icon::calendar() !!}</span>
@endif
@if ($notification['body']['name'] == 'appointment.cancel')
<span class="label label-... |
Fix usage of wrong Nullable annotation | package de.mineformers.investiture.allomancy.tileentity;
import javax.annotation.Nullable;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
/**
* Stores the mul... | package de.mineformers.investiture.allomancy.tileentity;
import com.sun.istack.internal.Nullable;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
/**
* Stores ... |
Fix a bug where spaces in a list element would cause an exception | package org.monospark.spongematchers.parser.element;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.monospark.spongematchers.util.PatternBuilder;
import com.google.common.collect.Lists;
public final class ListElementParser extends StringElementParser {
ListEle... | package org.monospark.spongematchers.parser.element;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.monospark.spongematchers.util.PatternBuilder;
import com.google.common.collect.Lists;
public final class ListElementParser extends StringElementParser {
ListEle... |
Split off two functions from GeometryExporter.__init__ | print "Loading ", __name__
import geometry, from_poser, to_lux
reload(geometry)
reload(from_poser)
reload(to_lux)
import from_poser, to_lux
def get_materials(geometry, convert = None):
f = convert or (lambda mat, k: ' NamedMaterial "%s/%s"' % (k, mat.Name()))
return [f(mat, geometry.material_key) for mat in ... | print "Loading ", __name__
import geometry, from_poser, to_lux
reload(geometry)
reload(from_poser)
reload(to_lux)
import from_poser, to_lux
class GeometryExporter(object):
def __init__(self, subject, convert_material = None,
write_mesh_parameters = None, options = {}):
geom = from_poser... |
Convert CLI output to `.csv` | #!/usr/bin/env node
'use strict';
var csv = require('to-csv');
var input = process.argv.slice(2);
var pkg = require('./package.json');
var stdin = require('get-stdin');
var viewport = require('./');
/**
* Help screen
*/
function help() {
console.log(pkg.description);
console.log('');
console.log('Usage... | #!/usr/bin/env node
'use strict';
var input = process.argv.slice(2);
var pkg = require('./package.json');
var stdin = require('get-stdin');
var viewport = require('./');
/**
* Help screen
*/
function help() {
console.log(pkg.description);
console.log('');
console.log('Usage');
console.log(' $ view... |
Add parameter documentation to the even emitter | package im.vector;
import android.os.Handler;
import android.os.Looper;
import org.matrix.androidsdk.util.Log;
import java.util.HashSet;
import java.util.Set;
public class EventEmitter<T> {
private static final String LOG_TAG = EventEmitter.class.getSimpleName();
private final Set<Listener<T>> mCallbacks;
... | package im.vector;
import android.os.Handler;
import android.os.Looper;
import org.matrix.androidsdk.util.Log;
import java.util.HashSet;
import java.util.Set;
public class EventEmitter<T> {
private static final String LOG_TAG = EventEmitter.class.getSimpleName();
private final Set<Listener<T>> mCallbacks;... |
Refactor `react-engine` client-side mounting to use Require.js
Replace event listener `DOMContentLoaded` with `requirejs` now
that the scripts will run after they are loaded.
Make sure to load `react` and `react-dom` before `react-router`.
Also, attach the modules to `window` for it to work in production. | require('../css/style.css');
(function(window, document, requirejs, define){
'use strict';
// config
try {
var config = JSON.parse(
document.getElementById('data-config').getAttribute('data-config')
);
var versions = config.versions;
} catch (error) {
// con... | require('../css/style.css');
(function(window, document, requirejs, define){
'use strict';
// config
try {
var config = JSON.parse(
document.getElementById('data-config').getAttribute('data-config')
);
var versions = config.versions;
} catch (error) {
// con... |
Fix blank alt fields by accepting preferred null
Definitely feeling the slowdown on `/artworks`. Might need to change
API to be a facade on Elasticsearch for speed, if we can figure out
`include` functionality on search. | <?php
namespace App;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class BelongsToManyOrOne extends BelongsToMany
{
/**
* Whether this relation should return a collection.
*
* @var boolean
*/
protected $isMany = true;
/**
* Get the results of the relationship.
*... | <?php
namespace App;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class BelongsToManyOrOne extends BelongsToMany
{
/**
* Whether this relation should return a collection.
*
* @var boolean
*/
protected $isMany = true;
/**
* Get the results of the relationship.
*... |
Fix duplicate download url, and fix unspecified key problem | import React, {PureComponent, PropTypes} from 'react'
import {connect} from 'react-redux'
import {parse} from 'url'
import {uniq} from 'lodash'
import ButtonItem from './button-item'
function mapStateToProps(state) {
return {
title: state.song.playing.title,
artist: state.song.playing.artist,
files: sta... | import React, {PureComponent, PropTypes} from 'react'
import {connect} from 'react-redux'
import {parse} from 'url'
import ButtonItem from './button-item'
function mapStateToProps(state) {
return {
title: state.song.playing.title,
artist: state.song.playing.artist,
files: state.song.playing.files
}
}
... |
Print project name even if it doesn't exist on disk | """Print utilities"""
import os
import emoji
from termcolor import colored, cprint
from clowder.utility.git_utilities import (
git_current_sha,
git_current_branch,
git_is_detached,
git_is_dirty
)
def print_project_status(root_directory, path, name):
"""Print repo status"""
repo_path = os.path.j... | """Print utilities"""
import os
import emoji
from termcolor import colored
from clowder.utility.git_utilities import (
git_current_sha,
git_current_branch,
git_is_detached,
git_is_dirty
)
def print_project_status(root_directory, path, name):
"""Print repo status"""
repo_path = os.path.join(root... |
Use DOTALL flag on regex. | # The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"basis,
#... | # The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"basis,
#... |
Update markup for survey link
Resolves: https://trello.com/c/ZpypHwAa/526-fix-banner-styling | <?php
$showBannerOnNetwork = get_site_option('banner_setting');
$showBannerBySite = get_field('show_banner', 'options');
if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) {
$bannerTitle = get_site_option('banner_title');
$bannerLinkText = get_site_option('banner_link... | <?php
$showBannerOnNetwork = get_site_option('banner_setting');
$showBannerBySite = get_field('show_banner', 'options');
if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) {
$bannerTitle = get_site_option('banner_title');
$bannerLinkText = get_site_option('banner_link... |
Add test case for empty and missing IRCv3 tags | import pytest
from pydle.features import ircv3
pytestmark = [pytest.mark.unit, pytest.mark.ircv3]
@pytest.mark.parametrize(
"payload, expected",
[
(
rb'@empty=;missing :irc.example.com NOTICE #channel :Message',
{'empty': True, 'missing': True}
),
(
... | import pytest
from pydle.features import ircv3
pytestmark = [pytest.mark.unit, pytest.mark.ircv3]
@pytest.mark.parametrize(
"payload, expected",
[
(
rb"@+example=raw+:=,escaped\:\s\\ :irc.example.com NOTICE #channel :Message",
{"+example": """raw+:=,escaped; \\"""}
... |
[IMP][10.0] Add UI notification for AJAX request status | 'use strict';
odoo.define('proxy_action.proxy_view', function (require) {
var ActionManager = require('web.ActionManager');
var core = require('web.core')
var _t = core._t
ActionManager.include({
ir_actions_act_proxy: function (action, options) {
var self = this;
self.do_... | 'use strict';
odoo.define('proxy_action.proxy_view', function (require) {
var ActionManager = require('web.ActionManager');
ActionManager.include({
ir_actions_act_proxy: function (action, options) {
var self = this;
action.action_list.forEach(function (task) {
$... |
Fix PyPi readme. Bump to 1.4.2 | import os
__location__ = os.path.dirname(__file__)
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# read the contents of README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='ut... | import os
__location__ = os.path.dirname(__file__)
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='pandas-profiling',
version='1.4.1',
author='Jos Polfliet',
author_email='jos.polfliet+panpro@gmail.com',
packages=['pandas_profiling'],
... |
Create codesandbox using the 'parcel' template
The default template is `create-react-app` and this one ignores the `head` tag defined in out `index.html` | (function() {
function compress(json) {
return LZString.compressToBase64(JSON.stringify(json))
.replace(/\+/g, `-`)
.replace(/\//g, `_`)
.replace(/=+$/, ``);
}
var htmlClipboard = new Clipboard('#copy-html-button');
htmlClipboard.on('success', function(e) {
e.clearSelection();
});
... | (function() {
function compress(json) {
return LZString.compressToBase64(JSON.stringify(json))
.replace(/\+/g, `-`)
.replace(/\//g, `_`)
.replace(/=+$/, ``);
}
var htmlClipboard = new Clipboard('#copy-html-button');
htmlClipboard.on('success', function(e) {
e.clearSelection();
});
... |
Use this instead of query | angular
.module('ngSharepoint.Lists')
.factory('UpdateQuery', ['$spList', 'CamlBuilder', 'WhereQuery', 'Query', function($spList, CamlBuilder, WhereQuery, Query) {
var UpdateQuery = function(list) {
this.__list = list;
this.__values = {};
this.__where = [];
return this;
};
UpdateQuery.prototype = ne... | angular
.module('ngSharepoint.Lists')
.factory('UpdateQuery', ['$spList', 'CamlBuilder', 'WhereQuery', 'Query', function($spList, CamlBuilder, WhereQuery, Query) {
var UpdateQuery = function(list) {
this.__list = list;
this.__values = {};
this.__where = [];
return this;
};
UpdateQuery.prototype = ne... |
Return is_authenticated true if we got user and it is active | from django.http import HttpResponse
from django.template import loader
from django.utils.crypto import salted_hmac, constant_time_compare
from django.contrib.auth.models import User
class HMACAuth(object):
def __init__(self, realm='API'):
self.realm = realm
def process_request(self, request):
... | from django.http import HttpResponse
from django.template import loader
from django.utils.crypto import salted_hmac, constant_time_compare
from django.contrib.auth.models import User
class HMACAuth(object):
def __init__(self, realm='API'):
self.realm = realm
def process_request(self, request):
... |
Change the way the configuration file is loaded | <?php
namespace ProjectLint\Console\Command;
use ProjectLint\Item\ItemManager;
use ProjectLint\Report\Renderer\TextRenderer;
use ProjectLint\Rule\RuleSet;
use ProjectLint\Rule\RuleSetChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Consol... | <?php
namespace ProjectLint\Console\Command;
use ProjectLint\Item\ItemManager;
use ProjectLint\Report\Renderer\TextRenderer;
use ProjectLint\Rule\RuleSet;
use ProjectLint\Rule\RuleSetChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Consol... |
Set value of 'owner' to the value of the ObjectId | from . import app, mongo
from alexandria.decorators import *
from flask import request, jsonify, url_for, session
from flask.ext.classy import FlaskView, route
import json
from bson import json_util
class BooksView(FlaskView):
route_prefix = '/api/'
@authenticated
def index(self):
query = mongo.... | from . import app, mongo
from alexandria.decorators import *
from flask import request, jsonify, url_for, session
from flask.ext.classy import FlaskView, route
import json
from bson import json_util
class BooksView(FlaskView):
route_prefix = '/api/'
@authenticated
def index(self):
query = mongo.... |
Increase update time for compliments. | var config = {
lang: 'nl',
time: {
timeFormat: 12
},
weather: {
//change weather params here:
//units: metric or imperial
params: {
q: 'Baarn,Netherlands',
units: 'metric',
// if you want a different lang for the weather that what is se... | var config = {
lang: 'nl',
time: {
timeFormat: 12
},
weather: {
//change weather params here:
//units: metric or imperial
params: {
q: 'Baarn,Netherlands',
units: 'metric',
// if you want a different lang for the weather that what is se... |
Fix result loading for novel mutations | from models import Protein, Mutation
from database import get_or_create
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
... | from models import Protein, Mutation
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self... |
Make test Callback a little more reusable | <?php
namespace Respect\Validation\Rules;
class CallbackTest extends \PHPUnit_Framework_TestCase
{
private $truthy, $falsy;
function setUp() {
$this->truthy = new Callback(function() {
return true;
});
$this->falsy = new Callback(function() {
return false;
... | <?php
namespace Respect\Validation\Rules;
class CallbackTest extends \PHPUnit_Framework_TestCase
{
public function thisIsASampleCallbackUsedInsideThisTest()
{
return true;
}
public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue()
{
$v = new Callback(function() ... |
Improve password hashing store in registration | <?php
namespace App\Controllers;
class AuthController
{
public function login()
{
var_dump(input());
return $input;
}
public function register()
{
$inputs = input()->all(['email', 'password']);
if (!$this->isValid($inputs))
{
return 'form is no... | <?php
namespace App\Controllers;
class AuthController
{
public function login()
{
var_dump(input());
return $input;
}
public function register()
{
$inputs = input()->all(['email', 'password']);
if (!$this->isValid($inputs))
{
return 'form is no... |
Rename integration test model names for debugging in console | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... |
Fix up migration to have only one PK | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-27 13:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('roombookings', '0006_bookinga_bookingb_lock'),
]
operations = [
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-27 13:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('roombookings', '0006_bookinga_bookingb_lock'),
]
operations = [
... |
Insert custom commands through the getCommands() function. | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
... | <?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Categories
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
... |
Remove loading indicator in case of error | 'use strict';
app.controller('UserProfileController', ['userService', '$routeParams', '$scope', 'favoritePost',
function (userService, $routeParams, $scope, favoritePost) {
$scope.size = "sm";
$scope.user = {};
$scope.imageSrc = '';
userService.getDetails($routeParams.user)
... | 'use strict';
app.controller('UserProfileController', ['userService', '$routeParams', '$scope', 'favoritePost',
function (userService, $routeParams, $scope, favoritePost) {
$scope.size = "sm";
$scope.user = {};
$scope.imageSrc = '';
userService.getDetails($routeParams.user)
... |
Test a manifest with multiple files. | import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-v... | from bmi_tester.api import check_bmi
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def te... |
Improve error handling for service retrieval | var request = require('request');
var async = require('async');
var Service = require('./service.js');
module.exports = function(uri){
this.uri = uri;
this.getServices = function(callback){
request.get(this.uri + '/zosConnect/services', function(error, response, body){
if(error){
... | var request = require('request');
var async = require('async');
var Service = require('./service.js');
module.exports = function(uri){
this.uri = uri;
this.getServices = function(callback){
request.get(this.uri + '/zosConnect/services', function(error, response, body){
if(error || response... |
Fix test case to account for method rename | import java.io.File;
import org.opensim.modeling.*;
class TestXsensDataReader {
public static void test_XsensDataReader() {
// Test creation and population of XsensDataReaderSettings object
XsensDataReaderSettings settings = new XsensDataReaderSettings();
ExperimentalSensor nextSensor = ... | import java.io.File;
import org.opensim.modeling.*;
class TestXsensDataReader {
public static void test_XsensDataReader() {
// Test creation and population of XsensDataReaderSettings object
XsensDataReaderSettings settings = new XsensDataReaderSettings();
ExperimentalSensor nextSensor = ... |
Fix to unicode problem in 3.2 | from __future__ import absolute_import, unicode_literals
import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,... | import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransac... |
Check returned value of non-stubbed method call | <?php
namespace spec\rtens\mockster3;
use rtens\mockster3\Mockster;
use watoki\scrut\Specification;
class CheckReturnTypeTest extends Specification {
/** @var CheckReturnTypeTest_FooClass $mock */
private $mock;
/** @var CheckReturnTypeTest_FooClass|Mockster $foo */
private $foo;
protected func... | <?php
namespace spec\rtens\mockster3;
use rtens\mockster3\Mockster;
use watoki\scrut\Specification;
class CheckReturnTypeTest extends Specification {
/** @var CheckReturnTypeTest_FooClass $mock */
private $mock;
/** @var CheckReturnTypeTest_FooClass|Mockster $foo */
private $foo;
protected func... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.