text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Revert "Update random number generator test"
This reverts commit b63bda37aa2e9b5251cf6c54d59785d2856659ca. | import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
shape = (100, 100)
mx.random.seed(128)
ret1 = mx.random.normal(mu, sigma, shape)
u... | import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
for i in range(5):
shape = (100 + i, 100 + i)
mx.random.seed(128)
ret1... |
Remove unused code in loose. | //>>includeStart('strict', pragmas.strict);
define(['./isImmutable'], function (isImmutable) {
'use strict';
/**
* Extract meta data from a property.
*
* @param {Mixed} prop The property
* @param {String} name The name of the property
*
* @return {Object} An object containg the m... | define(['./isImmutable'], function (isImmutable) {
'use strict';
/**
* Extract meta data from a property.
*
* @param {Mixed} prop The property
* @param {String} name The name of the property
*
* @return {Object} An object containg the metadata
*/
function propertyMeta(pr... |
Format rollbar, add sourcemap in DEV env | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import postcss from 'rollup-plugin-postcss';
import uglify from 'rollup-plugin-uglify';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import pkg from './pac... | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import postcss from 'rollup-plugin-postcss';
import uglify from 'rollup-plugin-uglify';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import pkg from './pac... |
Fix a bug after Last.fm site update | export function getTitle() {
var titleEl = document.querySelector('h1.header-title');
if (titleEl) {
var title = titleEl.textContent;
title = title.trim();
// remove song duration
title = title.replace(/ \(\d{1,2}:\d{1,2}\)$/, '');
title = title.trim();
return... | export function getTitle() {
var titleEl = document.querySelector('h1.header-title');
if (titleEl) {
var title = titleEl.textContent;
title = title.trim();
// remove song duration
title = title.replace(/ \(\d{1,2}:\d{1,2}\)$/, '');
title = title.trim();
return... |
Make wget use system dependent temp folder location | package com.jvm_bloggers.core.rss.fetchers;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import javaslang.control.Option;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
@Slf4j
public class WgetFetcher ... | package com.jvm_bloggers.core.rss.fetchers;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import javaslang.control.Option;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.UUID;
@Component
@Slf4j
pu... |
Document that pop() might return Null | <?php
namespace Kue;
/**
* Interface for Queues
*
* @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com>
*/
interface Queue
{
/**
* Blocks until a job is available, and returns it. This is used by the
* worker script that's shipped with Kue.
*
* @return Job|null Returns either... | <?php
namespace Kue;
/**
* Interface for Queues
*
* @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com>
*/
interface Queue
{
/**
* Blocks until a job is available, and returns it. This is used by the
* worker script that's shipped with Spark.
*
* @return Job
*/
funct... |
Update AudioChannel to create nodes in member function instead of constructor | var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
if(args) {
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wave : "triangle";... | var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
this.oscill.connect(this.gain);
this.gain.connect(this.context.destination);
if(args) {
this.oscill.fre... |
Convert umlaute in slugger urls | const mkdirp = require('mkdirp');
const fs = require('fs');
const dirname = require('path').dirname;
// Create "this-is-a-post" from "This is a Post"
exports.slugger = str => str
.toLowerCase()
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/[^\w ]+/g, ' ')
.replace(/ +/g, '-');
/... | const mkdirp = require('mkdirp');
const fs = require('fs');
const dirname = require('path').dirname;
// Create "this-is-a-post" from "This is a Post"
exports.slugger = str => str.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
// Random logo
exports.logoURL = () => `/img/bisnaer${Math.ceil(Math.random() * ... |
Remove Keras from network splitter
Keras isn't as stable as h5py and json. This commit removes the keras dependency from the network splitting function. | #!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse
def get_args():
d = '(default: %(default)s)'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('model')
parser.add_argument('-w','--weight-fi... | #!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse
def get_args():
d = '(default: %(default)s)'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('model')
parser.add_argument('-w','--weight-fi... |
Correct selecting text by length when text is Unicode. | # This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
... | # This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
... |
Stop looping when currentTarget becomes undefined | const EventKit = require('event-kit')
module.exports =
function listen (element, eventName, selector, handler) {
var innerHandler = function (event) {
if (selector) {
var currentTarget = event.target
while (currentTarget) {
if (currentTarget.matches && currentTarget.matches(selector)) {
... | const EventKit = require('event-kit')
module.exports =
function listen (element, eventName, selector, handler) {
var innerHandler = function (event) {
if (selector) {
var currentTarget = event.target
while (true) {
if (currentTarget.matches && currentTarget.matches(selector)) {
hand... |
Initialize seq without type in drop test class | package com.jmonad.seq;
import org.junit.Test;
public class SeqDropTest {
private Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private Seq<Integer> elements = new Seq<>(numbers);
@Test public void dropListElementsTest() {
assert elements.drop(5).toArrayList().toString().equals("[6, 7, 8, 9, 10]");... | package com.jmonad.seq;
import org.junit.Test;
public class SeqDropTest {
private Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private Seq<Integer> elements = new Seq<Integer>(numbers);
@Test public void dropListElementsTest() {
assert elements.drop(5).toArrayList().toString().equals("[6, 7, 8, 9,... |
Store more pings per transaction | import datetime
from django.core.management.base import BaseCommand, CommandError
from clowder_account.models import Company
from clowder_server.emailer import send_alert
from clowder_server.models import Alert, Ping
class Command(BaseCommand):
help = 'Checks and sends alerts'
def handle(self, *args, **opti... | import datetime
from django.core.management.base import BaseCommand, CommandError
from clowder_account.models import Company
from clowder_server.emailer import send_alert
from clowder_server.models import Alert, Ping
class Command(BaseCommand):
help = 'Checks and sends alerts'
def handle(self, *args, **opti... |
Handle un-loaded images when setting width | !(function () {
'use strict'
// Increase width of images on large screens
Array.from(document.querySelectorAll('.post__body p > img')).forEach(
(image) => {
if (image.naturalWidth) {
testImage(image)
} else {
image.onload = () => testImage(image)
}
}
)
function test... | !(function () {
'use strict'
// Increase width of images on large screens
var images = document.querySelectorAll('.post__body p > img')
for (var i = 0; i < images.length; i++) {
// Only apply to wide images
if (images[i].clientWidth >= 518) {
var wrap = images[i].parentNode
if (wrap.nodeNam... |
Index of the list should be an int | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... |
Improve tag handling in criteria | <?php
namespace Sellsy\Criteria\Generic;
use Sellsy\Criteria\CriteriaInterface;
use Sellsy\Models\SmartTags\TagInterface;
/**
* Class GetListCriteria
* @package Sellsy\Criteria\Generic
*/
abstract class GetListCriteria implements CriteriaInterface
{
/**
* @var array
*/
protected $tags;
/**
... | <?php
namespace Sellsy\Criteria\Generic;
use Sellsy\Criteria\CriteriaInterface;
/**
* Class GetListCriteria
* @package Sellsy\Criteria\Generic
*/
abstract class GetListCriteria implements CriteriaInterface
{
/**
* @var array
*/
protected $tags;
/**
* @param string $tag
* @return $... |
Migrate code for express 4.0 | var express = require('express');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
ap... | var express = require('express');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
app... |
Stop use of almanac() and altazimuth() functions for now. | #!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 30... | #!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 30... |
Refactor entity effect undo control | package com.elmakers.mine.bukkit.api.block;
import java.util.List;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import com.elmakers.mine.bukkit.api.magic.Mage;
public interface UndoList extends BlockList, Comparabl... | package com.elmakers.mine.bukkit.api.block;
import java.util.List;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import com.elmakers.mine.bukkit.api.magic.Mage;
public interface UndoList extends BlockList, Comparabl... |
Add support for CSV output | package batchgcd
import (
"fmt"
"github.com/ncw/gmp"
)
type Collision struct {
Modulus *gmp.Int
P *gmp.Int
Q *gmp.Int
}
func (x Collision) HavePrivate() bool {
return x.P != nil || x.Q != nil
}
func (x Collision) String() string {
if x.HavePrivate() {
if x.P.Cmp(x.Q) < 0 {
return fmt.Sprintf... | package batchgcd
import (
"fmt"
"github.com/ncw/gmp"
)
type Collision struct {
Modulus *gmp.Int
P *gmp.Int
Q *gmp.Int
}
func (x Collision) HavePrivate() bool {
return x.P != nil || x.Q != nil
}
func (x Collision) String() string {
if x.HavePrivate() {
if x.P.Cmp(x.Q) < 0 {
return fmt.Sprintf... |
Add test for getting/setting default encoding in preferences | package net.sf.jabref;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JabRefPreferencesTest {
private JabRefPreferences prefs;
private JabRefPreferences backup;... | package net.sf.jabref;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JabRefPreferencesTest {
private JabRefPreferences prefs;
private JabRefPreferences backup;
@Before
public void setUp() {
... |
Refactor API to a more readable form | import sublime_plugin
DEFAULT_NAME = 'Find Results'
ALT_NAME = 'Find Results '
class OpenSearchInNewTab(sublime_plugin.EventListener):
# set a bit changed name
# so the tab won't be bothered
# during new search
def on_activated(self, view):
if self.is_search_view(view):
self.appl... | import sublime_plugin
DEFAULT_NAME = 'Find Results'
ALT_NAME = 'Find Results '
class OpenSearchInNewTab(sublime_plugin.EventListener):
# set a bit changed name
# so the tab won't be bothered
# during new search
def on_activated(self, view):
if view.name() == DEFAULT_NAME:
view.se... |
Fix length calculation in the exception path | /*
Copyright 2011 Frederic Langlet
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
you may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writi... | /*
Copyright 2011 Frederic Langlet
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
you may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writi... |
Use the globalization object we already collected. | function startModule() {
// Get locale from phonegap
var globalization = navigator.globalization;
if (globalization) {
globalization.getLocaleName(
function (locale) {
setLocale(locale.value);
},
function () {
console.log("Failed to get locale from phonegap. Using ... | function startModule() {
// Get locale from phonegap
var globalization = navigator.globalization;
if (globalization) {
navigator.globalization.getLocaleName(
function (locale) {
setLocale(locale.value);
},
function () {
console.log("Failed to get locale from phoneg... |
Clear query on component unmount | import { PureComponent, createElement } from 'react';
import Proptypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import AutocompleteSearchComponent from './autocomplete-search-component';
import actions from './autocomplete-search-actions';
import { getFiltere... | import { createElement } from 'react';
import Proptypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { deburrUpper } from 'app/utils';
import AutocompleteSearchComponent from './autocomplete-search-component';
import actions from './autocomplete-search-act... |
Fix for nullable author in blogpost factory | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa 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... | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa 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... |
Add placeholder to attribute bindings | import Ember from 'ember';
const {
Component,
get
} = Ember;
export default Component.extend({
tagName: 'input',
type: 'text',
attributeBindings: [
'accept',
'autocomplete',
'autosave',
'dir',
'formaction',
'formenctype',
'formmethod',
'formnovalidate',
'formtarget',
... | import Ember from 'ember';
const {
Component,
get
} = Ember;
export default Component.extend({
tagName: 'input',
type: 'text',
attributeBindings: [
'accept',
'autocomplete',
'autosave',
'dir',
'formaction',
'formenctype',
'formmethod',
'formnovalidate',
'formtarget',
... |
Order map by modified_at desc in list | from django.views.generic import TemplateView
from chickpea.models import Map
class Home(TemplateView):
template_name = "youmap/home.html"
list_template_name = "chickpea/map_list.html"
def get_context_data(self, **kwargs):
maps = Map.objects.order_by('-modified_at')[:100]
return {
... | from django.views.generic import TemplateView
from chickpea.models import Map
class Home(TemplateView):
template_name = "youmap/home.html"
list_template_name = "chickpea/map_list.html"
def get_context_data(self, **kwargs):
maps = Map.objects.all()[:100]
return {
"maps": maps
... |
Add Context parameter to onCardDelete to match SDK | package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.content.Context;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements... | package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card... |
Update IIFE to reference window directly
When using this polyfill as an ES2015 module (with a tool such as Rollup), it receives this error:
```
node_modules\window.requestanimationframe\requestanimationframe.js (49:2) The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been re... | /**
* requestAnimationFrame polyfill v1.0.0
* requires Date.now
*
* © Polyfiller 2015
* Released under the MIT license
* github.com/Polyfiller/requestAnimationFrame
*/
window.requestAnimationFrame || function (window) {
'use strict';
window.requestAnimationFrame = window.msRequestAnimationFrame
|| ... | /**
* requestAnimationFrame polyfill v1.0.0
* requires Date.now
*
* © Polyfiller 2015
* Released under the MIT license
* github.com/Polyfiller/requestAnimationFrame
*/
window.requestAnimationFrame || function (window) {
'use strict';
window.requestAnimationFrame = window.msRequestAnimationFrame
|| ... |
Fix bug in unit tests | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
class TestOptionalParameters(unittest.TestCase):
def test... | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
class TestOptionalParameters(unittest.TestCase):
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
def tes... |
Upgrade type and click versions | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.6',
'botocore>=1.4.8,<2.0.0',
'virtualenv>=15.0.0,<16.0.0',
'typing==3.5.3.0',
]
setup(
name='chalice',
version='0.5.0',
... | #!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.2',
'botocore>=1.4.8,<2.0.0',
'virtualenv>=15.0.0,<16.0.0',
'typing==3.5.2.2',
]
setup(
name='chalice',
version='0.5.0',
... |
Fix bug in 'pure' due to operator precedence | <?php
namespace Phunkie\Functions\applicative;
use Phunkie\Cats\Applicative;
use Phunkie\Cats\Apply;
use function Phunkie\Functions\currying\applyPartially;
use Phunkie\Types\Kind;
/**
* F<A -> B> -> F<A> -> F<B>
*/
const ap = "\\Phunkie\\Functions\\applicative\\ap";
function ap(Kind $f)
{
return applyPartiall... | <?php
namespace Phunkie\Functions\applicative;
use Phunkie\Cats\Applicative;
use Phunkie\Cats\Apply;
use function Phunkie\Functions\currying\applyPartially;
use Phunkie\Types\Kind;
/**
* F<A -> B> -> F<A> -> F<B>
*/
const ap = "\\Phunkie\\Functions\\applicative\\ap";
function ap(Kind $f)
{
return applyPartiall... |
Update factory-boy's .generate to evaluate
Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com> | from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
... | from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
... |
Add new test domains for our test google suite instances | function (user, context, callback) {
if (!user) {
// If the user is not presented (i.e. a rule deleted it), just go on, since authenticate will always fail.
return callback(null, null, context);
}
if (context.clientID !== 'q0tFB9QyFIKqPOOKvkFnHMj2VwrLjX46') return callback(null, user, context); // Google... | function (user, context, callback) {
if (!user) {
// If the user is not presented (i.e. a rule deleted it), just go on, since authenticate will always fail.
return callback(null, null, context);
}
if (context.clientID !== 'q0tFB9QyFIKqPOOKvkFnHMj2VwrLjX46') return callback(null, user, context); // Google... |
Refactor equality function and add less function | package checkers
import (
"fmt"
"math"
)
type Point struct {
X, Y int
}
func (p Point) Add(q Point) Point {
return Point{p.X + q.X, p.Y + q.Y}
}
func (p Point) Sub(q Point) Point {
return Point{p.X - q.X, p.Y - q.Y}
}
func (p Point) Equal(q Point) bool {
return p.X == q.X && p.Y == q.Y
}
func (p Point) Less... | package checkers
import (
"fmt"
"math"
)
type Point struct {
X, Y int
}
func (p Point) Add(q Point) Point {
return Point{p.X + q.X, p.Y + q.Y}
}
func (p Point) Sub(q Point) Point {
return Point{p.X - q.X, p.Y - q.Y}
}
func (p Point) Equal(q Point) bool {
if p.X == q.X && p.Y == q.Y {
return true
}
return... |
Use JSON for API GET /auth/test response | # Copyright (C) 2016 University of Zurich. All rights reserved.
#
# This file is part of MSRegistry Backend.
#
# MSRegistry Backend is free software: you can redistribute it and/or
# modify it under the terms of the version 3 of the GNU Affero General
# Public License as published by the Free Software Foundation, or a... | # Copyright (C) 2016 University of Zurich. All rights reserved.
#
# This file is part of MSRegistry Backend.
#
# MSRegistry Backend is free software: you can redistribute it and/or
# modify it under the terms of the version 3 of the GNU Affero General
# Public License as published by the Free Software Foundation, or a... |
Prepare for Hapi 6 migration. | // Load modules
var Fs = require('fs');
var Path = require('path');
var HeapDump = require('heapdump');
var Hoek = require('hoek');
// Declare internals
var internals = {
initialized: false,
defaults: {
logPath: Path.join(__dirname, '..', 'poop.log')
}
};
exports.register = function (plugin, o... | // Load modules
var Fs = require('fs');
var Path = require('path');
var HeapDump = require('heapdump');
var Hoek = require('hoek');
// Declare internals
var internals = {
initialized: false,
defaults: {
logPath: Path.join(__dirname, '..', 'poop.log')
}
};
exports.register = function (plugin, o... |
Change url in dashboard administrador | from django.conf.urls import url
from .views import admin_main_dashboard, admin_users_dashboard, \
admin_users_create, admin_users_edit, admin_users_edit_form, \
admin_users_delete_modal, admin_users_delete, list_studies
app_name = 'administracion'
# Urls en espanol
urlpatterns =... | from django.conf.urls import url
from .views import admin_main_dashboard, admin_users_dashboard, \
admin_users_create, admin_users_edit, admin_users_edit_form, \
admin_users_delete_modal, admin_users_delete, list_studies
app_name = 'administracion'
# Urls en espanol
urlpatterns =... |
Expand the review if the user's at least entered a rating. | import template from './item-review.html';
import './item-review.scss';
function ItemReviewController($rootScope, dimSettingsService) {
'ngInject';
const vm = this;
vm.canReview = dimSettingsService.allowIdPostToDtr;
vm.submitted = false;
vm.hasUserReview = vm.item.userRating;
vm.expandReview = vm.hasUser... | import template from './item-review.html';
import './item-review.scss';
function ItemReviewController($rootScope, dimSettingsService) {
'ngInject';
const vm = this;
vm.canReview = dimSettingsService.allowIdPostToDtr;
vm.expandReview = false;
vm.submitted = false;
vm.hasUserReview = vm.item.userRating;
... |
Update sendEvent function to force passing undefined if metadata is empty. | /**
* Analytics advanced tracking script to be inserted into the frontend via PHP.
*
* Site Kit by Google, Copyright 2020 Google 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
*
... | /**
* Analytics advanced tracking script to be inserted into the frontend via PHP.
*
* Site Kit by Google, Copyright 2020 Google 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
*
... |
Update implementation as per spec | import { randomBytes } from 'crypto';
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
function strongRandomNumber() {
return randomBytes(4).readUInt32LE() / 0xFFFFFFFF
}
function encodeTime(now, len) {
let arr = []
for (let x = len; x > 0; x--) ... | // Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
if (ENCODING.length !== 32) throw new Error('ENCODING')
// Current Version of SUID
const VERSION = 1
function encodeVersion() {
if (VERSION >= 16) throw new Error('VERSION')
return VERSION.toString(16... |
fix(api): Fix formatting of API error message | from __future__ import absolute_import
from rest_framework import serializers
from sentry.utils.http import parse_uri_match
class OriginField(serializers.CharField):
# Special case origins that don't fit the normal regex pattern, but are valid
WHITELIST_ORIGINS = ('*')
def from_native(self, data):
... | from __future__ import absolute_import
from rest_framework import serializers
from sentry.utils.http import parse_uri_match
class OriginField(serializers.CharField):
# Special case origins that don't fit the normal regex pattern, but are valid
WHITELIST_ORIGINS = ('*')
def from_native(self, data):
... |
Fix utf-8 encoding error when saving the file. | #!/usr/bin/env python
from appkit.api.v0_2_8 import App
from flask import render_template, request
import os
import sys
import codecs
app = App(__name__)
try:
file_name = sys.argv[1]
if not os.path.exists(file_name):
open(file_name, 'w').close()
except:
file_name = None
app.file_name = file_name... | #!/usr/bin/env python
from appkit.api.v0_2_8 import App
from flask import render_template, request
import os
import sys
import codecs
app = App(__name__)
try:
file_name = sys.argv[1]
if not os.path.exists(file_name):
open(file_name, 'w').close()
except:
file_name = None
app.file_name = file_name... |
Update before/after to be proper pseudo-elements. | /**
* Storybook main config.
*
* Site Kit by Google, Copyright 2021 Google 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
... | /**
* Storybook main config.
*
* Site Kit by Google, Copyright 2021 Google 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
... |
Remove download URL since Github doesn't get his act together. Damnit
git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f
committer: leidel <leidel@12edf5ea-513a-0410-8a8c-37067077e60f>
--HG--
extra : convert_revision : aa256d6eb94fc5492608373969ed7c5826b2077a | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... |
Add comments to HTTPError interface
This can be very confusing potentially | package errors
import "fmt"
type HttpError interface {
error
StatusCode() int // actual HTTP status code
ErrorCode() string // error code returned in response body from CC or UAA
Headers() string // see: known_error_codes.go
Body() string
}
type httpError struct {
statusCode int
headers string
body ... | package errors
import "fmt"
type HttpError interface {
Error
StatusCode() int
Headers() string
Body() string
}
type httpError struct {
statusCode int
headers string
body string
code string
description string
}
type HttpNotFoundError struct {
*httpError
}
func NewHttpError(statusCode in... |
Update API path of geting sensors | (function(){
$.ajax({
url: 'users/evanxd/sensors',
})
.done(function(sensors) {
var sensorList = $('#sensor-list ul');
var html = '';
sensors.forEach(function(sensor) {
var html = '<li class="collection-item">' +
'<div>' +
sensor.name + '<a href="senso... | (function(){
$.ajax({
url: 'evanxd/sensors',
})
.done(function(sensors) {
var sensorList = $('#sensor-list ul');
var html = '';
sensors.forEach(function(sensor) {
var html = '<li class="collection-item">' +
'<div>' +
sensor.name + '<a href="sensor-deta... |
Simplify test case. Tweak logging. | package discord
import (
"fmt"
"testing"
"time"
)
func TestBasicTicker(t *testing.T) {
// t.Skip("TickOnce not implemented")
var counter = 1
var i = 0
f := func(to *Ticker) {
fmt.Printf("Iteration: %d\n", i)
if i >= 5 {
to.Done()
}
counter++
i++
}
cleanUp := func(to *Ticker) {
return
}
... | package discord
import (
"fmt"
"sync"
"testing"
"time"
)
func TestBasicTicker(t *testing.T) {
// t.Skip("TickOnce not implemented")
var counter = 1
var i = 0
mu := sync.Mutex{}
f := func(to *Ticker) {
fmt.Println("Iteration: " + string(i))
mu.Lock()
defer mu.Unlock()
if i >= 5 {
to.Done()
}
... |
Fix pretty duration for null value | from datetime import datetime, timedelta
from django import template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter
def duration(value):
""" Returns a duration in hours to a human readable version (minutes, days, ...)
... | from datetime import datetime, timedelta
from django import template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter
def duration(value):
""" Returns a duration in hours to a human readable version (minutes, days, ...)
... |
Fix condition to skip blacklisted extensions | 'use strict';
var crypto = require('crypto');
var CustomStats = require('webpack-custom-stats-patch');
var DEFAULT_PARAMS = {
customStatsKey: 'sprockets',
ignore: /\.(gz|html)$/
};
function SprocketsStatsWebpackPlugin(options) {
var params = options || {};
this._customStatsKey = options.customStatsKey || DE... | 'use strict';
var crypto = require('crypto');
var CustomStats = require('webpack-custom-stats-patch');
var DEFAULT_PARAMS = {
customStatsKey: 'sprockets',
ignore: /\.(gz|html)$/
};
function SprocketsStatsWebpackPlugin(options) {
var params = options || {};
this._customStatsKey = options.customStatsKey || DE... |
Make PDO connections persistent and exceptional | <?php
/* Site-wide utility functions */
require_once('secureConstants.php');
function mysqliConn() {
$db = new mysqli(
$GLOBALS['DB']['SERVER'],
$GLOBALS['DB']['USERNAME'],
$GOLBALS['DB']['PASSWORD'],
$GLOBALS['DB']['DATABASE']
);
if ($db->connect_errno) {
header('HTTP/1.1 500 Internal Server Error');
... | <?php
/* Site-wide utility functions */
require_once('secureConstants.php');
function mysqliConn() {
$db = new mysqli(
$GLOBALS['DB']['SERVER'],
$GLOBALS['DB']['USERNAME'],
$GOLBALS['DB']['PASSWORD'],
$GLOBALS['DB']['DATABASE']
);
if ($db->connect_errno) {
header('HTTP/1.1 500 Internal Server Error');
... |
Update adapter find to return a promise. | /**
* External imports
*/
import _ from 'underscore';
import co from 'co';
import mingo from 'mingo';
import libdebug from 'debug';
// create debug logger
const debug = libdebug('storage-adapter');
export const ADAPTABLE_METHODS = [
'skip',
'sort',
'find',
'limit',
'insert',
'update',
'remove',
'agg... | /**
* External imports
*/
import _ from 'underscore';
import mingo from 'mingo';
import libdebug from 'debug';
// create debug logger
const debug = libdebug('storage-adapter');
export const ADAPTABLE_METHODS = [
'skip',
'sort',
'find',
'limit',
'insert',
'update',
'remove',
'aggregate',
];
function... |
Fix sorting on FOLV settings example | import ListFormRoute from 'ember-flexberry/routes/list-form';
export default ListFormRoute.extend({
/**
Name of model projection to be used as record's properties limitation.
@property modelProjection
@type String
@default 'SuggestionL'
*/
modelProjection: 'SuggestionL',
/**
developerUserS... | import ListFormRoute from 'ember-flexberry/routes/list-form';
export default ListFormRoute.extend({
/**
Name of model projection to be used as record's properties limitation.
@property modelProjection
@type String
@default 'SuggestionL'
*/
modelProjection: 'SuggestionL',
/**
developerUserS... |
Remove stray print statement O_o | # Copyright 2018 The Lucid 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 applicable l... | # Copyright 2018 The Lucid 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 applicable l... |
Update classifiers to drop support for Python 2.7 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from setuptools import setup
setup(
name='pybreaker',
version='0.6.0',
description='Python implementation of the Circuit Breaker pattern',
long_description=open('README.rst', 'r').read(),
keywords=['design', 'pattern', 'circuit', 'breaker', 'integration'... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from setuptools import setup
setup(
name='pybreaker',
version='0.6.0',
description='Python implementation of the Circuit Breaker pattern',
long_description=open('README.rst', 'r').read(),
keywords=['design', 'pattern', 'circuit', 'breaker', 'integration'... |
Change path to mfr directory | """PDF renderer module."""
from mfr.core import RenderResult
import PyPDF2
import urllib
import mfr
def is_valid(fp):
"""Tests file pointer for validity
:return: True if fp is a valid pdf, False if not
"""
try:
PyPDF2.PdfFileReader(fp)
return True
except PyPDF2.utils.PdfReadError:... | """PDF renderer module."""
from mfr.core import RenderResult
import PyPDF2
import urllib
def is_valid(fp):
"""Tests file pointer for validity
:return: True if fp is a valid pdf, False if not
"""
try:
PyPDF2.PdfFileReader(fp)
return True
except PyPDF2.utils.PdfReadError:
re... |
Work around a paralleltest crash
> ERRO [runner] Panic: paralleltest: package "main" (isInitialPkg: true, needAnalyzeSource: true): runtime error: index out of range [0] with length 0: goroutine 5859 [running]:
> ...
> github.com/kunwardeep/paralleltest/pkg/paralleltest.isTestFunction(0x1b7d8c0?)
> github.com/kunward... | package main
import "testing"
func TestTree(_ *testing.T) {
nodes := []treeNode{
{"F", "H", []string{}},
{"F", "I", []string{}},
{"F", "J", []string{}},
{"A", "B", []string{}},
{"A", "C", []string{}},
{"A", "K", []string{}},
{"C", "F", []string{}},
{"C", "G", []string{"beware", "the", "scary", "thing... | package main
import "testing"
func TestTree(*testing.T) {
nodes := []treeNode{
{"F", "H", []string{}},
{"F", "I", []string{}},
{"F", "J", []string{}},
{"A", "B", []string{}},
{"A", "C", []string{}},
{"A", "K", []string{}},
{"C", "F", []string{}},
{"C", "G", []string{"beware", "the", "scary", "thing"}... |
Make windows bigger in this test so the captions can be read.
Index: tests/window/WINDOW_CAPTION.py
===================================================================
--- tests/window/WINDOW_CAPTION.py (revision 777)
+++ tests/window/WINDOW_CAPTION.py (working copy)
@@ -19,8 +19,8 @@
class WINDOW_CAPTION(unittest... | #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the ... | #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the ... |
Rename new sequence search url | """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
[Discord] Remove unused bot attribute from Duelyst cog |
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst())
class Duelyst(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(sel... |
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst(bot))
class Duelyst(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True,... |
Change environ.get → environ[] in scope of `if` | import os
class BaseConfig(object):
DEBUG_TB_INTERCEPT_REDIRECTS = False
SECRET_KEY = os.environ.get('SECRET_KEY', 'change me in production')
db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/database.db'))
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///... | import os
class BaseConfig(object):
DEBUG_TB_INTERCEPT_REDIRECTS = False
SECRET_KEY = os.environ.get('SECRET_KEY', 'change me in production')
db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/database.db'))
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///... |
Fix the name of arguments for PHP 8 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Php70 as p;
if (PHP_VERSION_ID >= 70000) {
return;
}
if... | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Polyfill\Php70 as p;
if (PHP_VERSION_ID >= 70000) {
return;
}
if... |
Fix Undertow static handler package name, as it was renamed | package org.wildfly.swarm.undertow;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;
/**
* @author Bob McWhirter
*/
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {
default T staticContent() {
return staticContent( "/", "." );
}
d... | package org.wildfly.swarm.undertow;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;
/**
* @author Bob McWhirter
*/
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {
default T staticContent() {
return staticContent( "/", "." );
}
d... |
Normalize all to spinal-case before other convertions. Added toSpaceCase. | var p = String.prototype;
// normalize always returns the string in spinal-case
function normalize(str) {
var arr = str.split(/[\s-_.]/);
if(arr.length > 1)
return arr.map(function(part) { return part.toLowerCase(); }).join('-');
else
return (str.charAt(0).toLowerCase() + str.slice(1)).replace(/([A-Z])/, '-$&'... | var p = String.prototype;
// Converts spinal-case, snake_case or space case to camelCase
p.toCamelCase = function(pascalCase) {
var str = this.toLowerCase();
var arr = str.split(/[\s-_]/);
for(var i = pascalCase ? 0 : 1; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
retu... |
jobs-041: Fix browsable API index regexp | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from jobs_backend.views import APIRoot
api_urlpatterns = [
# All api endpoints should be included here
url(r'^users/', include('jobs_backend.users.urls.users'... | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from jobs_backend.views import APIRoot
api_urlpatterns = [
# All api endpoints should be included here
url(r'^users/', include('jobs_backend.users.urls.users'... |
Add Array of responsive dates for navDates display | /* global GuardianAPI, NYTAPI, DomUpdater */
function main() {
const today = new Date(Date.now());
console.log(today);
const datesLastWeek = Array.from({ length: 7 }, (_, idx) => new Date(today - (idx + 1) * (8.64 * Math.pow(10, 7))));
console.log(datesLastWeek);
const navDates = datesLastWeek.map(el => el... | /* global GuardianAPI, NYTAPI, DomUpdater */
function fillZero(num) {
return num < 10 ? `0${num}` : num;
}
function formatGuardianDate(date) {
return `${date.getFullYear()}-${fillZero(date.getMonth() + 1)}-${fillZero(date.getDate())}`;
}
function formatNYTDate(date) {
return `${date.getFullYear()}${fillZero(d... |
Make it module loaders compatible | (function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.f = factory();
}
})(this, function () {
var lambdaRegex = /\((.*)\)[\s]*=>[\s]*(.+)/;
function f(x)... | var f = function(x) { return function() {return x}; ; };
var lambdaRegex = /\((.*)\)[\s]*=>[\s]*(.+)/;
f.property = function(propertyName) {
if(propertyName[0] === '!')
return function(obj) { return !obj[propertyName.substring(1)]; };
else
return function(obj) { return obj[propertyName]; };
}
f.method = function(... |
Remove superflous settings option on dredd command | import { lazyFunctionRequire } from 'roc';
import config from '../config/roc.config.js';
import meta from '../config/roc.config.meta.js';
const lazyRequire = lazyFunctionRequire(require);
export default {
config,
meta,
actions: [
{
hook: 'server-started',
description: 'Run... | import { lazyFunctionRequire } from 'roc';
import config from '../config/roc.config.js';
import meta from '../config/roc.config.meta.js';
const lazyRequire = lazyFunctionRequire(require);
export default {
config,
meta,
actions: [
{
hook: 'server-started',
description: 'Run... |
Add PUT/POST handling to ClassyResource
This resolves #1.
Data can be passed into a resource method call by including it
as the final parameter. For example, in this commit I have added
support for the following:
classy.organizations.createCampaign(##, {});
classy.campaigns.update(##, {}); | /** Just for testing */
import Classy from '../src/Classy';
let classy = new Classy({
clientId: 'fbnwFsTgUox9VAPTsHfJXk5KiyScSU',
clientSecret: 'XlX9sSH0sHHxTVIoBilbxcEYbQrrtLsYhtwNSrwuN0vgID0164xYY',
baseUrl: 'https://dev-gateway.classy-test.org'
});
let app = classy.app();
app.then((response) => {
clas... | /** Just for testing */
import Classy from '../dist/Classy';
let classy = new Classy({
clientId: 'fbnwFsTgUox9VAPTsHfJXk5KiyScSU',
clientSecret: 'XlX9sSH0sHHxTVIoBilbxcEYbQrrtLsYhtwNSrwuN0vgID0164xYY',
baseUrl: 'https://dev-gateway.classy-test.org'
});
let app = classy.app();
app.then((response) => {
cla... |
Clear $LANGUAGE before running tests | #!/usr/bin/env python
import unittest, os, sys
for x in ['LANGUAGE', 'LANG']:
if x in os.environ:
del os.environ[x]
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_... | #!/usr/bin/env python
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') an... |
Add simple login form in the API.
This is usefull for developers to explore the Browlable api directly
on the browser. | """snowman URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | """snowman URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
Make the Registry use the manager option | <?php
/**
* This file is part of the PierstovalCharacterManagerBundle package.
*
* (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pierstoval\Bundle\CharacterManagerBund... | <?php
/**
* This file is part of the PierstovalCharacterManagerBundle package.
*
* (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pierstoval\Bundle\CharacterManagerBund... |
Change json file to sample one | #coding=utf-8
#imports
import pystache as ps
import sys
import json
import imp
views = imp.load_source('views', 'swedish/views.py')
#from views import Invoice
def main():
configFile = "invoice.sample.json"
htmlFile = "invoice.html"
if len(sys.argv) == 2 :
configFile = sys.argv[1]
htmlFile = configFile[:-4] + "... | #coding=utf-8
#imports
import pystache as ps
import sys
import json
import imp
views = imp.load_source('views', 'swedish/views.py')
#from views import Invoice
def main():
configFile = "invoice.json"
htmlFile = "invoice.html"
if len(sys.argv) == 2 :
configFile = sys.argv[1]
htmlFile = configFile[:-4] + "html"
... |
Refactor to avoid dynamic module resolution | 'use strict';
/**
* Node version.
*
* @module @stdlib/process/node-version
* @type {(string|null)}
*
* @example
* var semver = require( 'semver' );
* var VERSION = require( '@stdlib/process/node-version' );
*
* if ( semver.lt( VERSION, '1.0.0' ) ) {
* console.log( 'Running on a pre-io.js version...' );
* }
* else i... | 'use strict';
/**
* Node version.
*
* @module @stdlib/process/node-version
* @type {(string|null)}
*
* @example
* var semver = require( 'semver' );
* var VERSION = require( '@stdlib/process/node-version' );
*
* if ( semver.lt( VERSION, '1.0.0' ) ) {
* console.log( 'Running on a pre-io.js version...' );
* }
* else i... |
Fix minor issue with Contributor component | import React, { Component, PropTypes } from "react"
import cx from "classnames"
import Avatar from "../Avatar"
export default class Contributor extends Component {
static propTypes = {
author: PropTypes.string.isRequired,
commits: PropTypes.number,
size: PropTypes.string,
}
render() {
const {
... | import React, { Component, PropTypes } from "react"
import cx from "classnames"
import Avatar from "../Avatar"
export default class Contributors extends Component {
static propTypes = {
author: PropTypes.string.isRequired,
commits: PropTypes.string,
size: PropTypes.string,
}
render() {
const {... |
Use pathlib for path segmentation | from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, ... | from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
... |
Add socket echo util function for adminBroadcast | const { ERROR } = require('../common/actionTypes/error');
const mergePermanentAndMetadata = (perm, meta) => Object.assign(perm, meta);
const createSocketObject = (channel, payload, metadata) => {
const obj = mergePermanentAndMetadata({
type: channel,
}, metadata);
obj.data = payload;
return obj;
};
const... | const { ERROR } = require('../common/actionTypes/error');
const mergePermanentAndMetadata = (perm, meta) => Object.assign(perm, meta);
const createSocketObject = (channel, payload, metadata) => {
const obj = mergePermanentAndMetadata({
type: channel,
}, metadata);
obj.data = payload;
return obj;
};
const... |
Fix test by actually setting package source to have no name | from nose.tools import istest, assert_equal
from whack.naming import PackageNamer
@istest
def package_with_unnamed_source_has_name_equal_to_install_identifier():
package_source = PackageSource("/tmp/nginx-src", None)
package_name = _name_package(package_source, {})
assert_equal("install-id(/tmp/nginx-src... | from nose.tools import istest, assert_equal
from whack.naming import PackageNamer
@istest
def package_with_unnamed_source_has_name_equal_to_install_identifier():
package_source = PackageSource("/tmp/nginx-src", "nginx")
package_name = _name_package(package_source, {})
assert_equal("install-id(/tmp/nginx-... |
Remove some extraneous comments and fix a spacing problem. | var ABTestHelper = require('../ABTestHelper.js');
module.exports['Test Input'] = {
setUp: function(callback) {
this.abTestHelper = new ABTestHelper();
this.abTestHelper.addVersion('A', { name: 'Original', eventCount: 1356, totalCount: 3150 });
this.abTestHelper.addVersion('B', { name: 'Original', eventCou... | var ABTestHelper = require('../ABTestHelper.js');
module.exports['Test Input'] = {
setUp: function(callback) {
// Put test setup here
// Test wildly varying input on existing functions and see if
// the expected result is obtained.
// Get Results - no data, lots of data,
// initialize vars an... |
Format migration for Django 1.7 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('cms', '0011_auto_20150419_1006'),
]
operations = [
migrations.AlterField(
model... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django.contrib.auth.models
class Migration(migrations.Migration):
dependencies = [
('cms', '0011_auto_20150419_1006'),
]
operations = [
migrat... |
Make deleting build plan and repository default when deleting participation | (function () {
'use strict';
angular
.module('exerciseApplicationApp')
.controller('ParticipationDeleteController', ParticipationDeleteController);
ParticipationDeleteController.$inject = ['$uibModalInstance', 'entity', 'Participation'];
function ParticipationDeleteController($uibModa... | (function () {
'use strict';
angular
.module('exerciseApplicationApp')
.controller('ParticipationDeleteController', ParticipationDeleteController);
ParticipationDeleteController.$inject = ['$uibModalInstance', 'entity', 'Participation'];
function ParticipationDeleteController($uibModa... |
Test out the live transport. | "use babel";
import async from "async";
import GitHubClient from "node-github";
import package from "../../../package.json";
import Fork from "../../models/fork";
var github = new GitHubClient({
version: "3.0.0",
debug: true,
headers: {
"user-agent": `atom-pull-request/${package.version}` // GitHub is happ... | "use babel";
import async from "async";
import GitHubClient from "node-github";
import package from "../../../package.json";
import Fork from "../../models/fork";
var github = new GitHubClient({
version: "3.0.0",
debug: true,
headers: {
"user-agent": `atom-pull-request/${package.version}` // GitHub is happ... |
Add left and right margin for spacing | @extends('components.content-area')
@section('content')
<img class="w-full block" src="/styleguide/image/1600x580?text=Full%20Width%20Image" />
<div class="bg-grey-lightest mb-4">
<div class="row py-4">
<p class="mx-4 py-2 text-4xl text-grey-darkest font-serif text-center">"{{ $faker->para... | @extends('components.content-area')
@section('content')
<img class="w-full block" src="/styleguide/image/1600x580?text=Full%20Width%20Image" />
<div class="bg-grey-lightest mb-4">
<div class="row py-4">
<p class="py-2 text-4xl text-grey-darkest font-serif text-center">"{{ $faker->paragraph... |
Add @Issue to reference JENKINS-44052 | package jenkins.util;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static jenkins.util.TimeDuration.*;
@Issue("JENKINS-44052")
public class TimeDurationTest {
@Test
publ... | package jenkins.util;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static jenkins.util.TimeDuration.*;
public class TimeDurationTest {
@Test
public void fromString() throws Exception {
assertEqual... |
Rebase most recent alembic change onto HEAD | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
... | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
... |
Update ApiRequest to not pass -d for empty data
'cf curl' has changed such that passing -d for empty data is an error.
Signed-off-by: Kris Hicks <6d3f751023bc04266d4da2ff94804f4240839fe2@pivotal.io> | package cf
import (
"encoding/json"
"strings"
"time"
. "github.com/onsi/gomega"
"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
)
//var CfApiTimeout = 30 * time.Second
type GenericResource struct {
Metadata struct {
Guid string `json:"guid"`
} `json:"metadata"`
}
type QueryResponse struct {
R... | package cf
import (
"encoding/json"
"strings"
"time"
. "github.com/onsi/gomega"
"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
)
//var CfApiTimeout = 30 * time.Second
type GenericResource struct {
Metadata struct {
Guid string `json:"guid"`
} `json:"metadata"`
}
type QueryResponse struct {
R... |
Fix missing opts in registerChannel | // Setup
const HTTPServer = require('./lib/http_server')
// Exports
module.exports = Oacp
// Oacp Constructor
function Oacp (namespace) {
var self = this
self.models = {}
self.channels = {}
self.controllers = {}
self.config = require('./config/app')(namespace)
self._ns = self.config.app.namespace
self.s... | // Setup
const HTTPServer = require('./lib/http_server')
// Exports
module.exports = Oacp
// Oacp Constructor
function Oacp (namespace) {
var self = this
self.models = {}
self.channels = {}
self.controllers = {}
self.config = require('./config/app')(namespace)
self._ns = self.config.app.namespace
self.s... |
Make pubmed hash accessible to API |
from pubrunner.command_line import *
from pubrunner.upload import *
from pubrunner.FTPClient import *
from pubrunner.getresource import *
from pubrunner.pubrun import pubrun,cleanWorkingDirectory
from pubrunner.convert import *
from pubrunner.pubmed_hash import pubmed_hash
def loadYAML(yamlFilename):
yamlData = None... |
from pubrunner.command_line import *
from pubrunner.upload import *
from pubrunner.FTPClient import *
from pubrunner.getresource import *
from pubrunner.pubrun import pubrun,cleanWorkingDirectory
from pubrunner.convert import *
def loadYAML(yamlFilename):
yamlData = None
with open(yamlFilename,'r') as f:
try:
... |
Update PyPI classifiers and test requirements | #!/usr/bin/env python
from setuptools import setup
setup(
name='bandicoot',
author='Yves-Alexandre de Montjoye',
author_email='yvesalexandre@demontjoye.com',
version="0.4",
url="https://github.com/yvesalexandre/bandicoot",
license="MIT",
packages=[
'bandicoot',
'bandicoot.h... | #!/usr/bin/env python
from setuptools import setup
setup(
name='bandicoot',
author='Yves-Alexandre de Montjoye',
author_email='yvesalexandre@demontjoye.com',
version="0.4",
url="https://github.com/yvesalexandre/bandicoot",
license="MIT",
packages=[
'bandicoot',
'bandicoot.h... |
Add missing value for sml:axis | package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.sml;
import com.google.gwt.core.shared.GWT;
import com.sensia.relaxNG.RNGElement;
import com.sensia.relaxNG.RNGTag;
import com.sensia.tools.client.swetools.editors.sensorml.panels.IPanel;
import com.sensia.tools.client.swetools.editors.se... | package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.sml;
import com.google.gwt.core.shared.GWT;
import com.sensia.relaxNG.RNGElement;
import com.sensia.relaxNG.RNGTag;
import com.sensia.tools.client.swetools.editors.sensorml.panels.IPanel;
import com.sensia.tools.client.swetools.editors.se... |
test: Add test for double assertion | /* eslint-env mocha */
const {expect} = chai;
import React from './React';
import TestUtils from './TestUtils';
describe('React components', () => {
it('should find valid xpath in react component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//b... | /* eslint-env mocha */
const {expect} = chai;
import React from './React';
import TestUtils from './TestUtils';
describe('React components', () => {
it('should find valid xpath in react component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//b... |
Add logo to command help information | /**
* Copyright 2017-present, Callstack.
* All rights reserved.
*
* @flow
*/
const program = require("commander");
const pjson = require("../../package.json");
const logger = require("../utils/logger")(false);
import type { Command, Context } from "../types";
const commands: Array<Command> = [require("./start")... | /**
* Copyright 2017-present, Callstack.
* All rights reserved.
*
* @flow
*/
const program = require("commander");
const pjson = require("../../package.json");
const logger = require("../utils/logger")(false);
import type { Command, Context } from "../types";
const commands: Array<Command> = [require("./start")... |
Change prompt to just '>'. | function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: { expr : code },
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = r... | function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: { expr : code },
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = r... |
Remove useless parenthesis in qrcode python demo | #!/usr/bin/env python
import StringIO
import angus
import cv2
import numpy as np
if __name__ == '__main__':
### Web cam index might be different from 0 on your setup.
stream_index = 0
cap = cv2.VideoCapture(stream_index)
if not cap.isOpened():
print "Cannot open stream of index " + str(stream... | #!/usr/bin/env python
import StringIO
import angus
import cv2
import numpy as np
if __name__ == '__main__':
### Web cam index might be different from 0 on your setup.
stream_index = 0
cap = cv2.VideoCapture(stream_index)
if not cap.isOpened():
print "Cannot open stream of index " + str(stream... |
Comment out heapdump for now. | #!/usr/bin/env node
/* eslint no-unused-expressions:0 */
'use strict';
// require('heapdump');
require('./lib/configure');
const yargs = require('yargs');
yargs
.strict()
.wrap(Math.min(120, yargs.terminalWidth()))
.version().alias('version', 'v')
.help('help').alias('help', 'h')
.usage('npms-analyzer command line... | #!/usr/bin/env node
/* eslint no-unused-expressions:0 */
'use strict';
require('heapdump');
require('./lib/configure');
const yargs = require('yargs');
yargs
.strict()
.wrap(Math.min(120, yargs.terminalWidth()))
.version().alias('version', 'v')
.help('help').alias('help', 'h')
.usage('npms-analyzer command line, c... |
Fix STPA modeling elements can't be loaded from saved model
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me> | """The RAAML Modeling Language module is the entrypoint for RAAML related
assets."""
import gaphor.SysML.propertypages # noqa
from gaphor.abc import ModelingLanguage
from gaphor.core import gettext
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
from gaphor.RAAML import diagramitems, raaml
from gaphor.RAA... | """The RAAML Modeling Language module is the entrypoint for RAAML related
assets."""
import gaphor.SysML.propertypages # noqa
from gaphor.abc import ModelingLanguage
from gaphor.core import gettext
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
from gaphor.RAAML import diagramitems
from gaphor.RAAML impo... |
Fix typo in search listener | package com.uservoice.uservoicesdk.ui;
import android.widget.SearchView;
import com.uservoice.uservoicesdk.activity.SearchActivity;
public class SearchQueryListener implements SearchView.OnQueryTextListener {
private final SearchActivity searchActivity;
public SearchQueryListener(SearchActivity searchActivi... | package com.uservoice.uservoicesdk.ui;
import android.widget.SearchView;
import com.uservoice.uservoicesdk.activity.SearchActivity;
public class SearchQueryListener implements SearchView.OnQueryTextListener {
private final SearchActivity searchActivity;
public SearchQueryListener(SearchActivity searchActivi... |
Add configuration flag to enable addon | /* jshint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
function readSnippet() {
try {
return fs.readFileSync(path.join(process.cwd(), 'vendor/newrelic-snippet.html'), {
encoding: 'UTF-8'
});
} catch(error) {
if (error.code === 'ENOENT') {
return '';
... | /* jshint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
function readSnippet() {
try {
return fs.readFileSync(path.join(process.cwd(), 'vendor/newrelic-snippet.html'), {
encoding: 'UTF-8'
});
} catch(error) {
if (error.code === 'ENOENT') {
return '';
... |
Load files using the new `pack` scene configuration. | import files from '@/constants/assets';
import fontConfig from '@/constants/bitmap-fonts';
export default class Loader extends Phaser.Scene {
/**
* Takes care of loading the main game assets.
*
* @extends Phaser.Scene
*/
constructor() {
super({key: 'Loader', pack: {files}});
}
/**
* Call... | import files from '@/constants/assets';
import fontConfig from '@/constants/bitmap-fonts';
export default class Loader extends Phaser.Scene {
/**
* Takes care of loading the main game assets.
*
* @extends Phaser.Scene
*/
constructor() {
super({key: 'Loader', files});
}
/**
* Called when ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.