text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Adjust name and description for consistency
http://jira.diamond.ac.uk/browse/DATAACQTEAM-240 | package org.eclipse.scanning.points;
import java.util.Iterator;
import org.eclipse.scanning.api.points.AbstractGenerator;
import org.eclipse.scanning.api.points.GeneratorException;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.points.models.ArrayModel;
public class ArrayGenerator ... | package org.eclipse.scanning.points;
import java.util.Iterator;
import org.eclipse.scanning.api.points.AbstractGenerator;
import org.eclipse.scanning.api.points.GeneratorException;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.points.models.ArrayModel;
public class ArrayGenerator ... |
Fix message panel close button bug | const $ = require('jquery');
export default function( msg ) {
$('.message-panel .message-content').html( msg );
var $panel = $('.message-panel');
var $textbox = $('#textbox');
$panel.removeClass('hidden');
let stickyWatch = setInterval(function(){
if ( $textbox.offset().top < 0 ) {
... | const $ = require('jquery');
export default function( msg ) {
$('.message-panel .message-content').html( msg );
var $panel = $('.message-panel');
var $textbox = $('#textbox');
$panel.removeClass('hidden');
let stickyWatch = setInterval(function(){
if ( $textbox.offset().top < 0 ) {
... |
Exclude /actuator/health from the authenticated resources | package com.rbmhtechnology.apidocserver.security;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirec... | package com.rbmhtechnology.apidocserver.security;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirec... |
Handle new sublime syntax: bash | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""
This module exports the Shellcheck plugin class.
Example output with --format gcc
-:230:7: warning: Quote this to prevent word splitting. [SC2046]
-:230:7... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""
This module exports the Shellcheck plugin class.
Example output with --format gcc
-:230:7: warning: Quote this to prevent word splitting. [SC2046]
-:230:7... |
lib/helpers: Use flask.flash instead of tg.flash | # -*- coding: utf-8 -*-
"""WebHelpers used in SkyLines."""
from __future__ import absolute_import
import datetime
import simplejson as json
from urllib import urlencode
from flask import flash
from webhelpers import date, feedgenerator, html, number, misc, text
from .string import *
from .country import *
from sky... | # -*- coding: utf-8 -*-
"""WebHelpers used in SkyLines."""
from __future__ import absolute_import
import datetime
import simplejson as json
from urllib import urlencode
from tg import flash
from webhelpers import date, feedgenerator, html, number, misc, text
from .string import *
from .country import *
from skylin... |
Increment minor version to 2.15 to prepare for a new release.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=159890586 | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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 appli... | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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 appli... |
Load MapQuest tiles over TLS. | $(function () {
try {
var map = L.map('map');
}
catch(e){
return true;
}
var lat = $('.map-view').data("lat").toString().split(","),
long = $('.map-view').data("long").toString().split(",");
L.tileLayer('https://otile{s}-s.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpg', {
... | $(function () {
try {
var map = L.map('map');
}
catch(e){
return true;
}
var lat = $('.map-view').data("lat").toString().split(","),
long = $('.map-view').data("long").toString().split(",");
L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpg', {
sub... |
Bring back commented lines of code. | var Model;
module("Ember.RecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 3, name: 'Kris'}
... | var Model;
module("Ember.RecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 3, name: 'Kris'}
... |
Change 'language' to 'syntax', that is more precise terminology. | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-pep257
# License: MIT
#
"""This module exports the PEP257 plugin linter class."""
import o... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-pep257
# License: MIT
#
"""This module exports the PEP257 plugin linter class."""
import o... |
Use list of values and not subquery (less efficient but do not use limit) | from django.core.management.base import BaseCommand, CommandError
from api import models
from django.db.models import Count, Q
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
if 'NR' in args:
print 'Delete activities of N/R cards'
act... | from django.core.management.base import BaseCommand, CommandError
from api import models
from django.db.models import Count, Q
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
if 'NR' in args:
print 'Delete activities of N/R cards'
act... |
Fix issue where data was not being cleared upon logout | const initialState = {
profile: { data: null },
name: { data: null },
image: { data: null },
barcode: { data: null }
}
function studentProfileReducer(state = initialState, action) {
const newState = { ...state }
switch (action.type) {
case 'SET_STUDENT_PROFILE':
newState.profile.data = action.profile
ret... | const initialState = {
profile: { data: null },
name: { data: null },
image: { data: null },
barcode: { data: null }
}
function studentProfileReducer(state = initialState, action) {
const newState = { ...state }
switch (action.type) {
case 'SET_STUDENT_PROFILE':
newState.profile.data = action.profile
ret... |
fix: Add release tag in sentry | const { ApolloServer } = require('apollo-server-micro')
const { schema } = require('./schema')
const { createErrorFormatter, sentryIgnoreErrors } = require('./errors')
module.exports = function createHandler(options) {
let Sentry
if (options.sentryDsn) {
Sentry = require('@sentry/node')
Sentry.init({
... | const { ApolloServer } = require('apollo-server-micro')
const { schema } = require('./schema')
const { createErrorFormatter, sentryIgnoreErrors } = require('./errors')
module.exports = function createHandler(options) {
let Sentry
if (options.sentryDsn) {
Sentry = require('@sentry/node')
Sentry.init({
... |
Use the OAuthLibCore object defined at the module level. | from django.contrib.auth import get_user_model
from .oauth2_backends import get_oauthlib_core
UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()
class OAuth2Backend(object):
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, **credentials):
request = cr... | from django.contrib.auth import get_user_model
from .oauth2_backends import get_oauthlib_core
UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()
class OAuth2Backend(object):
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, **credentials):
request = cr... |
Fix Racket on FreeBSD after openat changes
@quantum5 this feels iffy, but I think it's (marginally) better than allowing all .racket folders to be read | from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
import os
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?')]
command = 'rac... | from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$']
command = 'racket'
syscalls = ['epoll_create', 'epoll_wa... |
Add mutation detection in dev by default | import { createStore, compose, applyMiddleware, combineReducers } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import immutableStateInvariant from 'redux-immutable-state-invariant'
import isPlainObject from './isPlainObject'
const IS_PRODUCTION = process.... | import { createStore, compose, applyMiddleware, combineReducers } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import isPlainObject from './isPlainObject'
export function getDefaultMiddleware() {
return [thunk]
}
export function configureStore(options ... |
Refactor some book model variables
Add an edition field, help texts to some of the fields.
Change behaviour of the __str__ method to be more informative. | from django.db import models
from datetime import datetime
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
edition = models.SmallIntegerField(default=1)
author = models.CharField(max_length=200)
year = models.DateTimeField('year publis... | from django.db import models
from datetime import datetime
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
year = models.DateTimeField('year published',
help_text="Please use the following for... |
Remove uneccesary console.log and storage. | var app = require('./server/server-config.js');
var models = require('./server/db/orm-model.js');
var models = models();
var User = models.User;
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(... | var app = require('./server/server-config.js');
var models = require('./server/db/orm-model.js');
var models = models();
var User = models.User;
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(... |
Fix functional shell tests in travis
Hostname in travis contains random numbers meaning that it occasionally may
contain a PID as well. Thus it must be replaced first. | #!/usr/bin/env python
from __future__ import unicode_literals
import os
import socket
import sys
import codecs
fname = sys.argv[1]
new_fname = fname + '.new'
pid_fname = 'tests/shell/3rd/pid'
with open(pid_fname, 'r') as P:
pid = P.read().strip()
hostname = socket.gethostname()
user = os.environ['USER']
with cod... | #!/usr/bin/env python
from __future__ import unicode_literals
import os
import socket
import sys
import codecs
fname = sys.argv[1]
new_fname = fname + '.new'
pid_fname = 'tests/shell/3rd/pid'
with open(pid_fname, 'r') as P:
pid = P.read().strip()
hostname = socket.gethostname()
user = os.environ['USER']
with cod... |
Remove unnecessary variable in importantRule | 'use strict';
var path = require('path');
module.exports = function (options) {
var filename = path.basename(options.path);
var config = options.config;
var node = options.node;
var value;
// Bail if the linter isn't wanted
if (!config.importantRule || (config.importantRule && !config.importa... | 'use strict';
var path = require('path');
module.exports = function (options) {
var filename = path.basename(options.path);
var config = options.config;
var node = options.node;
var message;
var value;
// Bail if the linter isn't wanted
if (!config.importantRule || (config.importantRule &... |
Attach as_jsonapi to models for easy serialization | from __future__ import unicode_literals
registry = {}
bound_registry = {}
def register(cls):
registry[cls.api_type] = cls
def as_jsonapi(self):
return cls(self).serialize()
cls.model.as_jsonapi = as_jsonapi
return cls
def bind(parent=None, resource=None):
def wrapper(endpointset):
... | from __future__ import unicode_literals
registry = {}
bound_registry = {}
def register(cls):
registry[cls.api_type] = cls
return cls
def bind(parent=None, resource=None):
def wrapper(endpointset):
if parent is not None:
endpointset.parent = parent
endpointset.url.parent... |
Switch back to using query instead of body | var express = require('express');
var Global = require('../global');
var search = require('../commands/search');
var router = express.Router();
router.get('/*', function(req, res) {
var response = '';
var arg = req.query.text;
console.log(req.query); //TODO delete
console.log(req.query.token); //TODO delete
... | var express = require('express');
var Global = require('../global');
var search = require('../commands/search');
var router = express.Router();
router.get('/*', function(req, res) {
var response = '';
var arg = req.body.text;
console.log(req.body); //TODO delete
console.log(req.body.token); //TODO delete
... |
Change from beta -> stable for v1.0.x | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="energenie",
version="1.0.1",
author="Ben Nuttall",
author_email="ben@raspberrypi.org",
description="Remotely control power sockets from the Raspberry Pi",
... | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="energenie",
version="1.0.1",
author="Ben Nuttall",
author_email="ben@raspberrypi.org",
description="Remotely control power sockets from the Raspberry Pi",
... |
Make sure QuerySet.delete() operation does not bypass protection
This fixes #1 | from django.db import models
from logicaldelete.query import LogicalDeleteQuerySet
class LogicalDeletedManager(models.Manager):
"""
A manager that serves as the default manager for `logicaldelete.models.Model`
providing the filtering out of logically deleted objects. In addition, it
provides named q... | from django.db import models
class LogicalDeletedManager(models.Manager):
"""
A manager that serves as the default manager for `logicaldelete.models.Model`
providing the filtering out of logically deleted objects. In addition, it
provides named querysets for getting the deleted objects.
"""
... |
Add missing cascade deletes on user/roles | from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import UserMixin, RoleMixin
db = SQLAlchemy()
### Add models here
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')),
db.Column('role_i... | from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import UserMixin, RoleMixin
db = SQLAlchemy()
### Add models here
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(... |
Add tmp dummy mail report so that the diagnoser kinda works instead of failing miserably | #!/usr/bin/env python
import os
from yunohost.diagnosis import Diagnoser
class MailDiagnoser(Diagnoser):
id_ = os.path.splitext(os.path.basename(__file__))[0].split("-")[1]
cache_duration = 3600
dependencies = ["ip"]
def run(self):
# TODO / FIXME TO BE IMPLEMETED in the future ...
... | #!/usr/bin/env python
import os
from yunohost.diagnosis import Diagnoser
class MailDiagnoser(Diagnoser):
id_ = os.path.splitext(os.path.basename(__file__))[0].split("-")[1]
cache_duration = 3600
dependencies = ["ip"]
def run(self):
return # TODO / FIXME TO BE IMPLEMETED in the future ...... |
Make this the first release candidate. | """
Flask-Selfdoc
-------------
Flask selfdoc automatically creates an online documentation for your flask app.
"""
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='Flask-Selfdoc',
version='1.0rc1',
url='http://github.com/jwg4/flask-selfdo... | """
Flask-Selfdoc
-------------
Flask selfdoc automatically creates an online documentation for your flask app.
"""
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='Flask-Selfdoc',
version='1.0',
url='http://github.com/jwg4/flask-selfdoc',... |
Fix wrong paramter name in permit_groups decorator | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_... | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_... |
Add method comment to population script for easy deploy | from string import ascii_lowercase
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9
target_1 ... | from string import ascii_lowercase
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
from breach.models import Target, Victim
endpoint = 'https://dimkarakostas.com/rupture/test.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9
target_1 ... |
Remove cap from map def. | package sessmgr
import (
"sync"
"time"
)
type Session struct {
id string
Last time.Time
mu sync.RWMutex
Val map[string]interface{}
prov Provider
}
func NewSession(id string, provider Provider) *Session {
v := make(map[string]interface{})
return &Session{
id: id,
Last: time.Now(),
Val: v, prov:... | package sessmgr
import (
"sync"
"time"
)
type Session struct {
id string
Last time.Time
mu sync.RWMutex
Val map[string]interface{}
prov Provider
}
func NewSession(id string, provider Provider) *Session {
v := make(map[string]interface{}, 0)
return &Session{
id: id,
Last: time.Now(),
Val: v, pr... |
Fix converter to escape HTML characters | /*-
* #%L
* SciJava polyglot kernel for Jupyter.
* %%
* Copyright (C) 2017 Hadrien Mary
* %%
* 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/L... | /*-
* #%L
* SciJava polyglot kernel for Jupyter.
* %%
* Copyright (C) 2017 Hadrien Mary
* %%
* 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/L... |
Enable tooltip freeze on samples. | 'use strict';
var React = require('react');
var Sortable = require('../views/Sortable');
var {deepPureRenderMixin} = require('../react-utils');
// We skip the first column to keep 'samples' on the left.
function makeSortable(Component) {
return React.createClass({
displayName: 'SpreadsheetSortable',
mixins: [deep... | 'use strict';
var React = require('react');
var Sortable = require('../views/Sortable');
var {deepPureRenderMixin} = require('../react-utils');
// We skip the first column to keep 'samples' on the left.
function makeSortable(Component) {
return React.createClass({
displayName: 'SpreadsheetSortable',
mixins: [deep... |
Fix usage comment to refer to the correct filename | """
Usage:
$ python get_test_group.py group_1
test_foo.py test_bar.py::TestClass
$
This is used by CI to run only a certain set of tests on a particular builder.
See ``test_groups.yaml`` for details.
"""
import yaml
from pathlib import Path
from typing import List
import click
def patterns_from_group(group_name:... | """
Usage:
$ python test_group_name.py group_1
test_foo.py test_bar.py::TestClass
$
This is used by CI to run only a certain set of tests on a particular builder.
See ``test_groups.yaml`` for details.
"""
import yaml
from pathlib import Path
from typing import List
import click
def patterns_from_group(group_name... |
Fix format string for Python 2.6 | # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(Sim... | # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
requests = pytest.importorskip("requests")
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
class Proxy(SimpleHTTPServer.SimpleHTT... |
Add dependency and correct name | #!/usr/bin/env python3
import os
from setuptools import setup, find_packages
from vtimshow import defaults
def read(fname):
"""
Utility function to read a file.
"""
return open(fname, "r").read().strip()
setup(
name = "vtimshow",
version = read(os.path.join(os.path.dirname(__file__), "VERSI... | #!/usr/bin/env python3
import os
from setuptools import setup, find_packages
from vtimshow import defaults
def read(fname):
"""
Utility function to read a file.
"""
return open(fname, "r").read().strip()
setup(
name = "vtimshow",
version = read(os.path.join(os.path.dirname(__file__), "VERSI... |
Update expected endpoint object structure | /* global describe, context, it */
'use strict';
const path = require('path');
const chai = require('chai');
const endpoints = require(path.normalize(`${__dirname}/../lib/endpoints`));
describe('lib/endpoints.js', function () {
it('should have a method "getEndpoint"', function (done) {
chai.assert.isFunction(e... | /* global describe, context, it */
'use strict';
const path = require('path');
const chai = require('chai');
const endpoints = require(path.normalize(`${__dirname}/../lib/endpoints`));
describe('lib/endpoints.js', function () {
it('should have a method `getEndpoint`', function (done) {
chai.assert.isFunction(e... |
Fix import of Callable for Python 3.9
Python 3.3 moved Callable to collections.abc and Python 3.9 removes Callable from collections module | from __future__ import unicode_literals
import re
try:
from collections.abc import Callable
except ImportError:
from collections import Callable
def user_is_authenticated(user):
if isinstance(user.is_authenticated, Callable):
authenticated = user.is_authenticated()
else:
authenticated... | from __future__ import unicode_literals
import re
import collections
def user_is_authenticated(user):
if isinstance(user.is_authenticated, collections.Callable):
authenticated = user.is_authenticated()
else:
authenticated = user.is_authenticated
return authenticated
def camelToSnake(s)... |
Fix typo (filesytem --> filesystem).
RELNOTES: None.
PiperOrigin-RevId: 216337432 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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 appl... | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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 appl... |
Check if scholarship is open before rendering cta block | {{-- Block Type: Call To Action --}}
<section {{ output_id($block->block_title) }} class="segment segment--cta">
@if (!empty($block->block_title))
<h1 class="heading -alpha">{{ $block->block_title }}</h1>
@endif
<div class="wrapper">
@if (!empty($block->block_body_html))
{{ $block->block_body_htm... | {{-- Block Type: Call To Action --}}
<section {{ output_id($block->block_title) }} class="segment segment--cta">
@if (!empty($block->block_title))
<h1 class="heading -alpha">{{ $block->block_title }}</h1>
@endif
<div class="wrapper">
@if (!empty($block->block_body_html))
{{ $block->block_body_htm... |
Comment out extra logging on errorHandler | import { alerts } from '../stores/alerts'
// Handle axios errors from backend API so that they can be shown
export function errorHandler (error) {
if (error.response) {
const response = error.response
// The request was made and the server responded with a status code
// that falls out of ... | import { alerts } from '../stores/alerts'
// Handle axios errors from backend API so that they can be shown
export function errorHandler (error) {
if (error.response) {
const response = error.response
// The request was made and the server responded with a status code
// that falls out of ... |
Add image column to character table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCharactersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('characters', function (Blueprint $table) {
$table->increments('id');
$ta... | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCharactersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('characters', function (Blueprint $table) {
$table->increments('id');
$ta... |
Fix syntax of dependencies to be compatible with debuild
Also drop argparse as an explicit dependency, it's
part of python3 | from distutils.core import setup
from setuptools import find_packages
setup(
name='mediawiki-utilities',
version="0.4.15",
author='Aaron Halfaker',
author_email='aaron.halfaker@gmail.com',
packages=find_packages(),
scripts=[],
url='http://pypi.python.org/pypi/mediawiki-utilities',
lice... | from distutils.core import setup
from setuptools import find_packages
setup(
name='mediawiki-utilities',
version="0.4.15",
author='Aaron Halfaker',
author_email='aaron.halfaker@gmail.com',
packages=find_packages(),
scripts=[],
url='http://pypi.python.org/pypi/mediawiki-utilities',
lice... |
Make sure streams always have a source. | import factory
import faker
import random
import uuid
from astral.models.stream import Stream
from astral.models.node import Node
from astral.models.ticket import Ticket
ELIXIR_CREATION = lambda class_to_create, **kwargs: class_to_create(**kwargs)
factory.Factory.set_creation_function(ELIXIR_CREATION)
class Stream... | import factory
import faker
import random
import uuid
from astral.models.stream import Stream
from astral.models.node import Node
from astral.models.ticket import Ticket
ELIXIR_CREATION = lambda class_to_create, **kwargs: class_to_create(**kwargs)
factory.Factory.set_creation_function(ELIXIR_CREATION)
class Stream... |
Fix a postAccessRequired check for the case of nonexisting post | import { ForbiddenException, NotFoundException, ServerErrorException } from '../../support/exceptions';
import { dbAdapter } from '../../models';
export function postAccessRequired(map = { postId: 'post' }) {
return async (ctx, next) => {
const forbidden = (reason = 'You can not see this post') => new Forbidden... | import { ForbiddenException, NotFoundException, ServerErrorException } from '../../support/exceptions';
import { dbAdapter } from '../../models';
export function postAccessRequired(map = { postId: 'post' }) {
return async (ctx, next) => {
const forbidden = (reason = 'You can not see this post') => new Forbidden... |
Fix `get_queue` call in `enqueue` | """
byceps.util.jobqueue
~~~~~~~~~~~~~~~~~~~~
An asynchronously processed job queue based on Redis_ and RQ_.
.. _Redis: http://redis.io/
.. _RQ: http://python-rq.org/
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
from flask ... | """
byceps.util.jobqueue
~~~~~~~~~~~~~~~~~~~~
An asynchronously processed job queue based on Redis_ and RQ_.
.. _Redis: http://redis.io/
.. _RQ: http://python-rq.org/
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
from rq imp... |
Remove unused use statement from test. | <?php
namespace Tests\MoFlashCards\ResourceBundle\Service;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class TextToSpeechServiceTest extends KernelTestCase
{
public function testGetAudio()
{
static::bootKernel();
$service = static::$kernel->getContainer()->get('resource... | <?php
namespace Tests\MoFlashCards\ResourceBundle\Service;
use MoFlashCards\ResourceBundle\Service\TextToSpeechService;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class TextToSpeechServiceTest extends KernelTestCase
{
public function testGetAudio()
{
static::bootKernel();
... |
Enable backported ``int`` in future.builtins | """
A module that brings in equivalents of the new and modified Python 3
builtins into Py2. Has no effect on Py3.
See the docs for these modules for more information::
- future.builtins.iterators
- future.builtins.backports
- future.builtins.misc
- future.builtins.disabled
"""
from future.builtins.iterators import ... | """
A module that brings in equivalents of the new and modified Python 3
builtins into Py2. Has no effect on Py3.
See the docs for these modules for more information::
- future.builtins.iterators
- future.builtins.backports
- future.builtins.misc
- future.builtins.disabled
"""
from future.builtins.iterators import ... |
Remove koa.js dependencies and add any required express middleware | var express = require('express'),
path = require('path'),
cors = require('cors'),
dotenv = require('dotenv'),
async = require('async'),
request = require('request'),
config = require('./config'),
app = express();
// Including CORS for cross-origin request access
app.use(cors());... | var compress = require('koa-compress'),
logger = require('koa-logger'),
serve = require('koa-static'),
route = require('koa-route'),
cors = require('koa-cors'),
koa = require('koa'),
dotenv = require('dotenv'),
path = require('path'),
util = require('util'),
async = require... |
Remove the "Trying service" log. | var Q = require('q');
var util = require('util');
module.exports.ServiceDispatcher = function() {
this.services = [];
};
module.exports.ServiceDispatcher.prototype.use = function(service) {
this.services.push(service);
};
module.exports.ServiceDispatcher.prototype.forAll = function(command) {
var promises = this.... | var Q = require('q');
var util = require('util');
module.exports.ServiceDispatcher = function() {
this.services = [];
};
module.exports.ServiceDispatcher.prototype.use = function(service) {
this.services.push(service);
};
module.exports.ServiceDispatcher.prototype.forAll = function(command) {
var promises = this.... |
Add header to dev launch script | #!/usr/bin/env python
"""
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
... | #!/usr/bin/env python
"""
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
... |
Sort cache channels and keys alphabetically | var crypto = require('crypto');
function DatabaseTables(tables) {
this.namespace = 't';
this.tables = tables;
}
module.exports = DatabaseTables;
DatabaseTables.prototype.key = function() {
return this.tables.map(function(table) {
return this.namespace + ':' + shortHashKey(table.dbname + ':' + ta... | var crypto = require('crypto');
function DatabaseTables(tables) {
this.namespace = 't';
this.tables = tables;
}
module.exports = DatabaseTables;
DatabaseTables.prototype.key = function() {
return this.tables.map(function(table) {
return this.namespace + ':' + shortHashKey(table.dbname + ':' + ta... |
Handle favicon, HTTP and HTTPS | const {send} = require('micro');
const fetch = require('node-fetch');
const assert = require('http-assert');
module.exports = async (req, res) => {
let url = req.url.substr(1);
if (url === 'favicon.ico') return;
if (url.indexOf('http://') !== -1) {
url = url.substr(7);
} else if (url.indexOf('https://') !=... | const {send} = require('micro');
const fetch = require('node-fetch');
const assert = require('http-assert');
module.exports = async (req, res) => {
const url = req.url.substr(1);
assert(url !== '', 400, 'URL must be defined.');
let statusCode;
let message;
try {
const response = await fetch(`http://${url... |
Allow passing initialization kwargs to PDFDocument through pdf_response | from datetime import date
import re
from django.db.models import Max, Min
from django.http import HttpResponse
from pdfdocument.document import PDFDocument
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('dat... | from datetime import date
import re
from django.db.models import Max, Min
from django.http import HttpResponse
from pdfdocument.document import PDFDocument
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('dat... |
Move constant field to class constructor | <?php
/**
* Plugin Name: Hackerspace
*
* see http://spaceapi.net/documentation#documentation-tab-13
*/
class SpaceApi
{
const API_VERSION = '0.13';
public function __construct()
{
$this->spaceapi = new stdClass; // TODO create an external regular class ?
$this->spaceapi->api = self::A... | <?php
/**
* Plugin Name: Hackerspace
*
* see http://spaceapi.net/documentation#documentation-tab-13
*/
class SpaceApi
{
const API_VERSION = '0.13';
// get space api infos from the settings
public function get_spaceapi_settings()
{
$spaceapi = new stdClass;
$spaceapi->api = self::... |
Update maxBuffer limit to 100Mib | #!/usr/bin/env node
/*
*
* Copyright 2015 gRPC authors.
*
* 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 app... | #!/usr/bin/env node
/*
*
* Copyright 2015 gRPC authors.
*
* 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 app... |
Revert "use mktmp in driver tests"
This reverts commit 55c3796beadbf427b844972b68fb7c2078fea0ac. | // mongodb-driver-test.js
//
// Testing the mongodb driver
//
// Copyright 2012, StatusNet Inc.
//
// 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/LI... | // mongodb-driver-test.js
//
// Testing the mongodb driver
//
// Copyright 2012, StatusNet Inc.
//
// 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/LI... |
Fix gulp-istanbul 0.5.0 doesn't generate lcov file. | var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rirmaf = require('rimraf');
var lib = 'lib/**/*.js';
gulp.task('coverage', function(){
return gulp.src(lib)
.pipe($.istanbul())
.pipe($.istanbul.hookRequire());
});
gulp.task('coverage:clean', function(callback){
rirmaf('coverage', c... | 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rirmaf = require('rimraf');
var lib = 'lib/**/*.js';
gulp.task('coverage', function(){
return gulp.src(lib)
.pipe($.istanbul());
});
gulp.task('coverage:clean', function(callback){
rirmaf('coverage', callback);
});
gulp.t... |
Add TODO, sign bytes may be words | package me.hugmanrique.pokedata.sprites.signs;
import me.hugmanrique.pokedata.sprites.Sprite;
import me.hugmanrique.pokedata.utils.ROM;
/**
* @author Hugmanrique
* @since 02/05/2017
*/
public class SpriteSign extends Sprite {
// TODO Check if some of these bytes are words values
private byte b2;
privat... | package me.hugmanrique.pokedata.sprites.signs;
import me.hugmanrique.pokedata.sprites.Sprite;
import me.hugmanrique.pokedata.utils.ROM;
/**
* @author Hugmanrique
* @since 02/05/2017
*/
public class SpriteSign extends Sprite {
private byte b2;
private byte b4;
private byte b5;
private byte b6;
p... |
Add overload method for easier immediate friend accepting in dev | package GameNationBackEnd.Documents;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by tijs on 30/11/2016.
*/
@Document
p... | package GameNationBackEnd.Documents;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by tijs on 30/11/2016.
*/
@Document
p... |
Fix path to pybossa tests | import json
import random
from mock import patch
from pybossa.model.task import Task
from pybossa.model.project import Project
from pybossa.model.user import User
from pybossa.model.task_run import TaskRun
from pybossa.model.category import Category
import pybossa
import sys
import os
sys.path.append(os.path.abspath... | import json
import random
from mock import patch
from pybossa.model.task import Task
from pybossa.model.project import Project
from pybossa.model.user import User
from pybossa.model.task_run import TaskRun
from pybossa.model.category import Category
import pybossa
import sys
import os
sys.path.append(os.path.abspath... |
Allow to avoid translation of classname | package ru.ydn.wicket.wicketorientdb.utils;
import java.util.List;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import ru.ydn.wicket.wicketorientdb.OrientDbWebSession;
import ru.ydn.wicket.wicketorientdb.model.OClassNamingModel;
import com.orientechnologies.orien... | package ru.ydn.wicket.wicketorientdb.utils;
import java.util.List;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import ru.ydn.wicket.wicketorientdb.OrientDbWebSession;
import ru.ydn.wicket.wicketorientdb.model.OClassNamingModel;
import com.orientechnologies.orien... |
Add a build version to executables
Use -v to print version info. | package main
import (
"flag"
"github.com/litl/galaxy/log"
)
var (
// Location of the default config.
// This will not be overwritten by shuttle.
defaultConfig string
// Location of the live config which is updated on every state change.
// The default config is loaded if this file does not exist.
stateConfi... | package main
import (
"flag"
"github.com/litl/galaxy/log"
)
var (
// Location of the default config.
// This will not be overwritten by shuttle.
defaultConfig string
// Location of the live config which is updated on every state change.
// The default config is loaded if this file does not exist.
stateConfi... |
Load next page shortly before hitting the bottom
This improves the user experience by loading in the next entries shortly before him getting to the bottom. It makes the scrolling more smooth without a break in between.
It also fixes an error on my browser that scrolling never hits the defined number. When I debugged ... | $(document).ready(function() {
var win = $(window);
win.scroll(function() {
if ($(document).height() - win.height() - win.scrollTop() < 150) {
var formData = $('#pagination form:last').serialize();
if (formData) {
$('#pagination').html('<div class="loading-spinner... | $(document).ready(function() {
var win = $(window);
win.scroll(function() {
if ($(document).height() - win.height() == win.scrollTop()) {
var formData = $('#pagination form:last').serialize();
if (formData) {
$('#pagination').html('<div class="loading-spinner"></d... |
Create SiteMeta for default site | """
Business logic in this app is implemented using a CQRS style. Commands should
be implemented as functions here. Queries should be implemented as methods on
Django model managers. Commands can then be called from a management command
(i.e. the CLI), a view, a signal, etc.
"""
from django.conf import settings
from dj... | """
Business logic in this app is implemented using a CQRS style. Commands should
be implemented as functions here. Queries should be implemented as methods on
Django model managers. Commands can then be called from a management command
(i.e. the CLI), a view, a signal, etc.
"""
from django.conf import settings
from dj... |
Change version to 2.6 as feature was added | #!/usr/bin/env python
from setuptools import setup
import os
# Utility function to read README file
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='iss',
version='2.6',
description="Ideally Single Source app for MemberSuite data.",
author='AASHE',... | #!/usr/bin/env python
from setuptools import setup
import os
# Utility function to read README file
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='iss',
version='2.5.10',
description="Ideally Single Source app for MemberSuite data.",
author='AASH... |
Fix bench decorator to return a dict instead of a list | from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res... | from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res... |
Use reduce to avoid mutating the object unneededly. | 'use strict';
const externalDeps = [
'@angular/*',
'angular',
'angular-mocks',
'rxjs/*',
'lodash',
'moment',
'moment-timezone',
];
const map = {
'@angular': 'node_modules/@angular',
'angular': 'node_modules/angular/angular',
'angular-mocks': 'node_modules/angular-mocks/angular-mocks',
'rxjs': 'node_modules... | 'use strict';
const externalDeps = [
'@angular/*',
'angular',
'angular-mocks',
'rxjs/*',
'lodash',
'moment',
'moment-timezone',
];
const map = {
'@angular': 'node_modules/@angular',
'angular': 'node_modules/angular/angular',
'angular-mocks': 'node_modules/angular-mocks/angular-mocks',
'rxjs': 'node_modules... |
[Storybook] Remove header of addon-info temporary
Since the inline styling is damn strange now, header and preview parts are split into separate shadowed containers.
Issue: storybooks/storybook#1877 | import { configure, setAddon } from '@storybook/react';
import { setOptions } from '@storybook/addon-options';
import infoAddon, { setDefaults } from '@storybook/addon-info';
import propsTableAddon from './propsTable-addon';
import Code from './Code';
// -------------------------------------
// Addons
// ----------... | import { configure, setAddon } from '@storybook/react';
import { setOptions } from '@storybook/addon-options';
import infoAddon, { setDefaults } from '@storybook/addon-info';
import propsTableAddon from './propsTable-addon';
import Code from './Code';
// -------------------------------------
// Addons
// ----------... |
Remove unused statements from API controller | <?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\API\Listing;
use Symfony\Component\Routing\Annotation\Route;
class APIController extends Controller
{
/**
* @Route("/api/listing/organisms", name="api_l... | <?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\API\Listing;
use Symfony\Component\Routing\Annotat... |
Update required properties for RCTCircleView
On React Native 0.19 these added properties were required. | var { requireNativeComponent, PropTypes } = require('react-native');
var iface = {
name: 'CircleView',
propTypes: {
showTextWhileSpinning: PropTypes.bool,
autoTextColor: PropTypes.bool,
autoTextSize: PropTypes.bool,
showUnit: PropTypes.bool,
сontourColor: PropTypes.string,
b... | var { requireNativeComponent, PropTypes } = require('react-native');
var iface = {
name: 'CircleView',
propTypes: {
showTextWhileSpinning: PropTypes.bool,
autoTextColor: PropTypes.bool,
autoTextSize: PropTypes.bool,
showUnit: PropTypes.bool,
сontourColor: PropTypes.string,
b... |
Fix "UnboundLocalError: local variable 'dep' referenced before assignment" | from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from dapi import models
register = template.Library()
@register.filter(needs_autoescape=True)
@stringfilter
def deplink(value, autoescape=None):
'''Add links for required daps'''
... | from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from dapi import models
register = template.Library()
@register.filter(needs_autoescape=True)
@stringfilter
def deplink(value, autoescape=None):
'''Add links for required daps'''
... |
Disable colours when the output is not a terminal | package main
import (
"os"
"github.com/agtorre/gocolorize"
"github.com/jessevdk/go-flags"
"github.com/src-d/beanstool/cli"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
if !terminal.IsTerminal(int(os.Stdout.Fd())) {
gocolorize.SetPlain(true)
}
parser := flags.NewNamedParser("beanstool", flags.Default... | package main
import (
"os"
"github.com/jessevdk/go-flags"
"github.com/src-d/beanstool/cli"
)
func main() {
parser := flags.NewNamedParser("beanstool", flags.Default)
parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{})
parser.AddCommand("tail", "tails a tube and prints his content", ... |
Add other options to install packages | #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# # Search for GridSearch and L... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import weka.core.jvm as jvm
import weka.core.packages as packages
jvm.start()
# checking for installed packages
installed_packages = packages.installed_packages()
for item in installed_packages:
print item.name, item.url, "is installed\n"
# Search for GridSearch and Lib... |
Improve performance by prefixing all global functions calls with \ to
skip the look up and resolve process and go straight to the global
function
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
namespace Orchestra\Translation;
use Illuminate\Translation\FileLoader as BaseFileLoader;
class FileLoader extends BaseFileLoader
{
/**
* {@inheritdoc}
*/
protected function loadNamespaceOverrides(array $lines, $locale, $group, $namespace)
{
$files = [
"{$this->path}/p... | <?php
namespace Orchestra\Translation;
use Illuminate\Translation\FileLoader as BaseFileLoader;
class FileLoader extends BaseFileLoader
{
/**
* {@inheritdoc}
*/
protected function loadNamespaceOverrides(array $lines, $locale, $group, $namespace)
{
$files = [
"{$this->path}/p... |
Fix definition of a global variable | var spawn = require('child_process').spawn,
objectAssign = require('object-assign');
module.exports = function exec(script, program) {
var dotenvConfig = objectAssign({ silent: true }, {
encoding: program.encoding,
path: program.path
});
require('dotenv').config(dotenvConfig);
var argvIndex = -1,... | var spawn = require('child_process').spawn,
objectAssign = require('object-assign');
module.exports = function exec(script, program) {
var dotenvConfig = objectAssign({ silent: true }, {
encoding: program.encoding,
path: program.path
});
require('dotenv').config(dotenvConfig);
var argvIndex = -1;... |
Reorder TemplateSpec attributes and add to docstring. | # coding: utf-8
"""
Provides a class to customize template information on a per-view basis.
To customize template properties for a particular view, create that view
from a class that subclasses TemplateSpec. The "spec" in TemplateSpec
stands for "special" or "specified" template information.
"""
class TemplateSpec... | # coding: utf-8
"""
Provides a class to customize template information on a per-view basis.
To customize template properties for a particular view, create that view
from a class that subclasses TemplateSpec. The "Spec" in TemplateSpec
stands for template information that is "special" or "specified".
"""
# TODO: fi... |
Use unabbreviated --quiet-git option in clone test | import unittest
from cvsgit.command.clone import clone
from os.path import dirname, join, exists
from shutil import rmtree
class Test(unittest.TestCase):
def setUp(self):
self.tmpdir = join(dirname(__file__), 'tmp')
def tearDown(self):
if exists(self.tmpdir):
rmtree(self.tmpdir)
... | import unittest
from cvsgit.command.clone import clone
from os.path import dirname, join, exists
from shutil import rmtree
class Test(unittest.TestCase):
def setUp(self):
self.tmpdir = join(dirname(__file__), 'tmp')
def tearDown(self):
if exists(self.tmpdir):
rmtree(self.tmpdir)
... |
Fix duplicate volumes_from when switching consoles | package switchconsole
import (
"os"
log "github.com/Sirupsen/logrus"
composeConfig "github.com/docker/libcompose/config"
"github.com/docker/libcompose/project/options"
"github.com/rancher/os/compose"
"github.com/rancher/os/config"
"golang.org/x/net/context"
)
func Main() {
if len(os.Args) != 2 {
log.Fatal(... | package switchconsole
import (
"os"
log "github.com/Sirupsen/logrus"
"github.com/docker/libcompose/project/options"
"github.com/rancher/os/compose"
"github.com/rancher/os/config"
"golang.org/x/net/context"
)
func Main() {
if len(os.Args) != 2 {
log.Fatal("Must specify exactly one existing container")
}
ne... |
Add test, which fails, of the gammatone filtering. | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... |
Add filters to the Mongo DB example. | from chatterbot import ChatBot
from chatterbot.filters import LanguageFilter, RepetitiveResponseFilter
import logging
# Uncomment the following line to enable verbose logging
# logging.basicConfig(level=logging.INFO)
# Create a new ChatBot instance
bot = ChatBot("Terminal",
storage_adapter="chatterbot.adapters.s... | from chatterbot import ChatBot
from chatterbot.filters import LanguageFilter
import logging
# Uncomment the following line to enable verbose logging
# logging.basicConfig(level=logging.INFO)
# Create a new ChatBot instance
bot = ChatBot("Terminal",
storage_adapter="chatterbot.adapters.storage.MongoDatabaseAdapte... |
Fix go version in another brats test
Co-authored-by: An Yu <446e9838deaeb979640d56c46523b7c882d598cd@pivotal.io> | package brats_test
import (
"github.com/cloudfoundry/libbuildpack/bratshelper"
"github.com/cloudfoundry/libbuildpack/cutlass"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Go buildpack", func() {
bratshelper.UnbuiltBuildpack("go", CopyBrats)
bratshelper.DeployingAnAppWithAnUpdatedVer... | package brats_test
import (
"github.com/cloudfoundry/libbuildpack/bratshelper"
"github.com/cloudfoundry/libbuildpack/cutlass"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Go buildpack", func() {
bratshelper.UnbuiltBuildpack("go", CopyBrats)
bratshelper.DeployingAnAppWithAnUpdatedVer... |
Make sure we only fetch the member roles we want to be displayed on the members page. | <?php
/**
* Verb Path Action
* GET /members index
* GET /members/create create
* POST /members store
* GET /members/{id} show
* GET /members/{id}/edit edit
* PUT/PATCH /members/{id} update
* DELETE /members/{id} ... | <?php
/**
* Verb Path Action
* GET /members index
* GET /members/create create
* POST /members store
* GET /members/{id} show
* GET /members/{id}/edit edit
* PUT/PATCH /members/{id} update
* DELETE /members/{id} ... |
[Fix] Fix some fields being overwritten by undefined
When a required field is absent, it's substitute, even when existing, was being overwritten with
undefined or [undefined] | const sanitizer = require('../../../sanitizer');
/**
* Loop and sanitize fields of an item to create a new one
*
* @param {Array<string>} fields List of fields to look inside item
* @param {Object} item The item to be looped and sanitized
* @param {Object} services Sanitization methods an... | const sanitizer = require('../../../sanitizer');
/**
* Loop and sanitize fields of an item to create a new one
*
* @param {Array<string>} fields List of fields to look inside item
* @param {Object} item The item to be looped and sanitized
* @param {Object} services Sanitization methods an... |
Move test data into the scope where it is used | package search
import "testing"
func TestSubset(t *testing.T) {
t.Run("Asset", func(t *testing.T) {
a := &Asset{
VideoID: "video-id-123",
Type: "movie",
}
sub := Hit(a).Subset()
if got, want := sub.ID, a.VideoID; got != want {
t.Fatalf("sub.ID = %q, want %q", got, want)
}
if got, want := s... | package search
import "testing"
func TestSubset(t *testing.T) {
var (
a = &Asset{
VideoID: "video-id-123",
Type: "movie",
}
s = &Series{
BrandID: "brand-id-345",
Type: "series",
}
)
t.Run("Asset", func(t *testing.T) {
sub := Hit(a).Subset()
if got, want := sub.ID, a.VideoID; got !=... |
Mark 2012.2 final in prep for RC1
Mark 2012.2 Final=True as we prepare to publish Nova Folsom RC1
Change-Id: I72731bded164aeec3c7e47f6bfe44fb219a9ea56 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC
#
# 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
... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC
#
# 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
... |
Set loaded flag on a task to false. Only load the task template if the task is clicked on (preloading the templates for all tasks is an expensive operation when there are a decent (20+) number of tasks). | angular.module('materialscommons').factory('toUITask', toUITaskService);
/*@ngInject*/
function toUITaskService() {
return function(task) {
task.displayState = {
details: {
showNotes: true,
showFiles: false,
showSamples: false,
cur... | angular.module('materialscommons').factory('toUITask', toUITaskService);
/*@ngInject*/
function toUITaskService() {
return function(task) {
task.displayState = {
details: {
showNotes: true,
showFiles: false,
showSamples: false,
cur... |
Use real measure definitions in e2e tests | from __future__ import absolute_import
from .test import *
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": utils.get_env_setting("E2E_DB_NAME"),
"USER": utils.get_env_setting("DB_USER"),
"PASSWORD": utils.get_env_setting("DB_PASS"),
"HO... | from __future__ import absolute_import
from .test import *
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": utils.get_env_setting("E2E_DB_NAME"),
"USER": utils.get_env_setting("DB_USER"),
"PASSWORD": utils.get_env_setting("DB_PASS"),
"HO... |
Update lat and lng on marker dragged |
$(document).ready(function() {
$("#id_place")
.geocomplete({
map: "#map_location",
mapOptions: { zoom: 10 },
markerOptions: { draggable: true }
})
.bind("geocode:result", function(event, result) {
$('#id_location').val(result.geometry.location.lat() + ',' + resul... |
$(document).ready(function() {
$("#id_place")
.geocomplete({
map: "#map_location",
mapOptions: {
zoom: 10
},
markerOptions: {
draggable: true
}
})
.bind("geocode:result", function(event, result) {
var coordinates = result.geome... |
Reset genfors admin password in afterEach | jest.mock('../../models/meeting');
jest.mock('../../utils');
const { emit, broadcast } = require('../../utils');
const { createGenfors } = require('../../models/meeting');
const { generateGenfors, generateSocket } = require('../../utils/generateTestData');
const { createGenfors: createGenforsListener } = require('../au... | jest.mock('../../models/meeting');
jest.mock('../../utils');
const { emit, broadcast } = require('../../utils');
const { createGenfors } = require('../../models/meeting');
const { generateGenfors, generateSocket } = require('../../utils/generateTestData');
const { createGenfors: createGenforsListener } = require('../au... |
Refactor WebResourceManagerImpl to use WebResourceFormatters for javascript and css resources
- css resource parameter for IE conditional comments added
- also added support for several HTML attributes
git-svn-id: 3d1f0b8d955af71bf8e09c956c180519124e4717@22271 2c54a935-e501-0410-bc05-97a93f6bca70 | package com.atlassian.plugin.webresource;
import junit.framework.TestCase;
import java.util.HashMap;
public class TestJavascriptWebResourceFormatter extends TestCase
{
private JavascriptWebResourceFormatter javascriptWebResourceFormatter;
protected void setUp() throws Exception
{
super.setUp();
... | package com.atlassian.plugin.webresource;
import junit.framework.TestCase;
import java.util.HashMap;
public class TestJavascriptWebResourceFormatter extends TestCase
{
private JavascriptWebResourceFormatter javascriptWebResourceFormatter;
protected void setUp() throws Exception
{
super.setUp();
... |
Fix imgur `https` to `http`. | 'use strict';
angular.module('members').filter('getMemberIdByFullName', [
function() {
/**
* @param members A member object arrays.
* @param fullName A member full name that want to find, format is 'firstname-lastname'.
*
* @return A member object.
*/
return function(members, fullNam... | 'use strict';
angular.module('members').filter('getMemberIdByFullName', [
function() {
/**
* @param members A member object arrays.
* @param fullName A member full name that want to find, format is 'firstname-lastname'.
*
* @return A member object.
*/
return function(members, fullNam... |
Store and implement the necessary data and methods for storing information about the job and result set id.
git-svn-id: d02d9bbead102d27982d5b07d77674fa86f521a4@1142 eaa15691-b419-025a-1212-ee371bd00084 | /*
* Copyright 2009-2010 by The Regents of the University of California
* 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 from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless... | /*
* Copyright 2009-2010 by The Regents of the University of California
* 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 from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless... |
Switch default to actual ES default (date_optional_time) and add TIME type | # ElasticMapping
# File: types.py
# Desc: base Elasticsearch types
class CallableDict(dict):
BASE = None
OVERRIDES = None
def __call__(self, overrides):
new_dict = CallableDict(self)
new_dict.OVERRIDES = overrides
new_dict.BASE = self
return new_dict
BASE_TYPE = {
's... | # ElasticMapping
# File: types.py
# Desc: base Elasticsearch types
class CallableDict(dict):
BASE = None
OVERRIDES = None
def __call__(self, overrides):
new_dict = CallableDict(self)
new_dict.OVERRIDES = overrides
new_dict.BASE = self
return new_dict
BASE_TYPE = {
's... |
Add OPTIONS to hartbeat API | package org.jboss.aerogear.unifiedpush.rest;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.r... | package org.jboss.aerogear.unifiedpush.rest;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.datastax.driver.core.utils.UUIDs;
im... |
Revert backend template finder code | from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from armstrong.utils.backends import GenericBackend
def get_layout_template_name(model, name):
ret = []
for a in model.__class__.mro():
if not hasattr(a, "_meta"):
continue
ret.append... | from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from armstrong.utils.backends import GenericBackend
template_finder = GenericBackend('ARMSTRONG_LAYOUT_TEMPLATE_FINDER',
defaults='armstrong.core.arm_layout.utils.get_layout_template_name')\
.get_backend... |
[CovManager] Add redirect for / to collections | from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
ur... | from django.conf.urls import patterns, include, url
from rest_framework import routers
from covmanager import views
router = routers.DefaultRouter()
router.register(r'collections', views.CollectionViewSet, base_name='collections')
router.register(r'repositories', views.RepositoryViewSet, base_name='repositories')
ur... |
base_report_auto_create_qweb: Change authors to new ones | # -*- coding: utf-8 -*-
# Authors: See README.RST for Contributors
# Copyright 2015-2016 See __openerp__.py for Authors
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Report qweb auto generation",
"version": "9.0.1.0.0",
"depends": [
"report",
],
"external_d... | # -*- coding: utf-8 -*-
# Authors: See README.RST for Contributors
# Copyright 2015-2016 See __openerp__.py for Authors
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Report qweb auto generation",
"version": "9.0.1.0.0",
"depends": [
"report",
],
"external_d... |
Fix Firefox --headless config missing | 'use strict';
module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: ['Chrome'],
launch_in_dev: ['Chrome'],
browser_start_timeout: 120,
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
proc... | 'use strict';
module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: ['Chrome'],
launch_in_dev: ['Chrome'],
browser_start_timeout: 120,
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
proc... |
Return exact results by default | export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFil... | export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFil... |
Add Count method to StoresMap object | package tokay
import (
"sync"
)
type (
// routeStore stores route paths and the corresponding handlers.
routeStore interface {
Add(key string, data interface{}) int
Get(key string, pvalues []string) (data interface{}, pnames []string)
String() string
}
storesMap struct {
sync.RWMutex
M map[string]rout... | package tokay
import (
"sync"
)
type (
// routeStore stores route paths and the corresponding handlers.
routeStore interface {
Add(key string, data interface{}) int
Get(key string, pvalues []string) (data interface{}, pnames []string)
String() string
}
storesMap struct {
sync.RWMutex
M map[string]rout... |
Use single quotes instead of a double quotes | var gulp = require('gulp');
var nightwatch = require('../');
gulp.task('default', function() {
gulp.src('')
.pipe(nightwatch({
configFile: 'nightwatch.json'
}));
});
gulp.task('withCliArgs:array', function() {
gulp.src('')
.pipe(nightwatch({
configFile: 'nightwatch.json',
cliArgs: [ ... | var gulp = require('gulp');
var nightwatch = require('../');
gulp.task('default', function() {
gulp.src('')
.pipe(nightwatch({
configFile: 'nightwatch.json'
}));
});
gulp.task('withCliArgs:array', function() {
gulp.src('')
.pipe(nightwatch({
configFile: 'nightwatch.json',
cliArgs: [ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.