text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update yaml method to make CodeFactor happy | #!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2... | #!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2... |
Fix inaccurate docstring for dashboard issue count | from sqlalchemy import func
from catwatch.blueprints.user.models import db, User
from catwatch.blueprints.issue.models import Issue
class Dashboard(object):
@classmethod
def group_and_count_users(cls):
"""
Perform a group by/count on all user types.
:return: List of results
"... | from sqlalchemy import func
from catwatch.blueprints.user.models import db, User
from catwatch.blueprints.issue.models import Issue
class Dashboard(object):
@classmethod
def group_and_count_users(cls):
"""
Perform a group by/count on all user types.
:return: List of results
"... |
Add <yo-rc.json> to <configuring> priority | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.generators.Base.extend({
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the doozie ' + chalk.red... | 'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = yeoman.generators.Base.extend({
prompting: function () {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the doozie ' + chalk.red... |
Fix TicketedEventType import to not flush search | <?php
namespace App\Console\Commands\Import;
use App\Models\Membership\TicketedEventType;
class ImportTicketedEventTypesFull extends AbstractImportCommand
{
protected $signature = 'import:events-ticketed-types-full
{--y|yes : Answer "yes" to all prompts}';
protected $description... | <?php
namespace App\Console\Commands\Import;
use App\Models\Membership\TicketedEventType;
class ImportTicketedEventTypesFull extends AbstractImportCommand
{
protected $signature = 'import:events-ticketed-types-full
{--y|yes : Answer "yes" to all prompts}';
protected $description... |
Use develop for djsonb repository | #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = []
setup(
name='ashlar',
version='0.0.2',
description='Define and validate schemas for metadata for geotemporal event records',
author='Azavea, Inc.',
author_email='info@azavea.com',
keywords='gis jsonschema',
... | #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = []
setup(
name='ashlar',
version='0.0.2',
description='Define and validate schemas for metadata for geotemporal event records',
author='Azavea, Inc.',
author_email='info@azavea.com',
keywords='gis jsonschema',
... |
Revert "Attempt to fix provider injection"
This reverts commit 436801481c2aab67a2b55521a32a476cd88687dc. | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative ... | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative ... |
Remove spurious no cover pragma |
import numpy as np
from fastats.core.decorator import fs
def value(x):
return x
@fs
def single_pass(x):
"""
Performs a single iteration over the first
dimension of `x`.
Tests
-----
>>> def square(x):
... return x * x
>>> data = np.arange(10)
>>> single_pass(data, value... |
import numpy as np
from fastats.core.decorator import fs
def value(x): # pragma: no cover
return x
@fs
def single_pass(x):
"""
Performs a single iteration over the first
dimension of `x`.
Tests
-----
>>> def square(x):
... return x * x
>>> data = np.arange(10)
>>> sin... |
Update crossfilter to gray/blue scheme
Same as in https://vega.github.io/editor/#/examples/vega-lite/interactive_layered_crossfilter | """
Interactive Crossfilter
=======================
This example shows a multi-panel view of the same data, where you can interactively
select a portion of the data in any of the panels to highlight that portion in any
of the other panels.
"""
# category: interactive charts
import altair as alt
from vega_datasets impor... | """
Interactive Crossfilter
=======================
This example shows a multi-panel view of the same data, where you can interactively
select a portion of the data in any of the panels to highlight that portion in any
of the other panels.
"""
# category: interactive charts
import altair as alt
from vega_datasets impor... |
Fix typo (exists -> exits) | package main
import (
"flag"
"fmt"
"os"
"time"
_ "github.com/jackwilsdon/svnwatch/types"
)
func fatalf(format interface{}, a ...interface{}) {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...))
os.Exit(1)
}
func main() {
configDir := flag.String("config", "/etc/svnwatch", ... | package main
import (
"flag"
"fmt"
"os"
"time"
_ "github.com/jackwilsdon/svnwatch/types"
)
func fatalf(format interface{}, a ...interface{}) {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...))
os.Exit(1)
}
func main() {
configDir := flag.String("config", "/etc/svnwatch", ... |
Add a note about repushing app for env to take effect
Signed-off-by: Damien Le Berrigaud <99e6b749acbfbe2a596df99e91d24d6e1fdbee00@pivotallabs.com> | package commands
import (
"cf/api"
"cf/configuration"
term "cf/terminal"
"github.com/codegangsta/cli"
)
type SetEnv struct {
ui term.UI
appRepo api.ApplicationRepository
}
func NewSetEnv(ui term.UI, appRepo api.ApplicationRepository) (se SetEnv) {
se.ui = ui
se.appRepo = appRepo
return
}
func (se SetE... | package commands
import (
"cf/api"
"cf/configuration"
term "cf/terminal"
"github.com/codegangsta/cli"
)
type SetEnv struct {
ui term.UI
appRepo api.ApplicationRepository
}
func NewSetEnv(ui term.UI, appRepo api.ApplicationRepository) (se SetEnv) {
se.ui = ui
se.appRepo = appRepo
return
}
func (se SetE... |
Switch to memcachier dev plan | import logging
import os
import json
import TileStache
if 'AWS_ACCESS_KEY_ID' in os.environ and \
'AWS_SECRET_ACCESS_KEY' in os.environ:
cache = {
"name": "S3",
"bucket": "telostats-tiles",
"access": os.environ['AWS_ACCESS_KEY_ID'],
"secret": os.environ['AWS_... | import logging
import os
import json
import TileStache
if 'AWS_ACCESS_KEY_ID' in os.environ and \
'AWS_SECRET_ACCESS_KEY' in os.environ:
cache = {
"name": "S3",
"bucket": "telostats-tiles",
"access": os.environ['AWS_ACCESS_KEY_ID'],
"secret": os.environ['AWS_... |
chore(ci): Add console logs for deploy status | var fs = require("fs");
var path = require("path");
var ShopifyAPI = require("shopify-node-api");
var pageId = process.env.SHOPIFY_PAGE_ID;
var Shopify = new ShopifyAPI({
shop: process.env.SHOPIFY_SHOP,
shopify_api_key: process.env.SHOPIFY_API_KEY,
access_token: process.env.SHOPIFY_API_PASSWORD
});
var in... | console.log("Deploying Application...");
var fs = require("fs");
var path = require("path");
var ShopifyAPI = require("shopify-node-api");
var pageId = process.env.SHOPIFY_PAGE_ID;
var Shopify = new ShopifyAPI({
shop: process.env.SHOPIFY_SHOP,
shopify_api_key: process.env.SHOPIFY_API_KEY,
access_token: pro... |
Stop setting routing param in sfRequest | <?php
/*
* This file is part of the Access to Memory (AtoM) software.
*
* Access to Memory (AtoM) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your op... | <?php
/*
* This file is part of the Access to Memory (AtoM) software.
*
* Access to Memory (AtoM) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your op... |
Use shallowEqual to prevent false-positive values | /* @flow */
import { shallowEqual } from 'recompose'
import { objectEach } from 'fela-utils'
import createTheme from './createTheme'
export default function ThemeProviderFactory(
BaseComponent: any,
renderChildren: Function,
statics?: Object
): any {
class ThemeProvider extends BaseComponent {
theme: Obje... | /* @flow */
import { shallowEqual } from 'recompose'
import { objectEach } from 'fela-utils'
import createTheme from './createTheme'
export default function ThemeProviderFactory(
BaseComponent: any,
renderChildren: Function,
statics?: Object
): any {
class ThemeProvider extends BaseComponent {
theme: Obje... |
Migrate deprecated jest testUrl to testEnvironmentOptions.url | // For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
roots: ["<rootDir>/src/main/javascript"],
collectCoverage: false,
collectCoverageFrom: ["**/*.js", "!**/*.{test,spec}.js", "!**/__tests__/**", "!**/WEB-INF/**"],
covera... | // For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
roots: ["<rootDir>/src/main/javascript"],
collectCoverage: false,
collectCoverageFrom: ["**/*.js", "!**/*.{test,spec}.js", "!**/__tests__/**", "!**/WEB-INF/**"],
covera... |
Add model for storing words. | from sqlalchemy import create_engine, Column, Float, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
DeclarativeBase = declarative_base()
def db_connect():
"""
Performs database conn... | from sqlalchemy import create_engine, Column, Float, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
DeclarativeBase = declarative_base()
def db_connect():
"""
Performs database connection using database settings from settings.py.
... |
Remove metadata from special properties list
Metadata was originally put on the special properties list, since we had
plans to ask users to pass metadata in from the API object constructors.
Now that this plan is largely abandoned, there is no need to heed to it.
This commit will remove it from this set.
Signed-off-... | package ksonnet
import (
"log"
"os"
"os/exec"
"strings"
"github.com/ksonnet/ksonnet-lib/ksonnet-gen/kubespec"
)
const constructorName = "new"
var specialProperties = map[kubespec.PropertyName]kubespec.PropertyName{
"apiVersion": "apiVersion",
"kind": "kind",
}
func isSpecialProperty(pn kubespec.Proper... | package ksonnet
import (
"log"
"os"
"os/exec"
"strings"
"github.com/ksonnet/ksonnet-lib/ksonnet-gen/kubespec"
)
const constructorName = "new"
var specialProperties = map[kubespec.PropertyName]kubespec.PropertyName{
"apiVersion": "apiVersion",
"metadata": "metadata",
"kind": "kind",
}
func isSpecial... |
Add Theresa May Jive bot | package co.uk.jiveelection.campaign;
import co.uk.jiveelection.campaign.twit.TwitHelper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import twitter4j.TwitterException;
import java.io.IOException;
/**
* Main entry point for the Jive Campaign... | package co.uk.jiveelection.campaign;
import java.io.IOException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import twitter4j.TwitterException;
import co.uk.jiveelection.campaign.twit.TwitHelper;
/**
* Main entry point for the Jive Campaign application. Sets up a continuously running loop t... |
Change admin attribute to sysadmin | from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Route(entity.Entity, db.Model):
# TODO(samueldmq): recheck string lengths for below attributes
# TODO(samueldmq): add an 'active' attribute
attributes = ['id', 'name', 'url', 'm... | from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Route(entity.Entity, db.Model):
# TODO(samueldmq): recheck string lengths for below attributes
# TODO(samueldmq): add an 'active' attribute
attributes = ['id', 'name', 'url', 'm... |
Add name regex test and mail validation | describe('Users', function() {
describe('Creation', function () {
context('When creating a new user', function() {
var some_guy = jsf(mocks.user);
it('Should have an id', function() {
some_guy.should.have.property('userId');
some_guy.userId.should.be.ok();
some_guy.userId.sho... | describe('Users', function() {
describe('Creation', function () {
context('When creating a new user', function() {
var some_guy = jsf(mocks.user);
it('Should have an id', function() {
some_guy.should.have.property('userId');
some_guy.userId.should.be.ok();
some_guy.userId.sho... |
Fix ntee -h/--help not showing right name and version and showing cli's ones instead | #!/usr/bin/env node
var cli = require('cli').enable('version').setApp('./package.json');
var fs = require('fs');
var path = require('path');
var cwd = process.cwd();
var options = cli.parse({
'append': ['a', 'append to the given FILEs, do not overwrite'],
'ignore-interrupts': ['i', 'igno... | #!/usr/bin/env node
var cli = require('cli').enable('version');
var fs = require('fs');
var path = require('path');
var cwd = process.cwd();
var options = cli.parse({
'append': ['a', 'append to the given FILEs, do not overwrite'],
'ignore-interrupts': ['i', 'ignore interrupt signals'],
... |
Remove check for translation files
There is no reason why crash whole app when extension is not configured | <?php
namespace GettextTranslator\DI;
use Nette\DI\CompilerExtension;
use Nette\DI\ContainerBuilder;
if (!class_exists('Nette\DI\CompilerExtension'))
{
class_alias('Nette\Config\CompilerExtension', 'Nette\DI\CompilerExtension');
}
class Extension extends CompilerExtension
{
/** @var array */
private $defaults... | <?php
namespace GettextTranslator\DI;
use Nette;
if (!class_exists('Nette\DI\CompilerExtension'))
{
class_alias('Nette\Config\CompilerExtension', 'Nette\DI\CompilerExtension');
}
class Extension extends Nette\DI\CompilerExtension
{
/** @var array */
private $defaults = array(
'lang' => 'en',
'fil... |
Fix small bug in templatetags | from django import template
from ..models import Post, Section
register = template.Library()
@register.assignment_tag
def latest_blog_posts(scoper=None):
qs = Post.objects.current()
if scoper:
qs = qs.filter(blog__scoper=scoper)
return qs[:5]
@register.assignment_tag
def latest_blog_post(scop... | from django import template
from ..models import Post, Section
register = template.Library()
@register.assignment_tag
def latest_blog_posts(scoper=None):
qs = Post.objects.current()
if scoper:
qs = qs.filter(scoper=scoper)
return qs[:5]
@register.assignment_tag
def latest_blog_post(scoper=Non... |
Remove debugging print statement from changeMarginWidth | from PyQt5.Qsci import QsciScintilla, QsciLexerPython
class TextArea(QsciScintilla):
def __init__(self):
super().__init__()
self.filePath = "Untitled"
self.pythonLexer = QsciLexerPython(self)
self.setLexer(self.pythonLexer)
self.setMargins(1)
self.setMarginType(0,... | from PyQt5.Qsci import QsciScintilla, QsciLexerPython
class TextArea(QsciScintilla):
def __init__(self):
super().__init__()
self.filePath = "Untitled"
self.pythonLexer = QsciLexerPython(self)
self.setLexer(self.pythonLexer)
self.setMargins(1)
self.setMarginType(0,... |
Make entity repo compatible with parent | <?php
namespace Knp\RadBundle\Doctrine;
use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;
abstract class EntityRepository extends BaseEntityRepository
{
public function __call($method, $arguments)
{
if (0 === strpos($method, 'find')) {
if (method_ex... | <?php
namespace Knp\RadBundle\Doctrine;
use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;
abstract class EntityRepository extends BaseEntityRepository
{
public function __call($method, array $arguments = array())
{
if (0 === strpos($method, 'find')) {
... |
Fix DebugToolbar requirement in non-debug envs | import functools
import os
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask_app.app import app
from flask_app.models import db
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
_FROM_HERE = functools.partial(os.path.joi... | import functools
import os
from flask.ext.debugtoolbar import DebugToolbarExtension
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask_app.app import app
from flask_app.models import db
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', Mi... |
Enable generic tests on Windows
The build line excluding windows was inadvertent. | package liner
import (
"bytes"
"strings"
"testing"
)
func TestHistory(t *testing.T) {
input := `foo
bar
baz
quux
dingle`
var s State
num, err := s.ReadHistory(strings.NewReader(input))
if err != nil {
t.Fatal("Unexpected error reading history", err)
}
if num != 5 {
t.Fatal("Wrong number of history entri... | // +build !windows
package liner
import (
"bytes"
"strings"
"testing"
)
func TestHistory(t *testing.T) {
input := `foo
bar
baz
quux
dingle`
var s State
num, err := s.ReadHistory(strings.NewReader(input))
if err != nil {
t.Fatal("Unexpected error reading history", err)
}
if num != 5 {
t.Fatal("Wrong num... |
Add test to ensure all the views have assigned an eventManager
This test ensure that current eventManager bubbling logic performs correctly | var set = Em.set;
var get = Em.get;
module("Em.View extensions", {
setup: function() {
Em.Gestures.register('viewTestGesture',Em.Object.extend());
},
teardown: function() {
Em.Gestures.unregister('viewTestGesture');
}
});
test("should detect gesture", function() {
var view = Em.View.create({
... | var set = Em.set;
var get = Em.get;
module("Em.View extensions", {
setup: function() {
Em.Gestures.register('viewTestGesture',Em.Object.extend());
},
teardown: function() {
Em.Gestures.unregister('viewTestGesture');
}
});
test("should detect gesture", function() {
var view = Em.View.create({
... |
Use deprecated method to ensure we don't break with older versions of jackson | package com.bugsnag.serialization;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.OutputStream;
public class Serializer {
private ObjectMapper mapper = new ... | package com.bugsnag.serialization;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.OutputStream;
public class Serializer {
private ObjectMapper mapper = new ... |
[AC-6976] Remove physical_address from factory, not sure why this helps | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from factory import (
DjangoModelFactory,
Sequence,
)
from accelerator.apps import AcceleratorConfig
ProgramFamily = swapper.load_model(AcceleratorConfig.name, 'ProgramFamily')
class ProgramFamily... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from factory import (
DjangoModelFactory,
Sequence,
)
from accelerator.apps import AcceleratorConfig
ProgramFamily = swapper.load_model(AcceleratorConfig.name, 'ProgramFamily')
class ProgramFamily... |
Move sidebar to the left | <?php /* @var $this Controller */ ?>
<?php $this->beginContent('//layouts/main'); ?>
<div class="row">
<div class="span3">
<div id="sidebar">
<?php
$this->beginWidget('zii.widgets.CPortlet', array(
'title'=>'Operations',
));
$this->widget(... | <?php /* @var $this Controller */ ?>
<?php $this->beginContent('//layouts/main'); ?>
<div class="row">
<div class="span9">
<div id="content">
<?php echo $content; ?>
</div><!-- content -->
</div>
<div class="span3">
<div id="sidebar">
<?php
... |
Make sure bot jobs can be deserialized | """Heroku web worker."""
import os
import redis
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__': # pragma: nocover
# These imports are inside the __main__ block
# to make sure that we only import fr... | """Heroku web worker."""
import os
import redis
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__': # pragma: nocover
# These imports are inside the __main__ block
# to make sure that we only import fr... |
Fix typo in variable name. | import "../core/global";
import "../net/parseURLQueryTerms"
var sn_env = {
debug : false,
host : 'data.solarnetwork.net',
tls : (function() {
return (global !== undefined
&& global.location !== undefined
&& global.location.protocol !== undefined
&& global.location.protocol.toLowerCase().indexOf('https') ... | import "../core/global";
import "../net/parseURLQueryTerms"
var sn_env = {
debug : false,
host : 'data.solarnetwork.net',
tls : (function() {
return (global !== undefined
&& global.locaion !== undefined
&& global.location.protocol !== undefined
&& global.location.protocol.toLowerCase().indexOf('https')... |
Add trove classifiers for supported Python versions | from distutils.core import setup
import re
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("axiom/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
setup(
name="Axiom",
version=version,
description="An in-process object-relational database",... | from distutils.core import setup
import re
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("axiom/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
setup(
name="Axiom",
version=version,
description="An in-process object-relational database",... |
Update to pass live server url as param to protractor | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
... |
Change url for media list api | from django.conf.urls import url, include
from nimbus.apps import debug_urls
from . import views
urlpatterns = debug_urls()
urlpatterns += [
url(r"^$", views.api_root, name="api_root"),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth$', 'rest_framewor... | from django.conf.urls import url, include
from nimbus.apps import debug_urls
from . import views
urlpatterns = debug_urls()
urlpatterns += [
url(r"^$", views.api_root, name="api_root"),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth$', 'rest_framewor... |
Make anyone importing DIALS aware of !2.7 support
Warning is only shown on first import, and can be silenced in Python 2.7 with
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import dials
cf. #1175 | from __future__ import absolute_import, division, print_function
import logging
import sys
import warnings
if sys.version_info.major == 2:
warnings.warn(
"Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. "
"For more information on Python 2.7 support please... | from __future__ import absolute_import, division, print_function
import logging
import sys
import warnings
if sys.version_info.major == 2:
warnings.warn(
"Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. "
"For more information on Python 2.7 support please... |
Update the sequence alignment example. | from alignment.sequence import Sequence
from alignment.vocabulary import Vocabulary
from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner
# Create sequences to be aligned.
a = Sequence("what a beautiful day".split())
b = Sequence("what a disappointingly bad day".split())
print "Sequence A:", a
pr... | # Create sequences to be aligned.
from alignment.sequence import Sequence
a = Sequence("what a beautiful day".split())
b = Sequence("what a disappointingly bad day".split())
print "Sequence A:", a
print "Sequence B:", b
print
# Create a vocabulary and encode the sequences.
from alignment.vocabulary import Vocabulary
v... |
Update test to mock stripes-loader alias | import mockReq from 'mock-require';
import chai from 'chai';
import { shallow } from 'enzyme';
import Match from 'react-router/Match';
chai.should();
global.OKAPI_URL = 'http://localhost:9130';
mockReq('stripes-loader', { modules: {
app: [ {
displayName: 'someApp',
module: 'some-app',
getModule: () =>... | import mockReq from 'mock-require';
import chai from 'chai';
import { shallow } from 'enzyme';
import Match from 'react-router/Match';
chai.should();
global.OKAPI_URL = 'http://localhost:9130';
mockReq('stripes-loader!', { modules: {
app: [ {
displayName: 'someApp',
module: 'some-app',
getModule: () =... |
Clean up JS a bit | (function() {
'use strict';
var $sidebarButtonA = $('.sidebar-header-bills');
var $sidebarButtonB = $('.sidebar-header-resources');
var $sidebarContentA = $('.sidebar-content-bills');
var $sidebarContentB = $('.sidebar-content-resources');
function toggleBillSearch() {
$sidebarContentA.toggleClass('co... | $(function () {
'use strict';
var sidebarButtonA = $('.sidebar-header-bills');
var sidebarButtonB = $('.sidebar-header-resources');
var sidebarContentA = $('.sidebar-content-bills');
var sidebarContentB = $('.sidebar-content-resources');
function toggleBillSearch() {
sidebarContentA.toggleClass('colla... |
Fix jsdoc to pass lint | /**
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://... | /**
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://... |
Use mock instead of own class |
import os
import pytest
import requests
from cisco_olt_http import operations
from cisco_olt_http.client import Client
@pytest.fixture
def data_dir():
return os.path.abspath(
os.path.join(os.path.dirname(__file__), 'data'))
def test_get_data():
client = Client('http://base-url')
show_equipment_... |
import os
import pytest
from cisco_olt_http import operations
from cisco_olt_http.client import Client
@pytest.fixture
def data_dir():
return os.path.abspath(
os.path.join(os.path.dirname(__file__), 'data'))
def test_get_data():
client = Client('http://base-url')
show_equipment_op = operations.... |
Add namespace for products client | <?php
namespace WoowUp;
use WoowUp\Endpoints\Purchases;
use WoowUp\Endpoints\Users;
use WoowUp\Endpoints\Products;
class Client
{
const HOST = 'https://api.woowup.com';
const VERSION = 'apiv3';
protected $http;
public $purchases;
public $mailings;
public $users;
public $segments;
... | <?php
namespace WoowUp;
use WoowUp\Endpoints\Purchases;
use WoowUp\Endpoints\Users;
class Client
{
const HOST = 'https://api.woowup.com';
const VERSION = 'apiv3';
protected $http;
public $purchases;
public $mailings;
public $users;
public $segments;
public $products;
public f... |
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... |
Fix GORM v1 compile error | package utils
import (
"fmt"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
// TestDB initialize a db for testing
func TestDB() *gorm.DB {
dbuser, dbpwd, dbname := "qor", "qor", "qor_test"
if os.Getenv("TEST_ENV") == "CI" {
dbuser, dbpwd = os.Getenv("DB_USER"), os.... | package utils
import (
"fmt"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
// TestDB initialize a db for testing
func TestDB() *gorm.DB {
dbuser, dbpwd, dbname := "qor", "qor", "qor_test"
if os.Getenv("TEST_ENV") == "CI" {
dbuser, dbpwd = os.Getenv("DB_USER"), os.... |
Modify board_slug in url regex to pass numeric letter | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new... | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_p... |
Switch Workbox strategy from StaleWhileRevalidate to NetworkFirst | importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');
workbox.core.skipWaiting();
workbox.precaching.precacheAndRoute([]);
workbox.precaching.precache([
'/offline/',
'/static/images/avatar.jpg?cloudinary=w_200,f_auto',
'/static/images/avatar.jpg?cloudinary=w_40,f_auto'
]... | importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');
workbox.core.skipWaiting();
workbox.precaching.precacheAndRoute([]);
workbox.precaching.precache([
'/offline/',
'/static/images/avatar.jpg?cloudinary=w_200,f_auto',
'/static/images/avatar.jpg?cloudinary=w_40,f_auto'
]... |
Raise word limit by 50% | import os
import json
from random import randrange, seed, sample
MAX_LEN = 75
def shift(s, new):
space = s.find(' ')
if space == -1:
raise Exception('bad shift string ' + s)
return s[space+1:] + ' ' + new
def main():
getw = lambda arr: sample(arr, 1)[0]
words = {}
starters = 0
... | import os
import json
from random import randrange, seed, sample
MAX_LEN = 50
def shift(s, new):
space = s.find(' ')
if space == -1:
raise Exception('bad shift string ' + s)
return s[space+1:] + ' ' + new
def main():
getw = lambda arr: sample(arr, 1)[0]
words = {}
starters = 0
... |
Improve html markup of added item | // activity item template
var itemtemplate = ['<li class="activity-item">',
'<a href="{{modifier_url}}">',
'<img src="{{modifier_siteicon}}" />',
'</a>',
'<div>',
'<p>',
'<a href="{{modifier_url}}">{{modifier}}</a> is {{action}} ',
'<a class="tiddler-title" href="{{tiddler_url}}">{{tiddler_title}}</a>',
... | // activity item template
var itemtemplate = ['<div class="activity-item">',
'<a href="{{modifier_url}}">',
'<img src="{{modifier_siteicon}}" />',
'</a>',
'<div>',
'<p>',
'<a href="{{modifier_url}}">{{modifier}}</a> is {{action}} ',
'<a class="tiddler-title" href="{{tiddler_url}}">{{tiddler_title}}</a>',
... |
Make ubiquity work with at other paths than the base path | exports.addClassName = function(element, className) {
if (!(' ' + element.className + ' ').match(' ' + className + ' ')) {
element.className += className + ' ';
}
}
exports.removeClassName = function(element, className) {
className += ' ';
var current = element.className;
var index = current.indexOf(className);... | exports.addClassName = function(element, className) {
if (!(' ' + element.className + ' ').match(' ' + className + ' ')) {
element.className += className + ' ';
}
}
exports.removeClassName = function(element, className) {
className += ' ';
var current = element.className;
var index = current.indexOf(className);... |
Fix problem rendering oneof() predicate when the members aren't strings | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(memb... | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf(members)
class... |
Fix app files test on windows | package cf_test
import (
. "cf"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"path/filepath"
"path"
)
var _ = Describe("AppFiles", func() {
fixturePath := filepath.Join("..", "fixtures", "applications")
Describe("AppFilesInDir", func() {
It("all files have '/' path separators", func() {
files, e... | package cf_test
import (
. "cf"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"path/filepath"
)
var _ = Describe("AppFiles", func() {
fixturePath := filepath.Join("..", "fixtures", "applications")
Describe("AppFilesInDir", func() {
It("all files have '/' path separators", func() {
files, err := Ap... |
Add hexdec filter for Twig | <?php
namespace Scat;
class TwigExtension
extends \Twig\Extension\AbstractExtension
implements \Twig\Extension\GlobalsInterface
{
public function getGlobals() {
return [
'DEBUG' => $GLOBALS['DEBUG'],
'PUBLIC' => ORDURE,
'PUBLIC_CATALOG' => ORDURE . '/art-supplies',
'STATIC' => ORDURE_... | <?php
namespace Scat;
class TwigExtension
extends \Twig\Extension\AbstractExtension
implements \Twig\Extension\GlobalsInterface
{
public function getGlobals() {
return [
'DEBUG' => $GLOBALS['DEBUG'],
'PUBLIC' => ORDURE,
'PUBLIC_CATALOG' => ORDURE . '/art-supplies',
'STATIC' => ORDURE_... |
Allow running gulp install as root | var alloy = require('../.alloy');
var gulp = require('gulp');
var path = require('path');
var replace = require('gulp-replace');
var run = require('run-sequence');
var spawn = require('spawn-local-bin');
var ROOT = path.join(__dirname, '..');
gulp.task('init', function(callback) {
run('init-bower', 'init-npm', 'i... | var alloy = require('../.alloy');
var gulp = require('gulp');
var path = require('path');
var replace = require('gulp-replace');
var run = require('run-sequence');
var spawn = require('spawn-local-bin');
var ROOT = path.join(__dirname, '..');
gulp.task('init', function(callback) {
run('init-bower', 'init-npm', 'i... |
server: Add Authorization to Access-Control-Allow-Headers list. | package org.opencb.opencga.server;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by pfurio on 04/10/16.
*/
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig fil... | package org.opencb.opencga.server;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by pfurio on 04/10/16.
*/
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig fil... |
Adjust MorphForm textarea boxes to fill available height | import * as v from '../../styles/variables'
const styles = {
section: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-between',
alignItems: 'stretch',
alignContent: 'flex-start',
width: '100%'
},
container: {
position: 'relative',
width: '100%',
height: `calc(100% ... | import * as v from '../../styles/variables'
const styles = {
section: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-between',
alignItems: 'stretch',
alignContent: 'flex-start',
width: '100%'
},
container: {
position: 'relative',
width: '100%'
},
dataInput: {
... |
Reorganize for 100% for UserToken. | <?php
namespace inklabs\kommerce\Entity;
class UserTokenTest extends \PHPUnit_Framework_TestCase
{
public function testCreate()
{
$userToken = new UserToken;
$userToken->setUserAgent('UserAgent');
$userToken->setToken('token');
$userToken->setType('type');
$userToken->se... | <?php
namespace inklabs\kommerce\Entity;
class UserTokenTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->userToken = new UserToken;
$this->userToken->setUserAgent('XXX');
$this->userToken->setToken('XXX');
$this->userToken->setType('XXX');
$thi... |
Update command to work with sublime 3 | import json
import urllib
import sublime
import sublime_plugin
GIST_URL = 'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa
class UpdateUserSettingsCommand(sublime_plugin.TextCommand):
def run(self, edit):
gist_settings = self._get_set... | import json
import urllib2
import sublime
import sublime_plugin
GIST_URL = u'https://raw.githubusercontent.com/RomuloOliveira/dot-files/master/sublime/User/Preferences.sublime-settings' # noqa
class UpdateUserSettingsCommand(sublime_plugin.TextCommand):
def run(self, edit):
gist_settings = self._g... |
Fix forgot to make coffeescript :-) | // Generated by CoffeeScript 1.9.3
(function() {
var $, Radio, initCordova;
$ = require('jquery');
Radio = require('backbone.radio');
initCordova = function() {
var eventName, i, len, ref;
$(document).on('deviceready', function() {
return require('./cordova/ios_network_activity').init();
})... | // Generated by CoffeeScript 1.9.3
(function() {
var $, Radio, initCordova;
$ = require('jquery');
Radio = require('backbone.radio');
initCordova = function() {
var eventName, i, len, ref;
$(document).on('deviceready', function() {
return require('./cordova/ios_network_activity').init();
})... |
Handle GitHub's updated Content Security Policy
It looks like GitHub changed their CSP recently. This extension didn't work for me until I added this code. | // this idea borrowed from
// https://www.planbox.com/blog/development/coding/bypassing-githubs-content-security-policy-chrome-extension.html
chrome.webRequest.onHeadersReceived.addListener(function(details) {
for (i = 0; i < details.responseHeaders.length; i++) {
if (isCSPHeader(details.responseHeaders[i].name... | // this idea borrowed from
// https://www.planbox.com/blog/development/coding/bypassing-githubs-content-security-policy-chrome-extension.html
chrome.webRequest.onHeadersReceived.addListener(function(details) {
for (i = 0; i < details.responseHeaders.length; i++) {
if (isCSPHeader(details.responseHeaders[i].name... |
Add method to get the content as a string which is required for message manipulations in runtime | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/li... | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/li... |
Load messages and set local properly
Fixes missing uiv translations in plugin repo | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vue2Filters from 'vue2-filters'
import VueCookies from 'vue-cookies'
import VueScrollTo from 'vue-scrollto'
import VueFuse from 'vue-fuse'
import VueI1... | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vue2Filters from 'vue2-filters'
import VueCookies from 'vue-cookies'
import VueScrollTo from 'vue-scrollto'
import VueFuse from 'vue-fuse'
import VueI1... |
Fix last commit: use config.log() | #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChil... | #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChil... |
Add test case for OnlineStatistics where axis is a tuple | import numpy as np
from nose2 import tools
import utils
@tools.params(((1000, 25), 10, 0),
((1000, 25), 10, 1),
((1000, 25), 77, 0),
((1000, 1, 2, 3), 10, (0, 3))
)
def test_online_statistics(shape, batch_size, axis):
online_stats = utils.OnlineStatistics(ax... | import numpy as np
from nose2 import tools
import utils
@tools.params(((1000, 25), 10, 0),
((1000, 25), 10, 1),
((1000, 25), 77, 0)
)
def test_online_statistics(shape, batch_size, axis):
online_stats = utils.OnlineStatistics(axis=axis)
X = np.random.random(shape)
... |
Use / as the primary delimiter in compound key
We want to avoid confusion between kebab_case'd model names,
and components of the compound key. If for some reason a dev
wants to parse the compound key (i.e. the Solr key) into parts,
using a different top-level delimiter will ease this process. | <?php
namespace App\Shop;
use Illuminate\Database\Eloquent\Model;
use App\Scopes\SortByLastUpdatedScope;
use Laravel\Scout\Searchable;
class ShopModel extends Model
{
use Searchable;
public $incrementing = false;
protected $primaryKey = 'shop_id';
protected $dates = ['source_created_at', 'source_... | <?php
namespace App\Shop;
use Illuminate\Database\Eloquent\Model;
use App\Scopes\SortByLastUpdatedScope;
use Laravel\Scout\Searchable;
class ShopModel extends Model
{
use Searchable;
public $incrementing = false;
protected $primaryKey = 'shop_id';
protected $dates = ['source_created_at', 'source_... |
Fix typo for named argument | import tensorflow as tf
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.r... | import tensorflow as tf
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, lables=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.r... |
Add RPI3B+ support and remove IMX6UL
Update samples to add RPI3B+ and remove IMX6UL support.
Bug: 112590677
Bug: 112603667
Change-Id: I99d174bf17bc75e1d17192bc1e1227c97f85d171 | /*
* Copyright 2016, The Android Open Source Project
*
* 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 applic... | /*
* Copyright 2016, The Android Open Source Project
*
* 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 applic... |
Improve comment around transformed attributes | import { Component, Children, PropTypes } from "react";
import withSideEffect from "react-side-effect";
const supportedHTML4Attributes = {
"bgColor": "bgcolor"
};
class BodyAttributes extends Component {
render() {
return Children.only(this.props.children);
}
}
BodyAttributes.propTypes = {
children: Pro... | import { Component, Children, PropTypes } from "react";
import withSideEffect from "react-side-effect";
const supportedHTML4Attributes = {
"bgColor": "bgcolor"
};
class BodyAttributes extends Component {
render() {
return Children.only(this.props.children);
}
}
BodyAttributes.propTypes = {
children: Pro... |
Remove 'b' classifer on FileToList's read() usage | """
Class for FileToList
"""
class FileToList(object):
"""
FileToList is a helper class used to import text files and turn them into
lists, with each index in the list representing a single line from the
text file.
"""
@staticmethod
def to_list(file_path):
"""
Static method... | """
Class for FileToList
"""
class FileToList(object):
"""
FileToList is a helper class used to import text files and turn them into
lists, with each index in the list representing a single line from the
text file.
"""
@staticmethod
def to_list(file_path):
"""
Static method... |
Add more accurate time to unit observations | import React from 'react';
import moment from 'moment';
import {translate} from 'react-i18next';
const formatTime = (time: Date, t: Function) => {
const now = moment();
let lookup = 'TIME.';
let options = {};
if(now.diff(time, 'days') === 0) {
lookup += 'TODAY';
} else if (now.diff(time, 'days') === 1) ... | import React from 'react';
import moment from 'moment';
import {translate} from 'react-i18next';
const formatTime = (time: Date, t: Function) => {
const now = moment();
let lookup = 'TIME.';
let options = {};
if(now.diff(time, 'days') === 0) {
lookup += 'TODAY';
} else if (now.diff(time, 'days') === 1) ... |
Add PERSISTENT option to MySQL connection. | <?php
namespace Jafaripur\DAL;
/**
* Abstract Class MySQLOwnClient for using MySQL
*
* Each of model want to use MySQL should extend from this class
*
* @author A.Jafaripur <mjafaripur@yahoo.com>
*
*/
abstract class MySQLOwnClient extends \PDO {
const SERVER = 'localhost';
const USERNAME =... | <?php
namespace Jafaripur\DAL;
/**
* Abstract Class MySQLOwnClient for using MySQL
*
* Each of model want to use MySQL should extend from this class
*
* @author A.Jafaripur <mjafaripur@yahoo.com>
*
*/
abstract class MySQLOwnClient extends \PDO {
const SERVER = 'localhost';
const USERNAME =... |
Expand default testing on new object types | import cybox.utils
class ObjectTestCase(object):
"""A base class for testing all subclasses of ObjectProperties.
Each subclass of ObjectTestCase should subclass both unittest.TestCase
and ObjectTestCase, and defined two class-level fields:
- klass: the ObjectProperties subclass being tested
- obj... | import cybox.utils
class ObjectTestCase(object):
"""A base class for testing all subclasses of ObjectProperties.
Each subclass of ObjectTestCase should subclass both unittest.TestCase
and ObjectTestCase, and defined two class-level fields:
- klass: the ObjectProperties subclass being tested
- obj... |
[INTERNAL] CardExplorer: Use correct path in Custom Actions sample
Change-Id: I73b3f8aadd7b375267435e0b43cc1376c0d3447f
BCP: 2080456866 | sap.ui.define(["sap/ui/integration/Extension", "sap/ui/integration/ActionDefinition"], function (Extension, ActionDefinition) {
"use strict";
var CustomActionsExtension = Extension.extend("card.explorer.extension.customActions.CustomActionsExtension");
CustomActionsExtension.prototype.onCardReady = function () {
... | sap.ui.define(["sap/ui/integration/Extension", "sap/ui/integration/ActionDefinition"], function (Extension, ActionDefinition) {
"use strict";
var CustomActionsExtension = Extension.extend("card.explorer.extension.customActions.CustomActionsExtension");
CustomActionsExtension.prototype.onCardReady = function () {
... |
Fix errors cause by key error in sys.modules and wrong type error by uFid. | import importlib
import importlib.machinery
import sys
from module import Module
import json
def message_to_function(raw_message):
"""
converting json formatted string to a executable module.
Args:
raw_message (str): json formatted.
Returns:
None if raw_message is in wrong format, ... | import importlib
import importlib.machinery
import sys
from module import Module
import json
def message_to_function(raw_message):
"""
converting json formatted string to a executable module.
Args:
raw_message (str): json formatted.
Returns:
None if raw_message is in wrong format, ... |
Update test runner syntax to the new arista-transcode syntax and always output a status report even if the user stops the tests early. | #!/usr/bin/env python
"""
Run Arista Transcode Tests
==========================
Generate test files in various formats and transcode them to all available
output devices and qualities.
"""
import os
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import arista; arista.init... | #!/usr/bin/env python
"""
Run Arista Transcode Tests
==========================
Generate test files in various formats and transcode them to all available
output devices and qualities.
"""
import os
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import arista; arista.init... |
Switch from bold to red highlighting.
With many terminal fonts bold is subtle. The red is much more clear. | # Copyright Google
# BSD License
import copy
import wash
# from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033... | # Copyright Google
# BSD License
import copy
import wash
# from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033... |
Add designer photo and location to designer page. | @extends('layout.app', [
'title' => $designer->getTranslation()->name . ' - Designer',
'body_id' => 'designer-page',
'body_class' => 'designer-page',
])
@section('content')
@if (!Auth::guest())
<div id="action-bar">
<div class="container">
<a href="{{ url('/designer/'.$designer->id... | @extends('layout.app', [
'title' => $designer->getTranslation()->name . ' - Designer',
'body_id' => 'designer-page',
'body_class' => 'designer-page',
])
@section('content')
@if (!Auth::guest())
<div class="container">
<a href="{{ url('/designer/'.$designer->id.'/edit') }}"
id="edit-button" cl... |
Add case of escape branch for newMatcher | package main
import (
"reflect"
"regexp"
"testing"
)
var genMatcherTests = []struct {
src string
dst *regexp.Regexp
}{
{"abc", regexp.MustCompile(`(abc)`)},
{"a,b", regexp.MustCompile(`(a|b)`)},
{"a\\,b", regexp.MustCompile(`(a,b)`)},
}
func TestGenMatcher(t *testing.T) {
for _, test := range genMatcherTe... | package main
import (
"reflect"
"regexp"
"testing"
)
var genMatcherTests = []struct {
src string
dst *regexp.Regexp
}{
{"abc", regexp.MustCompile(`(abc)`)},
{"a,b", regexp.MustCompile(`(a|b)`)},
}
func TestGenMatcher(t *testing.T) {
for _, test := range genMatcherTests {
expect := test.dst
actual, err :... |
Fix sourcemap for dev mode | module.exports = {
entry: {
javascript: "./app/app.jsx"
},
output: {
path: __dirname,
filename: "bundle.js"
},
resolve: {
extensions: ["", ".json", ".js", ".jsx"]
},
module: {
noParse: [/autoit.js/],
loaders: [
{
... | module.exports = {
entry: {
javascript: "./app/app.jsx"
},
output: {
path: __dirname,
filename: "bundle.js"
},
resolve: {
extensions: ["", ".json", ".js", ".jsx"]
},
module: {
noParse: [/autoit.js/],
loaders: [
{
... |
Add multiple permissions to a single export | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... | '''
Module for managing NFS.
'''
# Import python libs
import logging
import salt.utils
log = logging.getLogger(__name__)
def __virtual__():
'''
Only work on posix-like systems
'''
# Disable on these platorms, specific service modules exist:
disable = [
'Windows',
]
if not sa... |
Fix for a potential NPE
Signed-off-by: Gorkem Ercan <401a00c042ea0ce3e74815aa3e2dca472ed1e2f8@gmail.com> | /*******************************************************************************
* Copyright (c) 2013, 2014 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is availabl... | /*******************************************************************************
* Copyright (c) 2013, 2014 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is availabl... |
Remove call to `console.log` in build script | 'use strict';
var zone = require('mdast-zone');
var u = require('unist-builder');
var sort = require('alphanum-sort/lib/compare');
var gemoji = require('gemoji').unicode;
var emotion = require('..');
module.exports = support;
function support() {
return transformer;
}
function transformer(tree) {
zone(tree, 'su... | 'use strict';
var zone = require('mdast-zone');
var u = require('unist-builder');
var sort = require('alphanum-sort/lib/compare');
var gemoji = require('gemoji').unicode;
var emotion = require('..');
module.exports = support;
function support() {
return transformer;
}
function transformer(tree) {
zone(tree, 'su... |
Make call to wordpress installation (TODO: mock) | package com.afrozaar.wordpress.wpapi.v2;
import com.afrozaar.wordpress.wpapi.v2.model.Post;
import com.afrozaar.wordpress.wpapi.v2.util.ClientFactory;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
public class Cli... | package com.afrozaar.wordpress.wpapi.v2;
import com.afrozaar.wordpress.wpapi.v2.model.Post;
import com.afrozaar.wordpress.wpapi.v2.util.ClientFactory;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Properties;
public class ClientTest {
@Test
public void foo() {
Asse... |
Add assertion for number of fields on person | from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_peo... | from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_peo... |
Move testing code into "if __name__ == '__main__'" so it's not run on import. | import errno
import hotshot
import hotshot.stats
import os
import sys
import test.pystone
def main(logfile):
p = hotshot.Profile(logfile)
benchtime, stones = p.runcall(test.pystone.pystones)
p.close()
print "Pystone(%s) time for %d passes = %g" % \
(test.pystone.__version__, test.pystone.LOO... | import errno
import hotshot
import hotshot.stats
import os
import sys
import test.pystone
if sys.argv[1:]:
logfile = sys.argv[1]
else:
import tempfile
logf = tempfile.NamedTemporaryFile()
logfile = logf.name
p = hotshot.Profile(logfile)
benchtime, stones = p.runcall(test.pystone.pystones)
p.close()
... |
Test reset on scatter pipe. | package com.tinkerpop.pipes.util;
import com.tinkerpop.pipes.BaseTest;
import com.tinkerpop.pipes.Pipe;
import java.util.Arrays;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class ScatterPipeTest extends BaseTest {
public void testScatterPipe() {
Pipe scatter = new ScatterPip... | package com.tinkerpop.pipes.util;
import com.tinkerpop.pipes.BaseTest;
import com.tinkerpop.pipes.Pipe;
import java.util.Arrays;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class ScatterPipeTest extends BaseTest {
public void testScatterPipe() {
Pipe scatter = new ScatterPip... |
BUGFIX: Add the Generator constructor to the global scope to support Flow generator annotations | module.exports = {
parser: 'babel-eslint',
extends: [
'xo',
'xo-react',
'plugin:jsx-a11y/recommended',
'plugin:promise/recommended',
'plugin:react/recommended',
'plugin:import/errors'
],
plugins: [
'compat',
'promise',
'babel',
'react',
'jsx-a11y'
],
env: {
node: true,
browser: true,
j... | module.exports = {
parser: 'babel-eslint',
extends: [
'xo',
'xo-react',
'plugin:jsx-a11y/recommended',
'plugin:promise/recommended',
'plugin:react/recommended',
'plugin:import/errors'
],
plugins: [
'compat',
'promise',
'babel',
'react',
'jsx-a11y'
],
env: {
node: true,
browser: true,
j... |
FIX end contract depart letter generation | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... |
Add fallback to freetype-config for compatibility. | import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OS... | import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OS... |
Use ejs templates to serve random video |
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
var express = require("express");
var app = express();
var path = require("path");
app.set('view engine', 'ejs');
app.use(express.static(__d... | var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/'));
app.get('/',fun... |
Replace test.done with test.end (patch) | 'use strict'
const tap = require('tap')
const getDokumenter = require('../lib/journals/getDokumenter')
tap.test('Requires options to be specified', function (test) {
const options = false
const expectedErrorMessage = 'Missing required input: options object'
getDokumenter(options, function (error, data) {
ta... | 'use strict'
const tap = require('tap')
const getDokumenter = require('../lib/journals/getDokumenter')
tap.test('Requires options to be specified', function (test) {
const options = false
const expectedErrorMessage = 'Missing required input: options object'
getDokumenter(options, function (error, data) {
ta... |
Check that env variables are present | <?php declare(strict_types=1);
use Discord\Discord;
use Monolog\Logger;
use PHPUnit\Framework\TestCase;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
final class DiscordTest extends TestCase
{
public function testCheckEnvVariablesPresent()
{
$this->assertNotFalse(getenv('DISCORD_TOKE... | <?php declare(strict_types=1);
use Discord\Discord;
use Monolog\Logger;
use PHPUnit\Framework\TestCase;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
final class DiscordTest extends TestCase
{
public function testCanConnect()
{
return wait(function (Discord $discord, $resolve) {
... |
Improve the get_nick a tiny amount | class IRCMessage:
""" Class to store and parse an IRC Message. """
def __init__(self, msg):
""" Parse a raw IRC message to IRCMessage. """
self.sender = None
self.nick = None
self.command = None
self.params = []
self.__parse_msg(msg)
def __parse_msg(self, ... | class IRCMessage:
""" Class to store and parse an IRC Message. """
def __init__(self, msg):
""" Parse a raw IRC message to IRCMessage. """
self.sender = None
self.nick = None
self.command = None
self.params = []
self.__parse_msg(msg)
def __parse_msg(self, ... |
Switch experiment to using Facebook with HTTPS | const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT... | const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT... |
[infrastructure] Allow all valid semvers as commit messages | const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const boxen = require('boxen')
const semver = require('semver')
const commitMsgPath = path.join(__dirname, '..', process.env.GIT_PARAMS)
const msg = fs.readFileSync(commitMsgPath, 'utf8').trim()
const template = /^\[[a-z-\/]+]\s[A-Z0... | const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const boxen = require('boxen')
const childProc = require('child_process')
const commitMsgPath = path.join(__dirname, '..', process.env.GIT_PARAMS)
const msg = fs.readFileSync(commitMsgPath, 'utf8').trim()
const template = /^\[[a-z-\/... |
Convert 'Go Back' from clickable span to button | import React, {PropTypes} from 'react';
import {browserHistory} from 'react-router';
import {HOME_PAGE_URI} from '../../utils/constants';
class Footer extends React.Component {
constructor(props, context) {
super(props, context);
this.redirectToPreviousPage = this.redirectToPreviousPage.bind(this);
}
r... | import React, {PropTypes} from 'react';
import {browserHistory} from 'react-router';
import {HOME_PAGE_URI} from '../../utils/constants';
class Footer extends React.Component {
constructor(props, context) {
super(props, context);
this.redirectToPreviousPage = this.redirectToPreviousPage.bind(this);
}
r... |
Use product_id stored in order item instead of getting it from product instance. | <?php
class SPM_ShopyMind_DataMapper_OrderItem
{
public function format(Mage_Sales_Model_Order_Item $orderItem)
{
$product = $orderItem->getProduct();
$combinationId = $this->getCombinationId($orderItem, $product);
return array(
'id_product' => $orderItem->getProductId(),
... | <?php
class SPM_ShopyMind_DataMapper_OrderItem
{
public function format(Mage_Sales_Model_Order_Item $orderItem)
{
$product = $orderItem->getProduct();
$combinationId = $this->getCombinationId($orderItem, $product);
return array(
'id_product' => $product->getId(),
... |
Use project-routes module to get route for projects. | var mount = require('koa-mount');
var router = require('koa-router')();
var koa = require('koa');
var Bus = require('busmq');
var app = koa();
require('koa-qs')(app);
var ropts = {
db: 'materialscommons',
port: 30815
};
var r = require('rethinkdbdash')(ropts);
var projectsModel = require('./model/db/projects')(... | var mount = require('koa-mount');
var router = require('koa-router')();
var koa = require('koa');
var Bus = require('busmq');
var app = koa();
require('koa-qs')(app);
var ropts = {
db: 'materialscommons',
port: 30815
};
var r = require('rethinkdbdash')(ropts);
var projectsModel = require('./model/db/projects')(... |
scripts: Move JSON dump parameters to a global dictionary. | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
import json
import os
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSO... | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
import json
import os
# Default parameters for JSON input and output
def json_load(fn):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file)
def... |
GBE-113: Add support for mixed geometry type (GEOMETRY_COLLECTION) | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomaja... | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomaja... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.