text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use a map of persons instead of new ops every time
|
// Mailin List - Entry point
const Person = require('./person.js');
const Group = require('./group.js');
const MailList = require('./maillist.js');
const people = new Map();
people.set('akata', new Person('Katzuro Akata', 'katzuro@stringcraft.org'));
people.set('tateke', new Person('Makimoro Tateke', 'maki.tate@pebblestone.net'));
people.set('taichi', new Person('Bessimo Taichi', 'bessimo@smallspace.com'));
people.set('agata', new Person('Agata Selfborn', 'agata@selfborn.net'));
function test01() {
const g1 = new Group('list-developers');
g1.add(people.get('akata'));
g1.add(people.get('tateke'));
g1.add(people.get('taichi'));
const sender = people.get('agata');
const ml = new MailList();
ml.send(sender, g1, 'Hello guys! This is a test message. Greets');
ml.report();
const ml2 = new MailList();
ml2.send(sender, people.get('akata'), 'Hey Katzuro! How\'s it going? Cheeres!');
ml2.report();
}
test01();
// eof
|
// Mailin List - Entry point
const Person = require('./person.js');
const Group = require('./group.js');
const MailList = require('./maillist.js');
function test01() {
const g1 = new Group('list-developers');
g1.add(new Person('Katzuro Akata', 'katzuro@stringcraft.org'));
g1.add(new Person('Makimoro Tateke', 'maki.tate@pebblestone.net'));
g1.add(new Person('Bessimo Taichi', 'bessimo@smallspace.com'));
const sender = new Person('Agata Selfborn', 'agata@selfborn.net');
const ml = new MailList();
ml.send(sender, g1, 'Hello guys! This is a test message. Greets');
ml.report();
const ml2 = new MailList();
ml2.send(sender, new Person('Katzuro Akata', 'katzuro@stringcraft.org'),
'Hey Katzuro! How\'s it going? Cheeres!');
ml2.report();
}
test01();
// eof
|
Add random jitter to the exponential backoff function
|
"""
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
import random
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor):
"""
Simple wrapper to ThreadPoolExecutor that is also a singleton.
We want one ThreadPool that is used by all the spawners, rather
than one ThreadPool per spawner!
"""
pass
@gen.coroutine
def exponential_backoff(func, fail_message, timeout=10, *args, **kwargs):
loop = ioloop.IOLoop.current()
start_tic = loop.time()
dt = DT_MIN
while True:
if (loop.time() - start_tic) > timeout:
# We time out!
break
if func(*args, **kwargs):
return
else:
yield gen.sleep(dt)
# Add some random jitter to improve performance
# This makes sure that we don't overload any single iteration
# of the tornado loop with too many things
# See https://www.awsarchitectureblog.com/2015/03/backoff.html
# for a good example of why and how this helps
dt = min(DT_MAX, (1 + random.random()) * (dt * DT_SCALE))
raise TimeoutError(fail_message)
|
"""
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurable, ThreadPoolExecutor):
"""
Simple wrapper to ThreadPoolExecutor that is also a singleton.
We want one ThreadPool that is used by all the spawners, rather
than one ThreadPool per spawner!
"""
pass
@gen.coroutine
def exponential_backoff(func, fail_message, timeout=10, *args, **kwargs):
loop = ioloop.IOLoop.current()
tic = loop.time()
dt = DT_MIN
while dt > 0:
if func(*args, **kwargs):
return
else:
yield gen.sleep(dt)
dt = min(dt * DT_SCALE, DT_MAX, timeout - (loop.time() - tic))
raise TimeoutError(fail_message)
|
Exit with non-zero if Whiskey exists with non-zero.
|
#!/usr/bin/env node
var assert = require('../lib/assert').getAssertModule();
var exec = require('child_process').exec;
var sprintf = require('sprintf').sprintf;
var cwd = process.cwd();
exec(sprintf('NODE_PATH=lib-cov %s/bin/whiskey --tests %s/example/test-success-with-coverage.js --timeout 6000 --coverage --coverage-reporter cli', cwd, cwd),
function(err, stdout, stderr) {
try {
assert.match(stdout, /test coverage/i);
assert.match(stdout, /coverage\.js/);
assert.match(stdout, /loc/i);
assert.match(stdout, /sloc/i);
assert.match(stdout, /missed/i);
}
catch (err2) {
process.exit(5);
}
if (err && err.code !== 0) {
process.exit(5);
}
process.exit(0);
});
|
#!/usr/bin/env node
var assert = require('../lib/assert').getAssertModule();
var exec = require('child_process').exec;
var sprintf = require('sprintf').sprintf;
var cwd = process.cwd();
exec(sprintf('NODE_PATH=lib-cov %s/bin/whiskey --tests %s/example/test-success-with-coverage.js --timeout 6000 --coverage --coverage-reporter cli', cwd, cwd),
function(err, stdout, stderr) {
try {
assert.match(stdout, /test coverage/i);
assert.match(stdout, /coverage\.js/);
assert.match(stdout, /loc/i);
assert.match(stdout, /sloc/i);
assert.match(stdout, /missed/i);
}
catch (err2) {
process.exit(5);
}
process.exit(0);
});
|
Fix background for chrome dark mode
|
// TODO: This should be replaced with a styled-components theme
import { createGlobalStyle } from 'styled-components'
import Cookies from 'cookies-js'
export const toggle = mode => {
const { theme } = document.documentElement.dataset
const nextTheme = { dark: 'default', default: 'dark' }[theme]
document.documentElement.dataset.theme = mode || nextTheme
const cookieFlag = { dark: '1', default: '0' }[nextTheme]
Cookies.set('is-inverted', cookieFlag)
}
export default createGlobalStyle`
html[data-theme='dark'] {
&,
img,
canvas,
[style*='background-image'] {
filter: invert(100%) hue-rotate(180deg);
iframe {
filter: invert(100%) hue-rotate(180deg);
}
}
// Chrome
@media all and (-webkit-min-device-pixel-ratio: 0) and (min-resolution: 0.001dpcm) {
body {
background-color: white;
}
}
// Safari 8+
_::-webkit-full-page-media,
_:future,
:root {
body {
background-color: white;
}
}
}
`
|
// TODO: This should be replaced with a styled-components theme
import { createGlobalStyle } from 'styled-components'
import Cookies from 'cookies-js'
export const toggle = mode => {
const { theme } = document.documentElement.dataset
const nextTheme = { dark: 'default', default: 'dark' }[theme]
document.documentElement.dataset.theme = mode || nextTheme
const cookieFlag = { dark: '1', default: '0' }[nextTheme]
Cookies.set('is-inverted', cookieFlag)
}
export default createGlobalStyle`
html[data-theme='dark'] {
&,
img,
canvas,
[style*='background-image'] {
filter: invert(100%) hue-rotate(180deg);
iframe {
filter: invert(100%) hue-rotate(180deg);
}
}
// Chrome
@media all and (-webkit-min-device-pixel-ratio: 0) and (min-resolution: 0.001dpcm) {
body {
background-color: black;
}
}
// Safari 8+
_::-webkit-full-page-media,
_:future,
:root {
body {
background-color: white;
}
}
}
`
|
Add closing brace and paren lost in merge
|
var child_process = require('child_process');
describe('Fixture that needs a stub dataservice as a child process', function() {
before(function(done) {
myUnkillableChild =
child_process.exec('node ./child_root/child.js',
{},
function(err, stdout, stderr) {
debugger;
if (err) console.log(err);
console.log('My child process should be dead');
});
setTimeout(function() {
// Wait for a few seconds to ensure the server is up and running
// Then continue.
done();
}, 3000)
});
it('Mocha should run this test function before tearing down', function(done) {
debugger;
console.log('Hello world!');
done();
});
after(function(done) {
console.log('Sending SIGTERM signal to child process!');
myUnkillableChild.kill('SIGTERM');
done();
});
});
|
var child_process = require('child_process');
describe('Fixture that needs a stub dataservice as a child process', function() {
before(function(done) {
myUnkillableChild =
child_process.exec('node ./child_root/child.js',
{},
function(err, stdout, stderr) {
debugger;
if (err) console.log(err);
console.log('My child process should be dead');
});
setTimeout(function() {
// Wait for a few seconds to ensure the server is up and running
// Then continue.
done();
}, 3000)
});
it('Mocha should run this test function before tearing down', function(done) {
debugger;
console.log('Hello world!');
done();
});
after(function(done) {
console.log('Sending SIGTERM signal to child process!');
myUnkillableChild.kill('SIGTERM');
done();
});
|
Bring back echo to ensure stability
|
<?php
/*
* Layout functions
*/
// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
return true;
}
}
// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
$i = 0;
foreach (glob($dir . '/*') as $file) {
if (!is_dir($file)) {
$i++;
}
}
echo $i;
}
// `feedparse`
//
// Parses RSS or Atom feed.
function feedparse($url) {
$feed = fopen($url, 'r');
$data = stream_get_contents($feed);
fclose($feed);
echo $data;
}
// `selectrandom`
//
// Selects a random value from array.
function selectrandom($array) {
echo $array[array_rand($array)];
}
// `undot`
//
// Removes dots from string.
function undot($string) {
echo str_replace('.', '', $string);
}
|
<?php
/*
* Layout functions
*/
// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
return true;
}
}
// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
$i = 0;
foreach (glob($dir . '/*') as $file) {
if (!is_dir($file)) {
$i++;
}
}
echo $i;
}
// `feedparse`
//
// Parses RSS or Atom feed.
function feedparse($url) {
$feed = fopen($url, 'r');
$data = stream_get_contents($feed);
fclose($feed);
echo $data;
}
// `selectrandom`
//
// Selects a random value from array.
function selectrandom($array) {
echo $array[array_rand($array)];
}
// `undot`
//
// Removes dots from string.
function undot($string) {
$string = str_replace('.', '', $string);
}
|
Reduce SQLite connection pool size from 5 to 1
(hopefully fixes #1309)
|
/*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
/* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
storage: 'data/juiceshop.sqlite',
logging: false,
pool: {
max: 1
}
})
sequelizeNoUpdateAttributes(sequelize)
const db = {}
fs.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(modelName => {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
|
/*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
/* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
storage: 'data/juiceshop.sqlite',
logging: false
})
sequelizeNoUpdateAttributes(sequelize)
const db = {}
fs.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(modelName => {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
|
Add alt names for 7th chords
|
const chordRegex = require('../src/chord-regex')
const tape = require('tape')
tape('Regex against valid chords', function (test) {
let chords = [
'C', 'D', 'E', 'F', 'G', 'A', 'B', // white keys
'C#', 'Eb', 'F#', 'Ab', 'G#', 'Bb', // sharps and flats
'Db', 'D#', 'Gb', 'A#', // for those who like to use non-canon names for sharps and flats
'Cm', 'Caug', 'Cdim', 'Csus', 'Csus2', 'Csus4', // a few more triads
'Cm7', 'CM7', 'Cmaj7', 'CmM7', // 7ths
'C6', 'C9', 'C11', 'C13', // few more extension chords
'C/E', 'D/F#' // Slash chords
]
test.plan(chords.length)
chords.forEach(chord => {
const input = '[' + chord + ']'
if (chordRegex.exec(input) === null || chordRegex.exec(input).length === 0) {
test.fail('Failed for input: ' + input)
} else {
const match = chordRegex.exec(input)[1]
test.equal(match, chord, input + ' passed with match ' + match)
}
})
})
|
const chordRegex = require('../src/chord-regex')
const tape = require('tape')
tape('Regex against valid chords', function (test) {
let chords = [
'C', 'D', 'E', 'F', 'G', 'A', 'B', // white keys
'C#', 'Eb', 'F#', 'Ab', 'G#', 'Bb', // sharps and flats
'Db', 'D#', 'Gb', 'A#', // for those who like to use non-canon names for sharps and flats
'Cm', 'Cm7', 'CM7', 'Cmaj7', 'CmM7', // minors and 7ths
'C6', 'C9', 'C11', 'C13', // few more extension chords
'Caug', 'Cdim', 'Csus', 'Csus2', 'Csus4',
'C/E', 'D/F#' // Slash chords
]
console.log(chords.length)
test.plan(chords.length)
chords.forEach(chord => {
const input = '[' + chord + ']'
if (chordRegex.exec(input) === null || chordRegex.exec(input).length === 0) {
test.fail('Failed for input: ' + input)
} else {
const match = chordRegex.exec(input)[1]
test.equal(match, chord, input + ' passed with match ' + match)
}
})
})
|
Use sentence faker for email subjects
|
import factory
from adhocracy4.follows import models as follow_models
from adhocracy4.test import factories as a4_factories
from meinberlin.apps.newsletters import models
from tests import factories
# FIXME: copied from core
class FollowFactory(factory.django.DjangoModelFactory):
class Meta:
model = follow_models.Follow
creator = factory.SubFactory(factories.UserFactory)
project = factory.SubFactory(a4_factories.ProjectFactory)
class NewsletterFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Newsletter
sender = factory.Faker('email')
sender_name = factory.Faker('name')
subject = factory.Faker('sentence')
body = factory.Faker('text')
receivers = models.PROJECT
creator = factory.SubFactory(factories.UserFactory)
project = factory.SubFactory(a4_factories.ProjectFactory)
organisation = factory.SubFactory(factories.OrganisationFactory)
|
import factory
from adhocracy4.follows import models as follow_models
from adhocracy4.test import factories as a4_factories
from meinberlin.apps.newsletters import models
from tests import factories
# FIXME: copied from core
class FollowFactory(factory.django.DjangoModelFactory):
class Meta:
model = follow_models.Follow
creator = factory.SubFactory(factories.UserFactory)
project = factory.SubFactory(a4_factories.ProjectFactory)
class NewsletterFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Newsletter
sender = factory.Faker('email')
sender_name = factory.Faker('name')
subject = factory.Faker('text', max_nb_chars=120)
body = factory.Faker('text')
receivers = models.PROJECT
creator = factory.SubFactory(factories.UserFactory)
project = factory.SubFactory(a4_factories.ProjectFactory)
organisation = factory.SubFactory(factories.OrganisationFactory)
|
UPDATE - Forgot password . . . again
|
<?php
global $project;
$project = 'mysite';
global $databaseConfig;
$databaseConfig = array(
"type" => 'MySQLDatabase',
"server" => 'localhost',
"username" => 'root',
"password" => 'Redrooster8',
"database" => 'sitesprocket24',
"path" => '',
);
MySQLDatabase::set_connection_charset('utf8');
// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.org/themes/
SSViewer::set_theme('sitesprocket');
// Set the site locale
i18n::set_locale('en_US');
// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();
// Force WWW
//Director::forceWWW();
// Force environment to Dev
Director::set_environment_type('dev');
// Temporary fix for Cookie Issue
Cookie::set_report_errors(false);
// Set default Login
Security::setDefaultAdmin('admin','pass');
|
<?php
global $project;
$project = 'mysite';
global $databaseConfig;
$databaseConfig = array(
"type" => 'MySQLDatabase',
"server" => 'localhost',
"username" => 'root',
"password" => 'root',
"database" => 'sitesprocket24',
"path" => '',
);
MySQLDatabase::set_connection_charset('utf8');
// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.org/themes/
SSViewer::set_theme('sitesprocket');
// Set the site locale
i18n::set_locale('en_US');
// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();
// Force WWW
//Director::forceWWW();
// Force environment to Dev
Director::set_environment_type('dev');
// Temporary fix for Cookie Issue
Cookie::set_report_errors(false);
// Set default Login
Security::setDefaultAdmin('admin','pass');
|
Exclude chamber workflow from targets tested by j2 testall
PiperOrigin-RevId: 384424406
|
# Copyright 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Runs various tests in the repository."""
import argparse
import subprocess
import repo_util
def main(argv):
root = "//third_party/java_src/j2cl/"
cmd = ["blaze", "test", "--test_tag_filters=-chamber", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(argv.platforms)
subprocess.call(cmd)
def add_arguments(parser):
parser.add_argument(
"test_pattern",
metavar="<root>",
nargs="*",
help="test root(s). e.g. transpiler jre")
def run_for_presubmit():
argv = argparse.Namespace(test_pattern=[])
main(argv)
|
# Copyright 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Runs various tests in the repository."""
import argparse
import subprocess
import repo_util
def main(argv):
root = "//third_party/java_src/j2cl/"
cmd = ["blaze", "test", "--keep_going"]
cmd += [root + t + "/..." for t in argv.test_pattern] or [root + "..."]
cmd += repo_util.create_test_filter(argv.platforms)
subprocess.call(cmd)
def add_arguments(parser):
parser.add_argument(
"test_pattern",
metavar="<root>",
nargs="*",
help="test root(s). e.g. transpiler jre")
def run_for_presubmit():
argv = argparse.Namespace(test_pattern=[])
main(argv)
|
Use item.config to access config.
Fixes #1.
|
# -*- coding: utf-8 -*-
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.buildKey',
'BUILDKITE',
]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
"""Failing test cases are not a problem anymore."""
outcome = yield
rep = outcome.get_result()
examinators = EXAMINATORS
for examinator in item.config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
if any(os.environ.get(gaze, False) for gaze in examinators):
rep.outcome = 'passed'
def pytest_addoption(parser):
parser.addini('vw_examinators', 'List of additional VW examinators.')
|
# -*- coding: utf-8 -*-
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
_config = None
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.buildKey',
'BUILDKITE',
]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
"""Failing test cases are not a problem anymore."""
outcome = yield
rep = outcome.get_result()
examinators = EXAMINATORS
for examinator in _config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
if any(os.environ.get(gaze, False) for gaze in examinators):
rep.outcome = 'passed'
def pytest_configure(config):
global _config
_config = config
def pytest_addoption(parser):
parser.addini('vw_examinators', 'List of additional VW examinators.')
|
Add comments to merge sort.
|
package algoholic
// Merge Sort, O(n lg n) worst-case. Very beautiful.
func MergeSort(ns []int) []int {
// Base case - an empty or length 1 slice is trivially sorted.
if len(ns) < 2 {
// We need not allocate memory here as the at most 1 element will only be referenced
// once.
return ns
}
half := len(ns) / 2
// The wonder of merge sort - we sort each half of the slice using... merge sort :-)
// Where is your God now?
ns1 := MergeSort(ns[:half])
ns2 := MergeSort(ns[half:])
// We now have 2 separately sorted slices, merge them into one.
return Merge(ns1, ns2)
}
// Merge, O(n), merges two sorted slices into one.
func Merge(ns1, ns2 []int) []int {
length := len(ns1) + len(ns2)
ret := make([]int, length)
i, j := 0, 0
// We iterate through each element of the returned slice, placing elements of each of the
// input slices in their appropriate places.
//
// Loop Invariant: ret[:k] consists of ns1[:i] and ns2[:j] in sorted order.
for k := 0; k < length; k++ {
switch {
case j >= len(ns2) || ns1[i] <= ns2[j]:
ret[k] = ns1[i]
i++
case i >= len(ns1) || ns2[j] <= ns1[i]:
ret[k] = ns2[j]
j++
}
}
// When the loop is complete, i == len(ns1), j == len(ns2). Therefore our loop invariant
// determines that ret consists of ns1 and ns2 in sorted order, which matches the purpose
// of the function.
return ret
}
|
package algoholic
// Merge Sort, O(n lg n) worst-case. Very beautiful.
func MergeSort(ns []int) []int {
if len(ns) < 2 {
return ns
}
half := len(ns) / 2
ns1 := MergeSort(ns[:half])
ns2 := MergeSort(ns[half:])
return Merge(ns1, ns2)
}
func Merge(ns1, ns2 []int) []int {
length := len(ns1) + len(ns2)
ret := make([]int, length)
i, j := 0, 0
for k := 0; k < length; k++ {
switch {
case j >= len(ns2) || ns1[i] <= ns2[j]:
ret[k] = ns1[i]
i++
case i >= len(ns1) || ns2[j] <= ns1[i]:
ret[k] = ns2[j]
j++
}
}
return ret
}
|
Allow compression and whitespace trimming.
|
var os = require('os')
, path = require('path')
, express = require('express')
, less = require('less-middleware')
, tmp = path.join(os.tmpDir(), 'TesselKey')
, root = __dirname
, pub = path.join(root, 'public')
, images = path.join(pub, 'images')
, scripts = path.join(pub, 'scripts')
, views = path.join(root, 'views')
, app = express()
, trimmer = require('./modules/trimmer.js')
;
app.disable('x-powered-by');
app.configure(function() {
app.use(express.compress());
app.use(trimmer());
app.use(express.favicon());
app.use('/images', express.static(images));
app.use('/scripts', express.static(scripts));
app.use(less({ src: pub, dest: tmp }));
app.use(express.static(tmp));
app.use(express.static(views));
});
app.listen(80);
|
var os = require('os')
, path = require('path')
, express = require('express')
, less = require('less-middleware')
, tmp = path.join(os.tmpDir(), 'TesselKey')
, root = __dirname
, pub = path.join(root, 'public')
, images = path.join(pub, 'images')
, scripts = path.join(pub, 'scripts')
, views = path.join(root, 'views')
, app = express()
, trimmer = require('./modules/trimmer.js')
;
app.disable('x-powered-by');
app.configure(function() {
app.use(trimmer());
//app.use(express.compress());
app.use(express.favicon());
app.use('/images', express.static(images));
app.use('/scripts', express.static(scripts));
app.use(less({ src: pub, dest: tmp }));
app.use(express.static(tmp));
//app.use(trimmer());
app.use(express.static(views));
});
app.listen(80);
|
Adjust Settings UI for Chrome Now's Geolocation Source
BUG=164227
Review URL: https://codereview.chromium.org/26315007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@228326 0039d316-1c4b-4281-b951-d872f2087c98
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.define('options', function() {
var OptionsPage = options.OptionsPage;
/**
* GeolocationOptions class
* Handles initialization of the geolocation options.
* @constructor
* @class
*/
function GeolocationOptions() {
OptionsPage.call(this,
'geolocationOptions',
loadTimeData.getString('geolocationOptionsPageTabTitle'),
'geolocationCheckbox');
};
cr.addSingletonGetter(GeolocationOptions);
GeolocationOptions.prototype = {
__proto__: OptionsPage.prototype
};
// TODO(robliao): Determine if a full unroll is necessary
// (http://crbug.com/306613).
GeolocationOptions.showGeolocationOption = function() {};
return {
GeolocationOptions: GeolocationOptions
};
});
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.define('options', function() {
var OptionsPage = options.OptionsPage;
/**
* GeolocationOptions class
* Handles initialization of the geolocation options.
* @constructor
* @class
*/
function GeolocationOptions() {
OptionsPage.call(this,
'geolocationOptions',
loadTimeData.getString('geolocationOptionsPageTabTitle'),
'geolocationCheckbox');
};
cr.addSingletonGetter(GeolocationOptions);
GeolocationOptions.prototype = {
__proto__: OptionsPage.prototype
};
GeolocationOptions.showGeolocationOption = function() {
$('geolocationCheckbox').hidden = false;
};
return {
GeolocationOptions: GeolocationOptions
};
});
|
Use range instead of xrange as it is also available in python 3
|
from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.ascii_uppercase]
available_tiles.remove('Q')
available_tiles.append('Qu')
# A boggle board is an n * n square. Set n:
size = 10
board = []
for row in range(size):
board.append([random.choice(available_tiles) for i in range(size)])
found_words = list_words(
word_list=english_words,
board=board,
)
print(len(found_words))
main()
|
from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.ascii_uppercase]
available_tiles.remove('Q')
available_tiles.append('Qu')
# A boggle board is an n * n square. Set n:
size = 15
board = []
for row in range(size):
board.append([random.choice(available_tiles) for i in xrange(size)])
found_words = list_words(
word_list=english_words,
board=board,
)
print(len(found_words))
main()
|
Use a better unique strings.
|
import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
<div className="headline">ES6 Katas</div>
<div className="scrollable">
{katas.map(kata => <KataLink kata={kata} selected={selectedKataId === kata.id} />)}
</div>
</div>
);
}
}
class KataLink extends React.Component {
render() {
const {kata, selected} = this.props;
const {id, path, groupName, name} = kata;
const uniqueString = new Date().getMilliseconds();
const url = `${window.location.pathname}?${uniqueString}#?kata=es6/language/${path}`;
const className = selected ? 'selected' : '';
return (
<a href={url} title={`${groupName}: ${name}`} className={className}>{id}</a>
);
}
}
|
import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
<div className="headline">ES6 Katas</div>
<div className="scrollable">
{katas.map(kata => <KataLink kata={kata} selected={selectedKataId === kata.id} />)}
</div>
</div>
);
}
}
class KataLink extends React.Component {
render() {
const {kata, selected} = this.props;
const {id, path, groupName, name} = kata;
const url = `${window.location.pathname}?${('' + (0 + new Date() )).substr(-5)}#?kata=es6/language/${path}`;
const className = selected ? 'selected' : '';
return (
<a href={url} title={`${groupName}: ${name}`} className={className}>{id}</a>
);
}
}
|
Make stats quieter in logs.
|
import bunyan from 'bunyan';
import Promise from 'bluebird';
import SDC from 'statsd-client';
const logger = bunyan.createLogger({name: 'Stats'});
export default class Stats {
constructor(config) {
const stats = config.statsd;
logger.info('Starting StatsD client.');
this._statsd = new SDC({
host: stats.host
});
}
/**
* Get the underlying stats client.
* You should not rely on the type of this, only that it can be used
* as a middleware for express.
**/
get client() {
return this._statsd;
}
close() {
this._statsd.close();
}
counter(name, value = 1) {
logger.debug('Updating counter %s by %s.', name, value);
this._statsd.counter(name, value);
}
gauge(name, value) {
logger.debug('Gauging %s at %s.', name, value);
this._statsd.gauge(name, value);
}
}
|
import bunyan from 'bunyan';
import Promise from 'bluebird';
import SDC from 'statsd-client';
const logger = bunyan.createLogger({name: 'Stats'});
export default class Stats {
constructor(config) {
const stats = config.statsd;
logger.info('Starting StatsD client.');
this._statsd = new SDC({
host: stats.host
});
}
/**
* Get the underlying stats client.
* You should not rely on the type of this, only that it can be used
* as a middleware for express.
**/
get client() {
return this._statsd;
}
close() {
this._statsd.close();
}
counter(name, value = 1) {
logger.info('Updating counter %s by %s.', name, value);
this._statsd.counter(name, value);
}
gauge(name, value) {
logger.info('Gauging %s at %s.', name, value);
this._statsd.gauge(name, value);
}
}
|
[change] Change the time of loading external CSS
|
'use strict';
module.exports = {
input: 'src/*.css',
dir: 'dist',
use: [
'postcss-import',
'postcss-custom-properties',
'postcss-normalize-charset',
'autoprefixer',
'postcss-reporter'
],
'postcss-import': {
plugins: [
require('postcss-import-url'),
require('postcss-copy')({
src: './src',
dest: './dist',
template: file => {
return `assets/${file.name}.${file.ext}`;
},
relativePath: (dir, file, result, opts) => {
return opts.dest;
}
})
]
},
'postcss-custom-properties': {
preserve: true
},
autoprefixer: {
browsers: [
'> 1% in JP'
]
},
'postcss-reporter': {
clearMessages: true
}
}
|
'use strict';
module.exports = {
input: 'src/*.css',
dir: 'dist',
use: [
'postcss-import',
'postcss-import-url',
'postcss-custom-properties',
'postcss-normalize-charset',
'autoprefixer',
'postcss-reporter'
],
'postcss-import': {
plugins: [
require('postcss-copy')({
src: './src',
dest: './dist',
template: (file) => {
return `assets/${file.name}.${file.ext}`;
},
relativePath: (dir, file, result, opts) => {
return opts.dest;
}
})
]
},
'postcss-custom-properties': {
preserve: true
},
autoprefixer: {
browsers: [
'> 1% in JP'
]
},
'postcss-reporter': {
clearMessages: true
}
}
|
Add null check in TaskCache
|
package com.bastienleonard.tomate.models;
import android.support.annotation.Nullable;
import android.support.v4.util.SimpleArrayMap;
import java.util.List;
public final class TasksCache {
private SimpleArrayMap<String, Task> mTasks;
public TasksCache() {
}
// FIXME: directly parse the tasks JSON as a map if we never never need them as a list
public void setTasks(List<Task> tasks) {
if (mTasks == null) {
mTasks = new SimpleArrayMap<>(tasks.size());
}
for (Task task: tasks) {
mTasks.put(task.getCardId(), task);
}
}
@Nullable
public Task get(String cardId) {
if (mTasks == null) {
return null;
}
return mTasks.get(cardId);
}
}
|
package com.bastienleonard.tomate.models;
import android.support.annotation.Nullable;
import android.support.v4.util.SimpleArrayMap;
import java.util.List;
public final class TasksCache {
private SimpleArrayMap<String, Task> mTasks;
public TasksCache() {
}
// FIXME: directly parse the tasks JSON as a map if we never never need them as a list
public void setTasks(List<Task> tasks) {
if (mTasks == null) {
mTasks = new SimpleArrayMap<>(tasks.size());
}
for (Task task: tasks) {
mTasks.put(task.getCardId(), task);
}
}
@Nullable
public Task get(String cardId) {
return mTasks.get(cardId);
}
}
|
Add support for directories in CLI
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
var globby = require('globby');
var meow = require('meow');
var updateNotifier = require('update-notifier');
var cli = meow({
help: [
'Usage',
' ava <file> [<file> ...]',
'',
'Example',
' ava test.js test2.js'
].join('\n')
}, {
string: ['_']
});
function run(file) {
fs.stat(file, function (err, stats) {
if (err) {
console.error(err.message);
process.exit(1);
}
if (stats.isDirectory()) {
init(path.join(file, '*.js'));
return;
}
require(file);
});
}
function init(files) {
globby(files, function (err, files) {
if (err) {
console.error(err.message);
process.exit(1);
}
files.forEach(function (file) {
run(path.resolve(process.cwd(), file));
});
});
}
updateNotifier({
packageName: cli.pkg.name,
packageVersion: cli.pkg.version
}).notify();
if (cli.input.length === 0) {
console.error('Input required');
process.exit(1);
}
init(cli.input);
|
#!/usr/bin/env node
'use strict';
var path = require('path');
var globby = require('globby');
var meow = require('meow');
var updateNotifier = require('update-notifier');
var cli = meow({
help: [
'Usage',
' ava <file> [<file> ...]',
'',
'Example',
' ava test.js test2.js'
].join('\n')
}, {
string: ['_']
});
updateNotifier({
packageName: cli.pkg.name,
packageVersion: cli.pkg.version
}).notify();
if (cli.input.length === 0) {
console.error('Input required');
process.exit(1);
}
globby(cli.input, function (err, files) {
if (err) {
console.error(err.message);
process.exit(1);
}
files.forEach(function (file) {
require(path.resolve(process.cwd(), file));
});
});
|
Add missing javadoc and block constructors
|
/*
* Copyright 2017 Daniel Pedraza-Arcega
*
* 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.danzx.zekke.message.impl;
import com.github.danzx.zekke.message.MessageSource;
/**
* Creates message sources.
*
* @author Daniel Pedraza-Arcega
*/
public class MessageSourceFactory {
private MessageSourceFactory() {
throw new AssertionError();
}
/** @return the default message source for this application. */
public static MessageSource defaultSource() {
return InstanceHolder.INSTANCE;
}
private static class InstanceHolder {
private static final String MESSAGES_BASENAME = "com.github.danzx.zekke.Messages";
private static final MessageSource INSTANCE = new DefaultMessageDecorator(new ResourceBundleMessageSource(MESSAGES_BASENAME));
private InstanceHolder() {
throw new AssertionError();
}
}
}
|
/*
* Copyright 2017 Daniel Pedraza-Arcega
*
* 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.danzx.zekke.message.impl;
import com.github.danzx.zekke.message.MessageSource;
/**
* @author Daniel Pedraza-Arcega
*/
public class MessageSourceFactory {
public static MessageSource defaultSource() {
return InstanceHolder.INSTANCE;
}
private static class InstanceHolder {
private static final String MESSAGES_BASENAME = "com.github.danzx.zekke.Messages";
private static final MessageSource INSTANCE = new DefaultMessageDecorator(new ResourceBundleMessageSource(MESSAGES_BASENAME));
}
}
|
Revert to old version of Backbone
Sync doesn't work properly in the latest release. (Though it does work in the
current master...)
|
require.config({
baseUrl: "/static/scripts/src",
paths: {
// Dependencies:
"underscore": "lib/underscore-min",
"backbone": "lib/backbone",
"jquery": "lib/jquery-3.1.1.min",
"chartjs": "lib/Chart.min"
},
moduleDefaults: {
"build/templates": {}
},
shim: {
chartjs: {exports: "Chart"},
leaflet: {exports: "L"},
underscore: {exports: "_"},
backbone: {deps: ["underscore", "jquery"],
exports: "Backbone"}
}
});
require(["setup"], function(setup) {
window.app = setup.start();
});
|
require.config({
baseUrl: "/static/scripts/src",
paths: {
// Dependencies:
"underscore": "lib/underscore-min",
"backbone": "lib/backbone-min",
"jquery": "lib/jquery-3.1.1.min",
"chartjs": "lib/Chart.min"
},
moduleDefaults: {
"build/templates": {}
},
shim: {
chartjs: {exports: "Chart"},
leaflet: {exports: "L"},
underscore: {exports: "_"},
backbone: {deps: ["underscore", "jquery"],
exports: "Backbone"}
}
});
require(["setup"], function(setup) {
window.app = setup.start();
});
|
Correct check if assertion verification failed.
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
Enable cache for 'get' API call to /cards
|
export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.path = path;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {
this.$log.info('api:create()', data, this);
return this.$http.post(`${this.url}`, data);
}
get(query = '') {
let httpObj = {
method: 'GET',
url: `${this.url}/${query}`,
cache: this.path === 'cards' ? true : false
}
this.$log.info('api:get()', query, this);
return this.$http(httpObj);
}
remove(id) {
this.$log.info('api:remove()', id, this);
return this.$http.delete(`${this.url}/${id}`);
}
update(id, data) {
this.$log.info('api:update()', id, data, this);
return this.$http.post(`${this.url}/${id}`, data);
}
}
|
export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {
this.$log.info('api:create()', data, this);
return this.$http.post(`${this.url}`, data);
}
get(query = '') {
this.$log.info('api:get()', query, this);
return this.$http.get(`${this.url}/${query}`);
}
remove(id) {
this.$log.info('api:remove()', id, this);
return this.$http.delete(`${this.url}/${id}`);
}
update(id, data) {
this.$log.info('api:update()', id, data, this);
return this.$http.post(`${this.url}/${id}`, data);
}
}
|
Remove unused part of code
Change-Id: I2cc8c4b4ef6e4a5b3889edb1dd2fa1a9fc09bd94
|
//= require diamond/thesis_menu
$(document).ready(function() {
$(".link-export").click(function() {
$(this).attr("href", $.clear_query_params($(this).attr("href"))+window.location.search);
});
$("button.select-all").click(function() {
$("button.button-checkbox", "div.theses-list").trigger("checkbox-change-state");
});
$("button.destroy-all").lazy_form_confirmable_action({
topic: 'confirmation_theses_delete',
success_action: function(obj, key, val) {
$("#thesis-"+key).remove();
}
});
$("button.deny-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_deny',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
$("button.accept-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_accept',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
});
|
//= require diamond/thesis_menu
$(document).ready(function() {
$(".link-export").click(function() {
$(this).attr("href", $.clear_query_params($(this).attr("href"))+window.location.search);
});
$("button.select-all").click(function() {
$("button.button-checkbox", "div.theses-list").trigger("checkbox-change-state");
});
$("button.destroy-all").lazy_form_confirmable_action({
topic: 'confirmation_theses_delete',
success_action: function(obj, key, val) {
$("#thesis-"+key).remove();
}
});
$("button.deny-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_deny',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
$("button.accept-selected").lazy_form_confirmable_action({
topic: 'confirmation_theses_accept',
success_action: function(obj, key, value) {
$("#thesis-"+key).replaceWith($.parseHTML(value));
}
});
});
$.widget( "core.per_page_paginator", $.core.loader, {
before_state_changed: function(ctxt, e) {
$("input[name='per_page']", ctxt).val($(e.currentTarget).html());
$("input[name='page']", ctxt).val(1);
}
});
|
Fix doc for non-existing parameter
|
<?php
namespace Brick\Money\Context;
use Brick\Money\Context;
use Brick\Money\Currency;
use Brick\Math\BigNumber;
/**
* Adjusts the scale & step of the result to custom values.
*/
class PrecisionContext implements Context
{
/**
* @var int
*/
private $scale;
/**
* @var int
*/
private $step;
/**
* @param int $scale
* @param int $step
*/
public function __construct($scale, $step = 1)
{
$this->scale = (int) $scale;
$this->step = (int) $step;
}
/**
* {@inheritdoc}
*/
public function applyTo(BigNumber $amount, Currency $currency, $roundingMode)
{
if ($this->step === 1) {
return $amount->toScale($this->scale, $roundingMode);
}
return $amount
->toBigRational()
->dividedBy($this->step)
->toScale($this->scale, $roundingMode)
->multipliedBy($this->step);
}
/**
* {@inheritdoc}
*/
public function getStep()
{
return $this->step;
}
}
|
<?php
namespace Brick\Money\Context;
use Brick\Money\Context;
use Brick\Money\Currency;
use Brick\Math\BigNumber;
/**
* Adjusts the scale & step of the result to custom values.
*/
class PrecisionContext implements Context
{
/**
* @var int
*/
private $scale;
/**
* @var int
*/
private $step;
/**
* @param int $scale
* @param int $step
* @param int $roundingMode
*/
public function __construct($scale, $step = 1)
{
$this->scale = (int) $scale;
$this->step = (int) $step;
}
/**
* {@inheritdoc}
*/
public function applyTo(BigNumber $amount, Currency $currency, $roundingMode)
{
if ($this->step === 1) {
return $amount->toScale($this->scale, $roundingMode);
}
return $amount
->toBigRational()
->dividedBy($this->step)
->toScale($this->scale, $roundingMode)
->multipliedBy($this->step);
}
/**
* {@inheritdoc}
*/
public function getStep()
{
return $this->step;
}
}
|
Migrate to PlaceholderExpansion from PlaceholderAPI
|
package com.github.games647.fastlogin.bukkit;
import java.util.stream.Collectors;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
public class PremiumPlaceholder extends PlaceholderExpansion {
private static final String PLACEHOLDER_VARIABLE = "fastlogin_status";
private final FastLoginBukkit plugin;
public PremiumPlaceholder(FastLoginBukkit plugin) {
this.plugin = plugin;
}
public static void register(FastLoginBukkit plugin) {
PremiumPlaceholder placeholderHook = new PremiumPlaceholder(plugin);
PlaceholderAPI.registerPlaceholderHook(PLACEHOLDER_VARIABLE, placeholderHook);
}
@Override
public String onPlaceholderRequest(Player player, String variable) {
if (player != null && PLACEHOLDER_VARIABLE.equals(variable)) {
return plugin.getStatus(player.getUniqueId()).name();
}
return "";
}
@Override
public String getIdentifier() {
return PLACEHOLDER_VARIABLE;
}
@Override
public String getPlugin() {
return plugin.getName();
}
@Override
public String getAuthor() {
return plugin.getDescription().getAuthors().stream().collect(Collectors.joining(", "));
}
@Override
public String getVersion() {
return plugin.getName();
}
}
|
package com.github.games647.fastlogin.bukkit;
import java.util.List;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderHook;
import org.bukkit.entity.Player;
import org.bukkit.metadata.MetadataValue;
public class PremiumPlaceholder extends PlaceholderHook {
private final FastLoginBukkit plugin;
public PremiumPlaceholder(FastLoginBukkit plugin) {
this.plugin = plugin;
}
@Override
public String onPlaceholderRequest(Player player, String variable) {
if (player != null && "fastlogin_status".contains(variable)) {
List<MetadataValue> metadata = player.getMetadata(plugin.getName());
if (metadata == null) {
return "unknown";
}
if (metadata.isEmpty()) {
return "cracked";
} else {
return "premium";
}
}
return "";
}
public static void register(FastLoginBukkit plugin) {
PlaceholderAPI.registerPlaceholderHook(plugin, new PremiumPlaceholder(plugin));
}
}
|
Convert numpy int to native int for JSON serialization
|
from analyses.mimp import glycosylation_sub_types, run_mimp
from helpers.plots import stacked_bar_plot
from ..store import counter
@counter
@stacked_bar_plot
def gains_and_losses_for_glycosylation_subtypes():
results = {}
effects = 'loss', 'gain'
for source_name in ['mc3', 'clinvar']:
for site_type_name in glycosylation_sub_types:
result = run_mimp(source_name, site_type_name, enzyme_type='catch-all')
if result.empty:
continue
effect_counts = result.effect.value_counts()
results[source_name] = effects, [
int(effect_counts.get(effect, 0))
for effect in effects
]
return results
|
from analyses.mimp import glycosylation_sub_types, run_mimp
from helpers.plots import stacked_bar_plot
from ..store import counter
@counter
@stacked_bar_plot
def gains_and_losses_for_glycosylation_subtypes():
results = {}
effects = 'loss', 'gain'
for source_name in ['mc3', 'clinvar']:
for site_type_name in glycosylation_sub_types:
result = run_mimp(source_name, site_type_name, enzyme_type='catch-all')
if result.empty:
continue
effect_counts = result.effect.value_counts()
results[source_name] = effects, [effect_counts.get(effect, 0) for effect in effects]
return results
|
Set group as read only when inviting students
|
from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
group.read_only = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user,
"invite_sent",
group=group)
|
from aiohttp.web import Application
from db_helper import get_most_recent_group
from mail import send_user_email
from permissions import get_users_with_permission
async def student_invite(app: Application) -> None:
print("Inviting students")
session = app["session"]
group = get_most_recent_group(session)
group.student_viewable = True
group.student_choosable = True
for user in get_users_with_permission(app, "join_projects"):
await send_user_email(app,
user,
"invite_sent",
group=group)
|
Fix errors showing up because 'email' is not set
|
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$beginning = '<div class="container"><nav class="navbar navbar-default "><div class="navbar-header">
<a class="navbar-brand">Navigation Bar </a>
</div><ul class="nav navbar-nav justified">';
$frontLink = '<li class="nav-item"> <a class="" href="';
$endLink = '</a></li>';
if (isset($_SESSION['user-type'])) {
echo $beginning;
switch ($_SESSION['user-type']) {
case 'doctor':
$email = $_SESSION['email'];
$result = getDoctorDetails($email);
$speciality = $result['speciality'];
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
break;
case 'clerk':
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
break;
default:
// code...
break;
}
echo '</ul> </nav></div>';
}
?>
|
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$beginning = '<div class="container"><nav class="navbar navbar-default "><div class="navbar-header">
<a class="navbar-brand">Navigation Bar </a>
</div><ul class="nav navbar-nav justified">';
$frontLink = '<li class="nav-item"> <a class="" href="';
$endLink = '</a></li>';
if (isset($_SESSION['user-type'])) {
echo $beginning;
$email = $_SESSION['email'];
switch ($_SESSION['user-type']) {
case 'doctor':
$result = getDoctorDetails($email);
$speciality = $result['speciality'];
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
break;
case 'clerk':
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
break;
default:
// code...
break;
}
echo '</ul> </nav></div>';
}
?>
|
Fix telescope-search route for iron:router 1.0
The ``onBeforeAction`` in ``PostsSearchController`` isn't calling ``this.next()``, and so is never dispatching.
|
adminNav.push({
route: 'searchLogs',
label: 'Search Logs'
});
Meteor.startup(function () {
PostsSearchController = PostsListController.extend({
view: 'search',
onBeforeAction: function() {
if ("q" in this.params) {
Session.set("searchQuery", this.params.q);
}
this.next();
}
});
Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']});
// Search
Router.route('/search/:limit?', {
name: 'search',
controller: PostsSearchController
});
// Search Logs
Router.route('/logs/:limit?', {
name: 'searchLogs',
waitOn: function () {
var limit = this.params.limit || 100;
if(Meteor.isClient) {
Session.set('logsLimit', limit);
}
return Meteor.subscribe('searches', limit);
},
data: function () {
return Searches.find({}, {sort: {timestamp: -1}});
},
fastRender: true
});
});
|
adminNav.push({
route: 'searchLogs',
label: 'Search Logs'
});
Meteor.startup(function () {
PostsSearchController = PostsListController.extend({
view: 'search',
onBeforeAction: function() {
if ("q" in this.params) {
Session.set("searchQuery", this.params.q);
}
}
});
Router.onBeforeAction(Router._filters.isAdmin, {only: ['logs']});
// Search
Router.route('/search/:limit?', {
name: 'search',
controller: PostsSearchController
});
// Search Logs
Router.route('/logs/:limit?', {
name: 'searchLogs',
waitOn: function () {
var limit = this.params.limit || 100;
if(Meteor.isClient) {
Session.set('logsLimit', limit);
}
return Meteor.subscribe('searches', limit);
},
data: function () {
return Searches.find({}, {sort: {timestamp: -1}});
},
fastRender: true
});
});
|
Add example points for InfluxDB
|
import serial
import schedule
import time
import json
from flask import Flask, request
from threading import Thread
from influxdb import InfluxDBClient
COM_PORT = 2
BAUDRATE = 9600
READ_SENSORS_TIMER = 1
DB_HOST = '192.168.1.73'
DB_PORT = 8086
DB_NAME = 'awarehouse'
DB_PASS = 'admin'
DB_USER = 'admin'
influxdb = InfluxDBClient(DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME)
ser = serial.Serial(COM_PORT, BAUDRATE)
app = Flask(__name__)
start_time = time.time()
def get_sensors():
# ser.write('r')
json = "fixme" # ser.readline()
influxdb.write_points([{
"points": [[20.44, 30, 231]],
"name": "sensors",
"columns": ["temp1", "light_sensor", "light"]
}])
print json
def run_schedule():
while 1:
schedule.run_pending()
time.sleep(1)
@app.route('/', methods=['GET'])
def index():
return '<html>test</html>'
if __name__ == '__main__':
schedule.every(READ_SENSORS_TIMER).seconds.do(get_sensors)
t = Thread(target=run_schedule)
t.start()
app.run(debug=True, use_reloader=False, host='0.0.0.0', port=5000)
ser.close()
|
import serial
import schedule
import time
from flask import Flask, request
from threading import Thread
from influxdb import InfluxDBClient
COM_PORT = 2
BAUDRATE = 9600
READ_THREAD = 10
DB_HOST = 'localhost'
DB_HOST_PORT = 8086
DB_NAME = 'awarehouse'
DB_PASS = 'admin'
DB_USER = 'admin'
influxdb = InfluxDBClient(DB_HOST, DB_HOST_PORT, DB_USER, DB_PASS, DB_NAME)
ser = serial.Serial(COM_PORT, BAUDRATE)
app = Flask(__name__)
start_time = time.time()
def get_sensors():
ser.write('r')
json = ser.readline()
influxdb.write_points([json])
print json
def run_schedule():
while 1:
schedule.run_pending()
time.sleep(1)
@app.route('/', methods=['GET'])
def index():
return '<html>test</html>'
if __name__ == '__main__':
schedule.every(READ_THREAD).seconds.do(get_sensors)
t = Thread(target=run_schedule)
t.start()
app.run(debug=True, use_reloader=False, host='0.0.0.0', port=5000)
ser.close()
|
Fix $.wrap for null
This also fixes $ for when no element is found
|
const flatten = require('flatten')
const Set = require('es6-set')
function normalizeRoot(root) {
if(!root) return document
if(typeof(root) == 'string') return $(root)
return root
}
function $(selector, root) {
root = normalizeRoot(root)
return wrapNode(root.querySelector(selector))
}
$.all = function $$(selector, root) {
root = normalizeRoot(root)
return [].slice.call(root.querySelectorAll(selector)).map(function(node) {
return wrapNode(node)
})
}
$.wrap = function(node) {
if(typeof(node.length) == 'number') {
return [].slice.call(node).map(function(node) {
return wrapNode(node)
})
} else {
return wrapNode(node)
}
}
function wrapNode(node) {
if(!node) return null
node.find = function(sel) {
return $(sel, node)
}
node.findAll = function(sel) {
return $.all(sel, node)
}
return node
}
module.exports = $
window.$ = $
|
const flatten = require('flatten')
const Set = require('es6-set')
function normalizeRoot(root) {
if(!root) return document
if(typeof(root) == 'string') return $(root)
return root
}
function $(selector, root) {
root = normalizeRoot(root)
return wrapNode(root.querySelector(selector))
}
$.all = function $$(selector, root) {
root = normalizeRoot(root)
return [].slice.call(root.querySelectorAll(selector)).map(function(node) {
return wrapNode(node)
})
}
$.wrap = function(node) {
if(typeof(node.length) == 'number') {
return [].slice.call(node).map(function(node) {
return wrapNode(node)
})
} else {
return wrapNode(node)
}
}
function wrapNode(node) {
node.find = function(sel) {
return $(sel, node)
}
node.findAll = function(sel) {
return $.all(sel, node)
}
return node
}
module.exports = $
window.$ = $
|
Add additional jquery expose-loader to global $
|
// Common webpack configuration used by webpack.hot.config and webpack.rails.config.
const path = require('path');
module.exports = {
// the project dir
context: __dirname,
entry: ['jquery', 'jquery-ujs', './assets/javascripts/App'],
resolve: {
root: [
path.join(__dirname, 'scripts'),
path.join(__dirname, 'assets/javascripts'),
],
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.scss', '.css', 'config.js'],
},
module: {
loaders: [
// React is necessary for the client rendering:
{test: require.resolve('react'), loader: 'expose?React'},
{test: require.resolve('jquery'), loader: 'expose?jQuery'},
{test: require.resolve('jquery'), loader: 'expose?$'},
],
},
};
|
// Common webpack configuration used by webpack.hot.config and webpack.rails.config.
const path = require('path');
module.exports = {
// the project dir
context: __dirname,
entry: ['jquery', 'jquery-ujs', './assets/javascripts/App'],
resolve: {
root: [
path.join(__dirname, 'scripts'),
path.join(__dirname, 'assets/javascripts'),
],
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.scss', '.css', 'config.js'],
},
module: {
loaders: [
// React is necessary for the client rendering:
{test: require.resolve('react'), loader: 'expose?React'},
{test: require.resolve('jquery'), loader: 'expose?jQuery'},
],
},
};
|
Add comment about setting unfriendly_mode.
|
package uk.ac.cam.gpe21.droidssl.analysis;
import soot.PackManager;
import soot.Transform;
import soot.options.Options;
import java.util.Arrays;
public final class StaticAnalyser {
public static void main(String[] args) {
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_output_format(Options.output_format_none);
Options.v().set_android_jars("/opt/android/platforms");
Options.v().set_process_dir(Arrays.asList("test-hv/build/apk/test-hv-release-unsigned.apk"));
/*
* We configure Soot with the Options class and then call its main()
* method with an empty arguments array. Enabling unfriendly mode stops
* Soot from printing the help because of the empty arguments array.
*/
Options.v().set_unfriendly_mode(true);
PackManager.v().getPack("jtp").add(new Transform("jtp.allow_all_hostname_verifier", new AllowAllHostnameVerifierTransformer()));
soot.Main.main(new String[0]);
}
}
|
package uk.ac.cam.gpe21.droidssl.analysis;
import soot.PackManager;
import soot.Transform;
import soot.options.Options;
import java.util.Arrays;
public final class StaticAnalyser {
public static void main(String[] args) {
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_output_format(Options.output_format_none);
Options.v().set_android_jars("/opt/android/platforms");
Options.v().set_process_dir(Arrays.asList("test-hv/build/apk/test-hv-release-unsigned.apk"));
Options.v().set_unfriendly_mode(true);
PackManager.v().getPack("jtp").add(new Transform("jtp.allow_all_hostname_verifier", new AllowAllHostnameVerifierTransformer()));
soot.Main.main(new String[0]);
}
}
|
Adjust to scalar types introduced in Locale component & bundle
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\Context;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Locale\Context\LocaleNotFoundException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
final class AdminBasedLocaleContext implements LocaleContextInterface
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* {@inheritdoc}
*/
public function getLocaleCode(): string
{
$token = $this->tokenStorage->getToken();
if (null === $token) {
throw new LocaleNotFoundException();
}
$user = $token->getUser();
if (!$user instanceof AdminUserInterface) {
throw new LocaleNotFoundException();
}
return $user->getLocaleCode();
}
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\Context;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Locale\Context\LocaleNotFoundException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
final class AdminBasedLocaleContext implements LocaleContextInterface
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* {@inheritdoc}
*/
public function getLocaleCode()
{
$token = $this->tokenStorage->getToken();
if (null === $token) {
throw new LocaleNotFoundException();
}
$user = $token->getUser();
if (!$user instanceof AdminUserInterface) {
throw new LocaleNotFoundException();
}
return $user->getLocaleCode();
}
}
|
Add a 'type()' function to resources for policy engines to lookup policies
|
from abc import ABCMeta, abstractmethod
from googleapiclienthelpers.discovery import build_subresource
class ResourceBase(metaclass=ABCMeta):
@abstractmethod
def get(self):
pass
@abstractmethod
def update(self):
pass
class GoogleAPIResourceBase(ResourceBase, metaclass=ABCMeta):
# Names of the get and update methods. Most are the same but override in
# the Resource if necessary
get_method = "get"
update_method = "update"
def __init__(self, resource_data, **kwargs):
full_resource_path = "{}.{}".format(
self.service_name,
self.resource_path
)
self.service = build_subresource(
full_resource_path,
self.version,
**kwargs
)
self.resource_data = resource_data
def type(self):
return ".".join(["gcp", self.service_name, self.resource_path])
def get(self):
method = getattr(self.service, self.get_method)
return method(**self._get_request_args()).execute()
def update(self, body):
method = getattr(self.service, self.update_method)
return method(**self._update_request_args(body)).execute()
|
from abc import ABCMeta, abstractmethod
from googleapiclienthelpers.discovery import build_subresource
class ResourceBase(metaclass=ABCMeta):
@abstractmethod
def get(self):
pass
@abstractmethod
def update(self):
pass
class GoogleAPIResourceBase(ResourceBase, metaclass=ABCMeta):
# Names of the get and update methods. Most are the same but override in
# the Resource if necessary
get_method = "get"
update_method = "update"
def __init__(self, resource_data, **kwargs):
full_resource_path = "{}.{}".format(
self.service_name,
self.resource_path
)
self.service = build_subresource(
full_resource_path,
self.version,
**kwargs
)
self.resource_data = resource_data
def get(self):
method = getattr(self.service, self.get_method)
return method(**self._get_request_args()).execute()
def update(self, body):
method = getattr(self.service, self.update_method)
return method(**self._update_request_args(body)).execute()
|
Remove unused custom http client
|
package skin
import (
"errors"
"fmt"
"image/png"
"net/http"
)
const (
skinURL = "http://skins.minecraft.net/MinecraftSkins/%s.png"
)
func Download(player string) (skin *Skin, err error) {
resp, err := http.Get(fmt.Sprintf(skinURL, player))
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
err = errors.New(resp.Request.URL.String() + " returned " + resp.Status)
return
}
contentType := resp.Header.Get("Content-Type")
if contentType != "image/png" {
err = errors.New("expected image/png, " + resp.Request.URL.String() + " returned " + contentType + " instead")
return
}
defer resp.Body.Close()
img, err := png.Decode(resp.Body)
if err != nil {
return
}
return (*Skin)(rgba(img)), nil
}
|
package skin
import (
"errors"
"fmt"
"image/png"
"net/http"
)
const (
skinURL = "http://skins.minecraft.net/MinecraftSkins/%s.png"
)
// Follow all redirects
var skinClient = &http.Client{
CheckRedirect: func(*http.Request, []*http.Request) error {
return nil
},
}
func Download(player string) (skin *Skin, err error) {
resp, err := http.Get(fmt.Sprintf(skinURL, player))
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
err = errors.New(resp.Request.URL.String() + " returned " + resp.Status)
return
}
contentType := resp.Header.Get("Content-Type")
if contentType != "image/png" {
err = errors.New("expected image/png, " + resp.Request.URL.String() + " returned " + contentType + " instead")
return
}
defer resp.Body.Close()
img, err := png.Decode(resp.Body)
if err != nil {
return
}
return (*Skin)(rgba(img)), nil
}
|
Add a key/value pairs parameter type
|
from collections import OrderedDict
from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label
class Integer(Parameter):
def __init__(self, default=None, label=None, range=None, step=1):
super(Integer, self).__init__(default, label)
self.range = range
self.step = step
class KeyValuePairs(Parameter):
def __init__(self, default=None, label=None):
default = default if default is not None else OrderedDict()
super().__init__(default, label)
class PathList(Parameter):
def __init__(self, default=None, label=None):
default = default if default is not None else []
super().__init__(default, label)
class String(Parameter):
def __init__(self, default=None, label=None, choices=None):
super(String, self).__init__(default, label)
self.choices = choices
|
from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label
class Integer(Parameter):
def __init__(self, default=None, label=None, range=None, step=1):
super(Integer, self).__init__(default, label)
self.range = range
self.step = step
class PathList(Parameter):
def __init__(self, default=None, label=None):
default = default if default is not None else []
super().__init__(default, label)
class String(Parameter):
def __init__(self, default=None, label=None, choices=None):
super(String, self).__init__(default, label)
self.choices = choices
|
Update docker-images to version 45
|
/*
* 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.tests.product.launcher.env;
public final class EnvironmentDefaults
{
public static final String DOCKER_IMAGES_VERSION = "45";
public static final String HADOOP_BASE_IMAGE = "ghcr.io/trinodb/testing/hdp2.6-hive";
public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";
private EnvironmentDefaults() {}
}
|
/*
* 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.tests.product.launcher.env;
public final class EnvironmentDefaults
{
public static final String DOCKER_IMAGES_VERSION = "43";
public static final String HADOOP_BASE_IMAGE = "ghcr.io/trinodb/testing/hdp2.6-hive";
public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";
private EnvironmentDefaults() {}
}
|
Allow PasswordFun to return an error
|
package ssh
import "os"
type C struct {
User string
Host string
HostKeyFun func([]byte)os.Error
PasswordFun func()(string,os.Error)
}
func New(C C) (*Client,os.Error) {
c,e := connect(C.Host)
if e != nil { return nil,e }
writeKexInit(c)
b,e := readPacket(c)
c.skex = make([]byte, len(b))
copy(c.skex, b)
if e!=nil { return nil,e }
k,e := parseKexInit(c,b[1:])
Log(6,"%v",k)
if e!=nil { return nil,e }
e = dh(c,k,&C)
if e!=nil { return nil,e }
client := &Client{ssh: c}
for C.PasswordFun!=nil {
pass,err := C.PasswordFun()
if err!=nil {
return nil,err
}
if password(c,C.User, pass) {
break
}
}
startClientLoop(client)
return client, nil
}
|
package ssh
import "os"
type C struct {
User string
Host string
HostKeyFun func([]byte)os.Error
PasswordFun func()string
}
func New(C C) (*Client,os.Error) {
c,e := connect(C.Host)
if e != nil { return nil,e }
writeKexInit(c)
b,e := readPacket(c)
c.skex = make([]byte, len(b))
copy(c.skex, b)
if e!=nil { return nil,e }
k,e := parseKexInit(c,b[1:])
Log(6,"%v",k)
if e!=nil { return nil,e }
e = dh(c,k,&C)
if e!=nil { return nil,e }
client := &Client{ssh: c}
for C.PasswordFun!=nil && !password(c,C.User, C.PasswordFun()) {}
startClientLoop(client)
return client, nil
}
|
Create Error instances when errors happen
|
var config = require("config")
, crypto = require("crypto")
, request = require("request")
, github = require("./github")
module.exports.generateNonce = function (length) {
return crypto.randomBytes(length * 2).toString("hex").slice(0, length)
}
module.exports.requestAccessToken = function (code, cb) {
var tokenRequest = {
url: "https://github.com/login/oauth/access_token",
json: {
client_id: config.github.oauth.id,
client_secret: config.github.oauth.secret,
code: code
}
}
request.post(tokenRequest, function (err, tokenRes, data) {
if (err || tokenRes.statusCode !== 200) {
return cb(err || new Error("Unable to exchange code for token"))
}
data = data || {}
if (!data.access_token) {
return cb(new Error("Failed to receive access token from GitHub"))
}
var authData = { access_token: data.access_token }
, gh = github.getInstance(data.access_token)
gh.user.get({}, function (err, data) {
if (err) {
return cb(err)
} else if (!data.login) {
return cb(new Error("Unable to find user from token"))
}
authData.user = data.login
cb(null, authData)
})
})
}
|
var config = require("config")
, crypto = require("crypto")
, request = require("request")
, github = require("./github")
module.exports.generateNonce = function (length) {
return crypto.randomBytes(length * 2).toString("hex").slice(0, length)
}
module.exports.requestAccessToken = function (code, cb) {
var tokenRequest = {
url: "https://github.com/login/oauth/access_token",
json: {
client_id: config.github.oauth.id,
client_secret: config.github.oauth.secret,
code: code
}
}
request.post(tokenRequest, function (err, tokenRes, data) {
if (err || tokenRes.statusCode !== 200) {
return cb(err || "Unable to exchange code for token")
}
data = data || {}
if (!data.access_token) {
return cb("Failed to receive access token from GitHub")
}
var authData = { access_token: data.access_token }
, gh = github.getInstance(data.access_token)
gh.user.get({}, function (err, data) {
if (err) {
return cb(err)
} else if (!data.login) {
return cb("Unable to find user from token")
}
authData.user = data.login
cb(null, authData)
})
})
}
|
Make the link to the ES6 katas at the bottom of the page work (with a hack).
|
import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
<div className="headline">ES6 Katas</div>
<div className="scrollable">
{katas.map(kata => <KataLink kata={kata} selected={selectedKataId === kata.id} />)}
</div>
</div>
);
}
}
class KataLink extends React.Component {
render() {
const {kata, selected} = this.props;
const {id, path, groupName, name} = kata;
const url = `${window.location.pathname}?${('' + ( + new Date() )).substr(-5)}#?kata=es6/language/${path}`;
const className = selected ? 'selected' : '';
return (
<a href={url} title={`${groupName}: ${name}`} className={className}>{id}</a>
);
}
}
|
import React from 'react';
export default class KatasNavigation extends React.Component {
render() {
if (!this.props.katas) {
return null;
}
const selectedKataId = null;
const katas = this.props.katas.items;
return (
<div id="katas-navigation" className="flex-columns-full-width">
<div className="headline">ES6 Katas</div>
<div className="scrollable">
{katas.map(kata => <KataLink kata={kata} selected={selectedKataId === kata.id} />)}
</div>
</div>
);
}
}
class KataLink extends React.Component {
render() {
const {kata, selected} = this.props;
const {id, path, groupName, name} = kata;
const url = '/#?kata=es6/language/' + path;
const className = selected ? 'selected' : '';
return (
<a href={url} title={`${groupName}: ${name}`} className={className}>{id}</a>
);
}
}
|
feat: Change the default value for format
|
const path = require('path')
const pkgConf = require('pkg-conf')
const { validate } = require('jest-validate')
function replaceRootDir (conf, rootDir) {
const replace = s => s.replace('<rootDir>', rootDir)
;['srcPathDirs', 'srcPathIgnorePatterns', 'localeDir']
.forEach(key => {
const value = conf[key]
if (!value) {
} else if (typeof value === 'string') {
conf[key] = replace(value)
} else if (value.length) {
conf[key] = value.map(replace)
}
})
conf.rootDir = rootDir
return conf
}
const defaults = {
localeDir: './locale',
fallbackLanguage: '',
srcPathDirs: ['<rootDir>'],
srcPathIgnorePatterns: ['/node_modules/'],
format: 'lingui',
rootDir: '.'
}
const configValidation = {
exampleConfig: defaults,
comment: `See https://l.lingui.io/ref-lingui-conf for a list of valid options`
}
function getConfig () {
const raw = pkgConf.sync('lingui', {
defaults,
skipOnFalse: true
})
validate(raw, configValidation)
const rootDir = path.dirname(pkgConf.filepath(raw))
return replaceRootDir(raw, rootDir)
}
export default getConfig
export { replaceRootDir }
|
const path = require('path')
const pkgConf = require('pkg-conf')
const { validate } = require('jest-validate')
function replaceRootDir (conf, rootDir) {
const replace = s => s.replace('<rootDir>', rootDir)
;['srcPathDirs', 'srcPathIgnorePatterns', 'localeDir']
.forEach(key => {
const value = conf[key]
if (!value) {
} else if (typeof value === 'string') {
conf[key] = replace(value)
} else if (value.length) {
conf[key] = value.map(replace)
}
})
conf.rootDir = rootDir
return conf
}
const defaults = {
localeDir: './locale',
fallbackLanguage: '',
srcPathDirs: ['<rootDir>'],
srcPathIgnorePatterns: ['/node_modules/'],
format: 'json-lingui',
rootDir: '.'
}
const configValidation = {
exampleConfig: defaults,
comment: `See https://l.lingui.io/ref-lingui-conf for a list of valid options`
}
function getConfig () {
const raw = pkgConf.sync('lingui', {
defaults,
skipOnFalse: true
})
validate(raw, configValidation)
const rootDir = path.dirname(pkgConf.filepath(raw))
return replaceRootDir(raw, rootDir)
}
export default getConfig
export { replaceRootDir }
|
Change class name in tests
|
# Licensed under an MIT open source license - see LICENSE
'''
Test function for Wavelet
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Wavelet, Wavelet_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class testWavelet(TestCase):
def setUp(self):
self.dataset1 = dataset1
self.dataset2 = dataset2
def test_Wavelet_method(self):
self.tester = Wavelet(dataset1["integrated_intensity"][0],
dataset1["integrated_intensity"][1])
self.tester.run()
assert np.allclose(self.tester.curve, computed_data['wavelet_val'])
def test_Wavelet_distance(self):
self.tester_dist = \
Wavelet_Distance(dataset1["integrated_intensity"],
dataset2["integrated_intensity"]).distance_metric()
npt.assert_almost_equal(self.tester_dist.distance,
computed_distances['wavelet_distance'])
|
# Licensed under an MIT open source license - see LICENSE
'''
Test function for Wavelet
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import wt2D, Wavelet_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class testWavelet(TestCase):
def setUp(self):
self.dataset1 = dataset1
self.dataset2 = dataset2
def test_Wavelet_method(self):
self.tester = wt2D(dataset1["integrated_intensity"][0],
dataset1["integrated_intensity"][1])
self.tester.run()
assert np.allclose(self.tester.curve, computed_data['wavelet_val'])
def test_Wavelet_distance(self):
self.tester_dist = \
Wavelet_Distance(dataset1["integrated_intensity"],
dataset2["integrated_intensity"]).distance_metric()
npt.assert_almost_equal(self.tester_dist.distance,
computed_distances['wavelet_distance'])
|
Fix type of EventIndex fields
|
from haystack import indexes
from .models import Event, Place, PublicationStatus
from django.utils.html import strip_tags
class EventIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
start_time = indexes.DateTimeField(model_attr='start_time')
end_time = indexes.DateTimeField(model_attr='end_time')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Event
def prepare(self, obj):
#obj.lang_keywords = obj.keywords.filter(language=get_language())
if obj.description:
obj.description = strip_tags(obj.description)
return super(EventIndex, self).prepare(obj)
def index_queryset(self, using=None):
return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC)
class PlaceIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Place
|
from haystack import indexes
from .models import Event, Place, PublicationStatus
from django.utils.html import strip_tags
class EventIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
start_time = indexes.DateField(model_attr='start_time')
end_time = indexes.DateField(model_attr='end_time')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Event
def prepare(self, obj):
#obj.lang_keywords = obj.keywords.filter(language=get_language())
if obj.description:
obj.description = strip_tags(obj.description)
return super(EventIndex, self).prepare(obj)
def index_queryset(self, using=None):
return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC)
class PlaceIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
autosuggest = indexes.EdgeNgramField(model_attr='name')
def get_updated_field(self):
return 'last_modified_time'
def get_model(self):
return Place
|
Add error ident for easier catching
|
#!/usr/bin/env node
const crypto = require("crypto");
const _sss = require("./build/Release/shamirsecretsharing");
exports.createShares = function createShares(data, n, k) {
return new Promise((resolve) => {
// Use node.js native random source for a key
crypto.randomBytes(32, (err, random) => {
if (err) throw err;
_sss.createShares(data, n, k, random, resolve);
});
});
};
exports.combineShares = function combineShares(shares) {
return new Promise((resolve) => {
_sss.combineShares(shares, resolve);
}).then((x) => {
if (x === null) {
throw "InvalidAccessError: nvalid or too few shares provided";
} else {
return x;
}
});
};
|
#!/usr/bin/env node
const crypto = require("crypto");
const _sss = require("./build/Release/shamirsecretsharing");
exports.createShares = function createShares(data, n, k) {
return new Promise((resolve) => {
// Use node.js native random source for a key
crypto.randomBytes(32, (err, random) => {
if (err) throw err;
_sss.createShares(data, n, k, random, resolve);
});
});
};
exports.combineShares = function combineShares(shares) {
return new Promise((resolve) => {
_sss.combineShares(shares, resolve);
}).then((x) => {
if (x === null) {
throw "invalid or too few shares provided";
} else {
return x;
}
});
};
|
Add another file type to the AcceptTypes
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
public static $AcceptTypes = array(
'text/plain',
'text/x-asm', // some css
'text/x-php',
'text/x-Algol68'
);
public static $InvalidFileNames = array(
'nbproject/', // netbeans project files
'__macosx/', // mac .zip remnants
'._' // mac temp file
);
public static function IsValidNameName($name) {
$lcName = strtolower($name);
$valid = true;
foreach (File::$InvalidFileNames as $invalidName) {
if (strpos($lcName, $invalidName) !== false) {
$valid = false;
}
}
return $valid;
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function reviews()
{
return $this->belongsTo('App\Review', 'review_id');
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
public static $AcceptTypes = array(
'text/plain',
'text/x-asm', // some css
'text/x-php',
);
public static $InvalidFileNames = array(
'nbproject/', // netbeans project files
'__macosx/', // mac .zip remnants
'._' // mac temp file
);
public static function IsValidNameName($name) {
$lcName = strtolower($name);
$valid = true;
foreach (File::$InvalidFileNames as $invalidName) {
if (strpos($lcName, $invalidName) !== false) {
$valid = false;
}
}
return $valid;
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function reviews()
{
return $this->belongsTo('App\Review', 'review_id');
}
}
|
Use the same logic to format message and asctime than the standard library.
This way we producte better message text on some circumstances when not logging
a string and use the date formater from the base class that uses the date format
configured from a file or a dict.
|
import logging
import json
import re
class JsonFormatter(logging.Formatter):
"""A custom formatter to format logging records as json objects"""
def parse(self):
standard_formatters = re.compile(r'\((.*?)\)', re.IGNORECASE)
return standard_formatters.findall(self._fmt)
def format(self, record):
"""Formats a log record and serializes to json"""
formatters = self.parse()
record.message = record.getMessage()
# only format time if needed
if "asctime" in formatters:
record.asctime = self.formatTime(record, self.datefmt)
log_record = {}
for formatter in formatters:
log_record[formatter] = record.__dict__[formatter]
return json.dumps(log_record)
|
import logging
import json
import re
from datetime import datetime
class JsonFormatter(logging.Formatter):
"""A custom formatter to format logging records as json objects"""
def parse(self):
standard_formatters = re.compile(r'\((.*?)\)', re.IGNORECASE)
return standard_formatters.findall(self._fmt)
def format(self, record):
"""Formats a log record and serializes to json"""
mappings = {
'asctime': create_timestamp,
'message': lambda r: r.msg,
}
formatters = self.parse()
log_record = {}
for formatter in formatters:
try:
log_record[formatter] = mappings[formatter](record)
except KeyError:
log_record[formatter] = record.__dict__[formatter]
return json.dumps(log_record)
def create_timestamp(record):
"""Creates a human readable timestamp for a log records created date"""
timestamp = datetime.fromtimestamp(record.created)
return timestamp.strftime("%y-%m-%d %H:%M:%S,%f"),
|
Fix typo in require statement of is-binary-string
|
'use strict';
// MODULES //
var isString = require( '@stdlib/utils/is-string' )[ 'primitive' ];
// BINARY STRING //
/**
* FUNCTION: isBinaryString( value )
* Tests if a value is a binary string.
*
* @param {*} value - value to test
* @returns {Boolean} boolean indicating if an input value is a binary string
*/
function isBinaryString( str ) {
var len;
var ch;
var i;
if ( !isString( str ) ) {
return false;
}
len = str.length;
if ( !len ) {
return false;
}
for ( i = 0; i < len; i++ ) {
ch = str[ i ];
if ( ch !== '1' && ch !== '0' ) {
return false;
}
}
return true;
} // end FUNCTION isBinaryString()
// EXPORTS //
module.exports = isBinaryString;
|
'use strict';
// MODULES //
var isString = require( '@stlib/utils/is-string' )[ 'primitive' ];
// BINARY STRING //
/**
* FUNCTION: isBinaryString( value )
* Tests if a value is a binary string.
*
* @param {*} value - value to test
* @returns {Boolean} boolean indicating if an input value is a binary string
*/
function isBinaryString( str ) {
var len;
var ch;
var i;
if ( !isString( str ) ) {
return false;
}
len = str.length;
if ( !len ) {
return false;
}
for ( i = 0; i < len; i++ ) {
ch = str[ i ];
if ( ch !== '1' && ch !== '0' ) {
return false;
}
}
return true;
} // end FUNCTION isBinaryString()
// EXPORTS //
module.exports = isBinaryString;
|
Use Python 3 style for super
|
from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super().retrieve(request, pk)
|
from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super(UserViewSet, self).retrieve(request, pk)
|
Handle situation when kwargs is None
|
from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
if reverse_kwargs!=None:
locale = utils.supported_language(reverse_kwargs.pop('locale',
translation.get_language()))
else:
locale = translation.get_language()
url = django_reverse(*args, **kwargs)
_, path = utils.strip_script_prefix(url)
return utils.locale_url(path, locale)
django_reverse = None
def patch_reverse():
"""
Monkey-patches the urlresolvers.reverse function. Will not patch twice.
"""
global django_reverse
if urlresolvers.reverse is not reverse:
django_reverse = urlresolvers.reverse
urlresolvers.reverse = reverse
if settings.USE_I18N:
patch_reverse()
|
from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
locale = utils.supported_language(reverse_kwargs.pop('locale',
translation.get_language()))
url = django_reverse(*args, **kwargs)
_, path = utils.strip_script_prefix(url)
return utils.locale_url(path, locale)
django_reverse = None
def patch_reverse():
"""
Monkey-patches the urlresolvers.reverse function. Will not patch twice.
"""
global django_reverse
if urlresolvers.reverse is not reverse:
django_reverse = urlresolvers.reverse
urlresolvers.reverse = reverse
if settings.USE_I18N:
patch_reverse()
|
Revert a debugging change that slipped in.
|
from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
print unicode(statement)
def execute_sql(cursor, sql):
"""
Execute a list of SQL statements on the provided cursor, unrolling
parameters as required
"""
for statement in sql:
if isinstance(statement, tuple):
if not statement[0].startswith('--'):
cursor.execute(*statement)
else:
if not statement.startswith('--'):
cursor.execute(statement)
|
from django_evolution.db import evolver
def write_sql(sql):
"Output a list of SQL statements, unrolling parameters as required"
for statement in sql:
if isinstance(statement, tuple):
print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1]))
else:
print unicode(statement)
def execute_sql(cursor, sql):
"""
Execute a list of SQL statements on the provided cursor, unrolling
parameters as required
"""
for statement in sql:
if isinstance(statement, tuple):
if not statement[0].startswith('--'):
cursor.execute(*statement)
else:
if not statement.startswith('--'):
try:
cursor.execute(statement)
except:
print statement
print sql
raise Exception(statement)
|
UglifyJs: Change the ecma option from 8 to 5
|
'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
optipng: { optimizationLevel: 7 },
gifsicle: { optimizationLevel: 3 },
pngquant: { quality: '65-90', speed: 4 },
svgo: {
plugins: [
{ removeUnknownsAndDefaults: false },
{ cleanupIDs: false },
{ removeViewBox: false },
],
},
plugins: [imageminMozjpeg({ quality: 75 })],
disable: (config.enabled.watcher),
}),
new UglifyJsPlugin({
uglifyOptions: {
ecma: 5,
compress: {
warnings: true,
drop_console: true,
},
},
}),
],
};
|
'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
optipng: { optimizationLevel: 7 },
gifsicle: { optimizationLevel: 3 },
pngquant: { quality: '65-90', speed: 4 },
svgo: {
plugins: [
{ removeUnknownsAndDefaults: false },
{ cleanupIDs: false },
{ removeViewBox: false },
],
},
plugins: [imageminMozjpeg({ quality: 75 })],
disable: (config.enabled.watcher),
}),
new UglifyJsPlugin({
uglifyOptions: {
ecma: 8,
compress: {
warnings: true,
drop_console: true,
},
},
}),
],
};
|
Add all modules to package
|
package com.reactlibrary;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNTensorflowPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNTensorflowModule(reactContext),
new RNTensorflowGraphModule(reactContext), new RNTensorflowGraphOperationsModule(reactContext));
}
// Deprecated from RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
package com.reactlibrary;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNTensorflowPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNTensorflowModule(reactContext));
}
// Deprecated from RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
Fix JavaScript bug with arguments.
|
/**
* @param {Object}
* @param {Array.<String>}
*/
module.exports = function(_class, _instance, mixined) {
_instance.mixined = {};
(mixined||[]).forEach(function(name) {
_instance.mixined[name] = [];
});
_instance.mixins = function(mixins)
{
var args = [].slice.call(arguments);
if (typeof args[0] === 'string') {
mixins = [{}];
mixins[0][args[0]] = args[1];
} else {
mixins = args;
}
mixins.forEach(function(mixin) {
Object.keys(mixin).forEach(function(name) {
if (name in _instance.mixined) {
_instance.mixined[name].push(mixin[name]);
} else if (_class.prototype[name] !== undefined) {
throw new Error("Mixin '" + name + "' could not override function.");
} else if (_instance[name] && typeof _instance[name] !== 'function') {
throw new Error("Mixin '" + name + "' could not override internal property.");
} else {
_instance[name] = mixin[name];
}
}, _instance);
}, _instance);
return _instance;
};
};
|
/**
* @param {Object}
* @param {Array.<String>}
*/
module.exports = function(_class, _instance, mixined) {
_instance.mixined = {};
(mixined||[]).forEach(function(name) {
_instance.mixined[name] = [];
});
_instance.mixins = function(mixins)
{
if (typeof arguments[0] === 'string') {
mixins = [{}];
mixins[0][arguments[0]] = arguments[1];
} else {
mixins = Array.prototype.slice.call(arguments);
}
mixins.forEach(function(mixin) {
Object.keys(mixin).forEach(function(name) {
if (name in _instance.mixined) {
_instance.mixined[name].push(mixin[name]);
} else if (_class.prototype[name] !== undefined) {
throw new Error("Mixin '" + name + "' could not override function.");
} else if (_instance[name] && typeof _instance[name] !== 'function') {
throw new Error("Mixin '" + name + "' could not override internal property.");
} else {
_instance[name] = mixin[name];
}
}, _instance);
}, _instance);
return _instance;
};
};
|
Use html string instead of temp html file
|
const fs = require('fs')
const path = require('path')
const showdown = require('showdown')
exports.reloadMarkdownFile = function (mainWindow, markdownFileName) {
fs.readFile(markdownFileName, 'utf8', function (err, markdown) {
if (err) throw err
var converter = new showdown.Converter()
var html = converter.makeHtml(markdown)
html = '<div class="markdown-body">' + html + '</div>'
html = 'data:text/html;charset=UTF-8,' + html
mainWindow.loadURL(html)
var cssPath = 'node_modules/github-markdown-css/github-markdown.css'
fs.readFile(path.join(__dirname, cssPath), 'utf8', function (err, css) {
if (err) throw err
mainWindow.webContents.on('did-finish-load', function() {
mainWindow.webContents.insertCSS(css)
})
})
})
}
|
const fs = require('fs')
const path = require('path')
const showdown = require('showdown')
const temp = require('temp')
const url = require('url')
exports.reloadMarkdownFile = function (mainWindow, markdownFileName) {
fs.readFile(markdownFileName, 'utf8', function (err, markdown) {
if (err) throw err
var converter = new showdown.Converter()
var html = converter.makeHtml(markdown)
html = '<div class="markdown-body">' + html + '</div>'
const tempHtmlPath = temp.path({suffix: '.html'})
fs.writeFile(tempHtmlPath, html, function (err) {
if (err) throw err
mainWindow.loadURL(url.format({
pathname: tempHtmlPath,
protocol: 'file:',
slashes: true
}))
var cssPath = 'node_modules/github-markdown-css/github-markdown.css'
fs.readFile(path.join(__dirname, cssPath), 'utf8', function (err, css) {
if (err) throw err
mainWindow.webContents.on('did-finish-load', function() {
mainWindow.webContents.insertCSS(css)
})
})
})
})
}
|
Add version constraint for underscore-deep
|
Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.use([
'meteor',
'underscore',
'coffeescript',
'practicalmeteor:loglevel@1.2.0_2',
'practicalmeteor:chai@2.1.0_1',
'practicalmeteor:underscore-deep@0.9.2'
]);
api.addFiles('namespace.coffee');
api.addFiles('EasyMeteorSettings.coffee');
});
Package.onTest(function(api) {
api.use([
'underscore',
'coffeescript',
'practicalmeteor:mocha@2.1.0_3'
]);
api.use('hubaaa:easy-meteor-settings@0.1.0');
api.addFiles('EasyMeteorSettingsTest.coffee');
});
|
Package.describe({
name: 'hubaaa:easy-meteor-settings',
version: '0.1.0',
// Brief, one-line summary of the package.
summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.2');
api.use([
'meteor',
'underscore',
'coffeescript',
'practicalmeteor:loglevel@1.2.0_2',
'practicalmeteor:chai@2.1.0_1',
'practicalmeteor:underscore-deep'
]);
api.addFiles('namespace.coffee');
api.addFiles('EasyMeteorSettings.coffee');
});
Package.onTest(function(api) {
api.use([
'underscore',
'coffeescript',
'practicalmeteor:mocha@2.1.0_3'
]);
api.use('hubaaa:easy-meteor-settings@0.1.0');
api.addFiles('EasyMeteorSettingsTest.coffee');
});
|
Append new individual batch operation data to the end of the batch data array.
array_merge() is *slow* as the number of operations gets larger.
|
<?php
namespace Everyman\Neo4j\Command\Batch;
use Everyman\Neo4j\Client,
Everyman\Neo4j\Batch;
/**
* Commit a batch operation
* @todo: Handle the case of empty body or body\data needing to be objects not arrays
*/
class Commit extends Command
{
protected $batch = null;
/**
* Set the batch to drive the command
*
* @param Client $client
* @param Batch $batch
*/
public function __construct(Client $client, Batch $batch)
{
parent::__construct($client);
$this->batch = $batch;
}
/**
* Return the data to pass
*
* @return mixed
*/
protected function getData()
{
$operations = $this->batch->getOperations();
$data = array();
foreach ($operations as $op) {
if ($op->reserve()) {
$opData = $op->getCommand()->getData();
foreach ($opData as $datum) {
$data[] = $datum;
}
}
}
return $data;
}
/**
* Use the results
*
* @param array $result
*/
protected function handleSingleResult($result)
{
$operations = $this->batch->getOperations();
$command = $operations[$result['id']]->getCommand();
return $command->handleSingleResult($result);
}
}
|
<?php
namespace Everyman\Neo4j\Command\Batch;
use Everyman\Neo4j\Client,
Everyman\Neo4j\Batch;
/**
* Commit a batch operation
* @todo: Handle the case of empty body or body\data needing to be objects not arrays
*/
class Commit extends Command
{
protected $batch = null;
/**
* Set the batch to drive the command
*
* @param Client $client
* @param Batch $batch
*/
public function __construct(Client $client, Batch $batch)
{
parent::__construct($client);
$this->batch = $batch;
}
/**
* Return the data to pass
*
* @return mixed
*/
protected function getData()
{
$operations = $this->batch->getOperations();
$data = array();
foreach ($operations as $op) {
if ($op->reserve()) {
$command = $op->getCommand();
$data = array_merge($data, $command->getData());
}
}
return $data;
}
/**
* Use the results
*
* @param array $result
*/
protected function handleSingleResult($result)
{
$operations = $this->batch->getOperations();
$command = $operations[$result['id']]->getCommand();
return $command->handleSingleResult($result);
}
}
|
Improve time generation for logging
|
const moment = require("moment");
let ctx;
try {
const chalk = require("chalk");
ctx = new chalk.constructor({enabled:true});
} catch (err) {
// silent
}
function getTime() {
return (" " + moment().format("LTS")).slice(-11);
}
module.exports = {
log(...args) {
if (ctx) console.log(getTime(), "|", ctx.grey("[LOG]"), ...args);
else console.log(getTime(), "|", ...args);
},
warn(...args) {
if (ctx) console.error(getTime(), "|", ctx.yellow("[WARN]"), ...args);
else console.error(getTime(), "|", ...args);
},
error(...args) {
if (ctx) console.error(getTime(), "|", ctx.red("[ERROR]"), ...args);
else console.error(getTime(), "|", ...args);
}
};
|
const moment = require("moment");
let ctx;
try {
const chalk = require("chalk");
ctx = new chalk.constructor({enabled:true});
} catch (err) {
// silent
}
function getTime() {
const curHour = new Date().getHours() % 12 || 12;
return (curHour < 10 ? " " : "") + moment().format("LTS");
}
module.exports = {
log(...args) {
if (ctx) console.log(getTime(), "|", ctx.grey("[LOG]"), ...args);
else console.log(getTime(), "|", ...args);
},
warn(...args) {
if (ctx) console.error(getTime(), "|", ctx.yellow("[WARN]"), ...args);
else console.error(getTime(), "|", ...args);
},
error(...args) {
if (ctx) console.error(getTime(), "|", ctx.red("[ERROR]"), ...args);
else console.error(getTime(), "|", ...args);
}
};
|
Add job label description equal to service label description
|
const Labels = {
type: 'object',
title: 'Labels',
description: 'Attach metadata to jobs to expose additional information to other jobs.',
properties: {
items: {
type: 'array',
duplicable: true,
addLabel: 'Add Label',
getter(job) {
let labels = job.getLabels() || {};
return Object.keys(labels).map(function (key) {
return {
key,
value: labels[key]
};
});
},
itemShape: {
properties: {
key: {
title: 'Label Name',
type: 'string'
},
value: {
title: 'Label Value',
type: 'string'
}
}
}
}
}
};
module.exports = Labels;
|
const Labels = {
type: 'object',
title: 'Labels',
properties: {
items: {
type: 'array',
duplicable: true,
addLabel: 'Add Label',
getter(job) {
let labels = job.getLabels() || {};
return Object.keys(labels).map(function (key) {
return {
key,
value: labels[key]
};
});
},
itemShape: {
properties: {
key: {
title: 'Label Name',
type: 'string'
},
value: {
title: 'Label Value',
type: 'string'
}
}
}
}
}
};
module.exports = Labels;
|
Make the Sifter issue matching more specific.
Now it matches:
* 3-5 digit numbers
* Preceded by a #, whitespace, or beginning-of-line.
* Followed by a comma, period, question mark, exclamation point,
whitespace, or end-of-line.
|
from base import BaseMatcher
import os
import requests
import re
import json
NUM_REGEX = r'(?:[\s#]|^)(\d\d\d\d?\d?)(?:[\s\.,\?!]|$)'
API_KEY = os.environ.get('SIFTER')
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
class SifterMatcher(BaseMatcher):
name = 'sifter'
def respond(self, message, user=None):
issues = parse(message)
if len(issues) == 0:
return
message = str(", ".join(issues))
self.speak(message)
|
from base import BaseMatcher
import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ.get('SIFTER')
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
class SifterMatcher(BaseMatcher):
name = 'sifter'
def respond(self, message, user=None):
issues = parse(message)
if len(issues) == 0:
return
message = str(", ".join(issues))
self.speak(message)
|
Use proper package name for pbr
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import pbr.version
version_info = pbr.version.VersionInfo('python-gilt') # noqa
__version__ = version_info.release_string()
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import pbr.version
version_info = pbr.version.VersionInfo('gilt') # noqa
__version__ = version_info.release_string()
|
Return 0 as an int rather than a string.
This was causing an ocassional crash in bumblebee/engine.py threshold_state
when checkupdates fails, perhaps due to wifi not being up yet.
For me this showed up regularly on login.
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return 0
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages)
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages)
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
Add a recipe for making the parent item from the created currency item
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.content.registry.item.currency;
import com.skelril.nitro.registry.item.CraftableItem;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class CondensedCofferItem extends CofferItem implements CraftableItem {
private CofferItem parent;
public CondensedCofferItem(String ID, CofferItem parent) {
super(ID, parent.getCofferValue() * 9);
this.parent = parent;
}
public CofferItem getParent() {
return parent;
}
@Override
public void registerRecipes() {
GameRegistry.addRecipe(
new ItemStack(this),
"AAA",
"AAA",
"AAA",
'A', new ItemStack(parent)
);
GameRegistry.addShapelessRecipe(
new ItemStack(parent, 9),
new ItemStack(this)
);
}
}
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.content.registry.item.currency;
import com.skelril.nitro.registry.item.CraftableItem;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class CondensedCofferItem extends CofferItem implements CraftableItem {
private CofferItem parent;
public CondensedCofferItem(String ID, CofferItem parent) {
super(ID, parent.getCofferValue() * 9);
this.parent = parent;
}
public CofferItem getParent() {
return parent;
}
@Override
public void registerRecipes() {
GameRegistry.addRecipe(
new ItemStack(this),
"AAA",
"AAA",
"AAA",
'A', new ItemStack(parent)
);
}
}
|
Add array return for the rest controller
|
<?php
namespace MainBundle\Controller;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use MainBundle\Entity\Logo;
use MainBundle\Entity\Section;
use MainBundle\Repository\LogoRepository;
use MainBundle\Repository\SectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use phpCAS;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use UserBundle\Entity\User;
use UserBundle\Repository\UserRepository;
class RestController extends BaseController
{
public function logoAction($code_section)
{
/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();
/** @var Section $section */
$section = $em->getRepository('MainBundle:Section')->findOneBy(array("code" => $code_section));
if (!$section){
throw $this->createNotFoundException('No section found with this code');
}
/** @var Logo $logo */
$logo = $section->getLogos()->first();
$baseurl = "http://logoinserter.esnlille.fr";
return new JsonResponse(array(
"url" => $baseurl . "/" . $logo->getWebPath()
)
);
}
}
|
<?php
namespace MainBundle\Controller;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use MainBundle\Entity\Logo;
use MainBundle\Entity\Section;
use MainBundle\Repository\LogoRepository;
use MainBundle\Repository\SectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use phpCAS;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use UserBundle\Entity\User;
use UserBundle\Repository\UserRepository;
class RestController extends BaseController
{
public function logoAction($code_section)
{
/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();
/** @var Section $section */
$section = $em->getRepository('MainBundle:Section')->findOneBy(array("code" => $code_section));
if (!$section){
throw $this->createNotFoundException('No section found with this code');
}
/** @var Logo $logo */
$logo = $section->getLogos()->first();
$baseurl = "http://logoinserter.esnlille.fr";
return new JsonResponse(
$baseurl . "/" . $logo->getWebPath()
);
}
}
|
Read env variables with dotenv
|
import argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
load_dotenv(find_dotenv())
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
|
import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
|
Return a fallback "version" if dosage is not installed
Additionally, inform the user on how to fix the problem. Thanks to twb
for noticing this.
|
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs
# Copyright (C) 2012-2014 Bastian Kleineidam
# Copyright (C) 2015-2019 Tobias Gruetzmacher
"""
Automated comic downloader. Dosage traverses comic websites in
order to download each strip of the comic. The intended use is for
mirroring the strips locally for ease of viewing; redistribution of the
downloaded strips may violate copyright, and is not advisable unless you
have communicated with all of the relevant copyright holders, described
your intentions, and received permission to distribute.
The primary interface is the 'dosage' commandline script.
Comic modules for each comic are located in L{dosagelib.plugins}.
"""
from __future__ import absolute_import, division, print_function
try:
from importlib.metadata import version, PackageNotFoundError
except ImportError:
from importlib_metadata import version, PackageNotFoundError
from .output import out
AppName = u'dosage'
try:
__version__ = version(AppName) # PEP 396
except PackageNotFoundError:
# package is not installed
out.warn('{} is not installed, no version available.'
' Use at least {!r} or {!r} to fix this.'.format(
AppName, 'pip install -e .', 'setup.py egg_info'))
__version__ = 'ERR.NOT.INSTALLED'
|
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs
# Copyright (C) 2012-2014 Bastian Kleineidam
# Copyright (C) 2015-2019 Tobias Gruetzmacher
"""
Automated comic downloader. Dosage traverses comic websites in
order to download each strip of the comic. The intended use is for
mirroring the strips locally for ease of viewing; redistribution of the
downloaded strips may violate copyright, and is not advisable unless you
have communicated with all of the relevant copyright holders, described
your intentions, and received permission to distribute.
The primary interface is the 'dosage' commandline script.
Comic modules for each comic are located in L{dosagelib.plugins}.
"""
from __future__ import absolute_import, division, print_function
try:
from importlib.metadata import version, PackageNotFoundError
except ImportError:
from importlib_metadata import version, PackageNotFoundError
from .output import out
AppName = u'dosage'
try:
__version__ = version(AppName) # PEP 396
except PackageNotFoundError:
# package is not installed
pass
|
Fix KeyError when accessing non-existing header
|
from flask import Request, Response
class RqRequest(Request):
def rq_headers(self):
headers = {}
if 'Authorization' in self.headers:
headers['Authorization'] = self.headers['Authorization']
if self.headers.get('Accept') == 'application/xml':
headers['Accept'] = 'application/xml'
else:
headers['Accept'] = 'application/json'
return self.headers
# request.form is a Werkzeug MultiDict
# we want to create a string
def rq_data(self):
data = ""
for k, v in self.form.iteritems():
data += k + "=" + v + "&"
return data
def rq_params(self):
return self.args.to_dict()
|
from flask import Request, Response
class RqRequest(Request):
def rq_headers(self):
headers = {}
if 'Authorization' in self.headers:
headers['Authorization'] = self.headers['Authorization']
if self.headers['Accept'] == 'application/xml':
headers['Accept'] = 'application/xml'
else:
headers['Accept'] = 'application/json'
return self.headers
# request.form is a Werkzeug MultiDict
# we want to create a string
def rq_data(self):
data = ""
for k, v in self.form.iteritems():
data += k + "=" + v + "&"
return data
def rq_params(self):
return self.args.to_dict()
|
Change redirect URI to github project page
|
var browser = require('openurl');
var config = require('./config');
var REDIRECT_URI = 'https://rogeriopvl.github.io/downstagram';
console.log('\n********** DOWNSTAGRAM OAUTH SETUP **********');
console.log('\n To use downstagram you need to authorize it to access your instagram account.');
console.log('Your browser will open for you to authorize the app...');
var authURI = [
'https://instagram.com/oauth/authorize/?',
'client_id=' + config.auth.client_id,
'&redirect_uri=' + REDIRECT_URI,
'&response_type=token'
].join('');
browser.open(authURI);
console.log('Now according to the intructions in the App page, insert your access token here:');
var stdin = process.openStdin();
stdin.on('data', function(chunk) {
var token = chunk.toString().trim();
config.auth.access_token = token;
// TODO: config.save(config);
process.exit(0);
});
|
var browser = require('openurl');
var config = require('./config');
var REDIRECT_URI = '';
console.log('\n********** DOWNSTAGRAM OAUTH SETUP **********');
console.log('\n To use downstagram you need to authorize it to access your instagram account.');
console.log('Your browser will open for you to authorize the app...');
var authURI = [
'https://instagram.com/oauth/authorize/?',
'client_id=' + config.auth.client_id,
'&redirect_uri=http://rogeriopvl.com',
'&response_type=token'
].join('');
browser.open(authURI);
console.log('Now according to the intructions in the App page, insert your access token here:');
var stdin = process.openStdin();
stdin.on('data', function(chunk) {
var token = chunk.toString().trim();
config.auth.access_token = token;
// TODO: config.save(config);
process.exit(0);
});
|
Add tests for parse CLI with pos_kind
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom'])
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix, sample, pos_kind):
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli, [
'parse', '-o', out_file.name, '-f',
sample(''), '-p', prefix, '--pos-kind', pos_kind
],
catch_exceptions=False
)
print(run.output)
model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(
folder=sample(''), prefix=prefix, pos_kind=pos_kind
)
models_equal(model_res, model_reference)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix, sample):
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli,
['parse', '-o', out_file.name, '-f',
sample(''), '-p', prefix],
catch_exceptions=False
)
print(run.output)
model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(
folder=sample(''), prefix=prefix
)
models_equal(model_res, model_reference)
|
Use jquery instead of ext in Directory-ViewMap component
|
var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var formRegistry = require('kwf/frontend-form/form-registry');
var gmapLoader = require('kwf/google-map/loader');
var gmapMap = require('kwf/google-map/map');
var renderedMaps = [];
var renderMap = function(map) {
if (renderedMaps.indexOf(map) != -1) return;
renderedMaps.push(map);
var cfg = map.find(".options");
if (!cfg) return;
cfg = $.parseJSON(cfg.val());
cfg.mapContainer = map;
var cls = eval(cfg.mapClass) || gmapMap;
var myMap = new cls(cfg);
map.map = myMap;
gmapLoader(function() {
this.show();
}, myMap);
if (cfg.searchFormComponentId) {
var searchForm = formRegistry.getFormByComponentId(cfg.searchFormComponentId);
searchForm.on('beforeSubmit', function(form, ev) {
myMap.setBaseParams($.extend(searchForm.getValues(), myMap.getBaseParams()));
myMap.centerMarkersIntoView();
return false;
}, this);
}
};
onReady.onRender('.kwcClass', function(map) {
renderMap(map);
}, { checkVisibility: true });
|
var onReady = require('kwf/on-ready-ext2');
var formRegistry = require('kwf/frontend-form/form-registry');
var gmapLoader = require('kwf/google-map/loader');
var gmapMap = require('kwf/google-map/map');
var renderedMaps = [];
var renderMap = function(map) {
if (renderedMaps.indexOf(map) != -1) return;
renderedMaps.push(map);
var mapContainer = new Ext2.Element(map);
var cfg = mapContainer.down(".options", true);
if (!cfg) return;
cfg = Ext2.decode(cfg.value);
cfg.mapContainer = map;
var cls = eval(cfg.mapClass) || gmapMap;
var myMap = new cls(cfg);
map.map = myMap;
gmapLoader(function() {
this.show();
}, myMap);
if (cfg.searchFormComponentId) {
var searchForm = formRegistry.getFormByComponentId(cfg.searchFormComponentId);
searchForm.on('beforeSubmit', function(form, ev) {
myMap.setBaseParams(
Ext2.applyIf(searchForm.getValues(), myMap.getBaseParams())
);
myMap.centerMarkersIntoView();
return false;
}, this);
}
};
onReady.onRender('.kwcClass', function(map) {
renderMap(map.dom);
}, { checkVisibility: true });
|
Fix case sensitive email login
|
/* eslint-disable func-names, prefer-arrow-callback */
import local from 'passport-local';
import * as objection from 'objection';
import bcrypt from 'bcrypt';
import { User } from './models';
export default (passport) => {
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async function (id, done) {
const user = await User
.query()
.findById(id);
if (!user) {
return done(null, false, { error: 'User not found.' });
}
return done(null, {
id: user.id,
email: user.email,
admin: user.admin,
canCreate: user.canCreate,
});
});
passport.use(new local.Strategy({
usernameField: 'email',
passwordField: 'password',
}, async function (email, password, done) {
const users = await User
.query()
.where('email', email.toLowerCase());
const user = users[0];
if (!user) {
return done(null, false, { error: 'User not found.' });
} else if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, { error: 'Incorrect password.' });
}
return done(null, {
id: user.id,
email: user.email,
admin: user.admin,
canCreate: user.canCreate,
});
}));
};
|
/* eslint-disable func-names, prefer-arrow-callback */
import local from 'passport-local';
import * as objection from 'objection';
import bcrypt from 'bcrypt';
import { User } from './models';
export default (passport) => {
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async function (id, done) {
const user = await User
.query()
.findById(id);
if (!user) {
return done(null, false, { error: 'User not found.' });
}
return done(null, {
id: user.id,
email: user.email,
admin: user.admin,
canCreate: user.canCreate,
});
});
passport.use(new local.Strategy({
usernameField: 'email',
passwordField: 'password',
}, async function (email, password, done) {
const users = await User
.query()
.where('email', email);
const user = users[0];
if (!user) {
return done(null, false, { error: 'User not found.' });
} else if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, { error: 'Incorrect password.' });
}
return done(null, {
id: user.id,
email: user.email,
admin: user.admin,
canCreate: user.canCreate,
});
}));
};
|
Mark compatibility table test as slow (temporary)
Prevent Travis from running test test until models repo is published
|
# coding: utf-8
from __future__ import unicode_literals
from ..download import download, get_compatibility, get_version, check_error_depr
import pytest
@pytest.mark.slow
def test_download_fetch_compatibility():
compatibility = get_compatibility()
assert type(compatibility) == dict
@pytest.mark.slow
@pytest.mark.parametrize('model', ['en_core_web_md-1.2.0'])
def test_download_direct_download(model):
download(model, direct=True)
@pytest.mark.parametrize('model', ['en_core_web_md'])
def test_download_get_matching_version_succeeds(model):
comp = { model: ['1.7.0', '0.100.0'] }
assert get_version(model, comp)
@pytest.mark.parametrize('model', ['en_core_web_md'])
def test_download_get_matching_version_fails(model):
diff_model = 'test_' + model
comp = { diff_model: ['1.7.0', '0.100.0'] }
with pytest.raises(SystemExit):
assert get_version(model, comp)
@pytest.mark.parametrize('model', [False, None, '', 'all'])
def test_download_no_model_depr_error(model):
with pytest.raises(SystemExit):
check_error_depr(model)
|
# coding: utf-8
from __future__ import unicode_literals
from ..download import download, get_compatibility, get_version, check_error_depr
import pytest
def test_download_fetch_compatibility():
compatibility = get_compatibility()
assert type(compatibility) == dict
@pytest.mark.slow
@pytest.mark.parametrize('model', ['en_core_web_md-1.2.0'])
def test_download_direct_download(model):
download(model, direct=True)
@pytest.mark.parametrize('model', ['en_core_web_md'])
def test_download_get_matching_version_succeeds(model):
comp = { model: ['1.7.0', '0.100.0'] }
assert get_version(model, comp)
@pytest.mark.parametrize('model', ['en_core_web_md'])
def test_download_get_matching_version_fails(model):
diff_model = 'test_' + model
comp = { diff_model: ['1.7.0', '0.100.0'] }
with pytest.raises(SystemExit):
assert get_version(model, comp)
@pytest.mark.parametrize('model', [False, None, '', 'all'])
def test_download_no_model_depr_error(model):
with pytest.raises(SystemExit):
check_error_depr(model)
|
Remove obsolete call to debugComponentTrees
|
package ch.difty.scipamato.publ.web.paper.browse;
import org.apache.wicket.model.Model;
import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter;
import ch.difty.scipamato.publ.web.common.PanelTest;
public class SimpleFilterPanelTest extends PanelTest<SimpleFilterPanel> {
private static final String PANEL = "panel";
@Override
protected SimpleFilterPanel makePanel() {
return new SimpleFilterPanel(PANEL, Model.of(new PublicPaperFilter()));
}
@Override
protected void assertSpecificComponents() {
getTester().assertComponent(PANEL, SimpleFilterPanel.class);
assertLabeledTextField(PANEL, "methodsSearch");
assertLabeledTextField(PANEL, "authorsSearch");
assertLabeledTextField(PANEL, "pubYearFrom");
assertLabeledTextField(PANEL, "pubYearUntil");
assertLabeledMultiSelect(PANEL, "populationCodes");
assertLabeledMultiSelect(PANEL, "studyDesignCodes");
}
}
|
package ch.difty.scipamato.publ.web.paper.browse;
import org.apache.wicket.model.Model;
import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter;
import ch.difty.scipamato.publ.web.common.PanelTest;
public class SimpleFilterPanelTest extends PanelTest<SimpleFilterPanel> {
private static final String PANEL = "panel";
@Override
protected SimpleFilterPanel makePanel() {
return new SimpleFilterPanel(PANEL, Model.of(new PublicPaperFilter()));
}
@Override
protected void assertSpecificComponents() {
getTester().debugComponentTrees();
getTester().assertComponent(PANEL, SimpleFilterPanel.class);
assertLabeledTextField(PANEL, "methodsSearch");
assertLabeledTextField(PANEL, "authorsSearch");
assertLabeledTextField(PANEL, "pubYearFrom");
assertLabeledTextField(PANEL, "pubYearUntil");
assertLabeledMultiSelect(PANEL, "populationCodes");
assertLabeledMultiSelect(PANEL, "studyDesignCodes");
}
}
|
Remove event start field from form
|
# -*- coding: utf-8 -*-
from django import forms
from apps.posters.models import Poster
class AddPosterForm(forms.ModelForm):
display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'}))
display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'}))
class Meta:
model = Poster
fields = ['event', 'amount', 'description',
'price', 'display_from', 'display_to', 'comments']
class EditPosterForm(forms.ModelForm):
class Meta:
model = Poster
fields = ['event', 'amount', 'description',
'price', 'display_to', 'display_from', 'comments', 'finished']
|
# -*- coding: utf-8 -*-
from django import forms
from apps.posters.models import Poster
class AddPosterForm(forms.ModelForm):
when = forms.CharField(label=u"Event start", widget=forms.TextInput(attrs={'type': 'datetime-local'}))
display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'}))
display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'}))
class Meta:
model = Poster
fields = ['event', 'amount', 'description',
'price', 'display_from', 'display_to', 'comments']
class EditPosterForm(forms.ModelForm):
class Meta:
model = Poster
fields = ['event', 'amount', 'description',
'price', 'display_to', 'display_from', 'comments', 'finished']
|
Use Sentry Laravel object as client.
|
<?php
namespace Timetorock\LaravelMonologSentry\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RavenHandler;
use Raven_Client;
use Log;
class MonologSentryServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->bootstrapRaven();
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// Nothing to register
}
/**
* Bootstraps Raven and Monolog together
*/
private function bootstrapRaven()
{
$sentryDsn = config('sentry.dsn', null);
if (!empty($sentryDsn)) {
$handler = new RavenHandler(app('sentry'));
$handler->setFormatter(new LineFormatter("%message% %context% %extra%\n"));
$monolog = Log::getMonolog();
$monolog->pushHandler($handler);
}
}
}
|
<?php
namespace Timetorock\LaravelMonologSentry\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RavenHandler;
use Raven_Client;
use Log;
class MonologSentryServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->bootstrapRaven();
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// Nothing to register
}
/**
* Bootstraps Raven and Monolog together
*/
private function bootstrapRaven()
{
$sentryDsn = config('sentry.dsn', null);
$sentryOptions = config('sentry.options', []);
if (!empty($sentryDsn)) {
$client = new Raven_Client($sentryDsn, $sentryOptions);
$handler = new RavenHandler($client);
$handler->setFormatter(new LineFormatter("%message% %context% %extra%\n"));
$monolog = Log::getMonolog();
$monolog->pushHandler($handler);
}
}
}
|
Add check to customer context
| Q | A
| ------------- | ---
| Bug fix? | no
| New feature? | no
| BC breaks? | no
| Deprecations? | no
| Fixed tickets |
| License | MIT
| Doc PR |
In one part of our site we don't need sylius autentication, just basic http with a generic username and password (which by default uses a Symfony user), so the Customer context fails when calling `->getCustomer()`.
Adding this check allows us to use basic http autentication.
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\UserBundle\Context;
use Sylius\Component\User\Context\CustomerContextInterface;
use Sylius\Component\User\Model\CustomerInterface;
use Sylius\Component\User\Model\UserInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
/**
* @author Michał Marcinkowski <michal.marcinkowski@lakion.com>
*/
class CustomerContext implements CustomerContextInterface
{
/**
* @var SecurityContextInterface
*/
private $securityContext;
/**
* @param SecurityContextInterface $securityContext
*/
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}
/**
* Gets customer based on currently logged user.
*
* @return CustomerInterface|null
*/
public function getCustomer()
{
if ($this->securityContext->getToken() && $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')
&& $this->securityContext->getToken()->getUser() instanceof UserInterface
) {
return $this->securityContext->getToken()->getUser()->getCustomer();
}
return null;
}
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\UserBundle\Context;
use Sylius\Component\User\Context\CustomerContextInterface;
use Sylius\Component\User\Model\CustomerInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
/**
* @author Michał Marcinkowski <michal.marcinkowski@lakion.com>
*/
class CustomerContext implements CustomerContextInterface
{
/**
* @var SecurityContextInterface
*/
private $securityContext;
/**
* @param SecurityContextInterface $securityContext
*/
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}
/**
* Gets customer based on currently logged user.
*
* @return CustomerInterface|null
*/
public function getCustomer()
{
if ($this->securityContext->getToken() && $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')
&& $this->securityContext->getToken()->getUser()
) {
return $this->securityContext->getToken()->getUser()->getCustomer();
}
return null;
}
}
|
Declare return type on exists()
|
<?php
namespace Amp\Parallel\Worker;
interface Environment extends \ArrayAccess
{
/**
* @param string $key
*
* @return bool
*/
public function exists(string $key): bool;
/**
* @param string $key
*
* @return mixed|null Returns null if the key does not exist.
*/
public function get(string $key);
/**
* @param string $key
* @param mixed $value Using null for the value deletes the key.
* @param int $ttl Number of seconds until data is automatically deleted. Use 0 for unlimited TTL.
*/
public function set(string $key, $value, int $ttl = null);
/**
* @param string $key
*/
public function delete(string $key);
/**
* Removes all values.
*/
public function clear();
}
|
<?php
namespace Amp\Parallel\Worker;
interface Environment extends \ArrayAccess
{
/**
* @param string $key
*
* @return bool
*/
public function exists(string $key);
/**
* @param string $key
*
* @return mixed|null Returns null if the key does not exist.
*/
public function get(string $key);
/**
* @param string $key
* @param mixed $value Using null for the value deletes the key.
* @param int $ttl Number of seconds until data is automatically deleted. Use 0 for unlimited TTL.
*/
public function set(string $key, $value, int $ttl = null);
/**
* @param string $key
*/
public function delete(string $key);
/**
* Removes all values.
*/
public function clear();
}
|
Fix piwik by using window._paq
Fix #636
|
if (document.head.dataset.piwikHost) {
window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
window._paq.push(['trackPageView']);
window._paq.push(['enableLinkTracking']);
(function() {
var u=document.head.dataset.piwikHost;
window._paq.push(['setTrackerUrl', u+'piwik.php']);
window._paq.push(['setSiteId', '6']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
document.addEventListener('click', function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (target.dataset.piwikAction) {
window._paq.push(['trackEvent', target.dataset.piwikAction, target.dataset.piwikName, target.dataset.piwikValue]);
}
}, false);
}
|
if (document.head.dataset.piwikHost) {
var _paq = _paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u=document.head.dataset.piwikHost;
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', '6']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
document.addEventListener('click', function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (target.dataset.piwikAction) {
_paq.push(['trackEvent', target.dataset.piwikAction, target.dataset.piwikName, target.dataset.piwikValue]);
}
}, false);
}
|
Allow layout and theme opt-out
|
import React from 'react'
import styles from './PreviewTools.styl'
export default ({ href, layout, theme, onLayoutChanged, onThemeChanged }) =>
<div className={styles.container}>
<div>
Layout:
<select value={layout} onChange={onLayoutChanged}>
<option value="none">None</option>
<option value="blog">Blog</option>
<option value="centered">Centered</option>
</select>
</div>
<div>
Theme:
<select value={theme} onChange={onThemeChanged}>
<option value="none">None</option>
<option value="idyll">Idyll</option>
<option value="github">GitHub</option>
</select>
</div>
<a href={href} target="_blank">
Open in New Window
</a>
</div>
|
import React from 'react'
import styles from './PreviewTools.styl'
export default ({ href, layout, theme, onLayoutChanged, onThemeChanged }) =>
<div className={styles.container}>
<div>
Layout:
<select value={layout} onChange={onLayoutChanged}>
<option value="blog">Blog</option>
<option value="centered">Centered</option>
</select>
</div>
<div>
Theme:
<select value={theme} onChange={onThemeChanged}>
<option value="idyll">Idyll</option>
<option value="github">GitHub</option>
</select>
</div>
<a href={href} target="_blank">
Open in New Window
</a>
</div>
|
Update cli help to say milliseconds
|
#!/usr/bin/env node
var program = require('commander')
var command
var env
program
.usage('[options]')
.option('-f, --file [file]', 'config file - defaults to testem.json or testem.yml')
.option('-p, --port [num]', 'server port - defaults to 7357', Number)
.option('-l, --launch [list]', 'list of launchers to launch(comma separated)')
.option('-s, --skip [list]', 'list of launchers to skip(comma separated)')
.option('-d, --debug', 'output debug to debug log - testem.log')
program
.command('launchers')
.description('Print the list of available launchers (browsers & process launchers)')
.action(function(e){
env = e
console.log(env)
})
program
.command('ci')
.description('Continuous integration mode')
.option('-t, --timeout [ms]', 'timeout a browser after [ms] milliseconds', null)
.action(function(e){
env = e
console.log(env.skip)
command = 'ci'
})
program.parse(process.argv)
console.log(program)
|
#!/usr/bin/env node
var program = require('commander')
var command
var env
program
.usage('[options]')
.option('-f, --file [file]', 'config file - defaults to testem.json or testem.yml')
.option('-p, --port [num]', 'server port - defaults to 7357', Number)
.option('-l, --launch [list]', 'list of launchers to launch(comma separated)')
.option('-s, --skip [list]', 'list of launchers to skip(comma separated)')
.option('-d, --debug', 'output debug to debug log - testem.log')
program
.command('launchers')
.description('Print the list of available launchers (browsers & process launchers)')
.action(function(e){
env = e
console.log(env)
})
program
.command('ci')
.description('Continuous integration mode')
.option('-t, --timeout [sec]', 'timeout a browser after [sec] seconds', null)
.action(function(e){
env = e
console.log(env.skip)
command = 'ci'
})
program.parse(process.argv)
console.log(program)
|
Fix parsing of item strings in first position
|
import CodeMirror from 'codemirror';
import 'codemirror/addon/mode/simple';
var VAR_REGEX = /(\?|\$)[A-Za-z_][A-Za-z0-9\-_]*/;
var STRING_REGEX = /\"(\\.|[^\"])*\"/;
var PROPERTY_ID_REGEX = /:P[0-9]*/;
var ITEM_ID_REGEX = /:Q[0-9]*/;
CodeMirror.defineSimpleMode('qwery', {
start: [
{regex: STRING_REGEX, token: 'item', next: 'startEntityID', sol: true},
{regex: VAR_REGEX, token: 'variable', next: 'property', sol: true}
],
startEntityID: [
{regex: ITEM_ID_REGEX, token: 'item-id', next: 'property'}
],
property: [
{regex: STRING_REGEX, token: 'property', next: 'propertyID'},
],
propertyID: [
{regex: PROPERTY_ID_REGEX, token: 'property-id', next: 'entity'}
],
entity: [
{regex: STRING_REGEX, token: 'item', next: 'entityID'},
{regex: VAR_REGEX, token: 'variable', next: 'start'}
],
entityID: [
{regex: ITEM_ID_REGEX, token: 'item-id', next: 'start'}
],
});
|
import CodeMirror from 'codemirror';
import 'codemirror/addon/mode/simple';
var VAR_REGEX = /(\?|\$)[A-Za-z_][A-Za-z0-9\-_]*/;
var STRING_REGEX = /\"(\\.|[^\"])*\"/;
var PROPERTY_ID_REGEX = /:P[0-9]*/;
var ITEM_ID_REGEX = /:Q[0-9]*/;
CodeMirror.defineSimpleMode('qwery', {
start: [
{regex: STRING_REGEX, token: 'item', next: 'property', sol: true},
{regex: VAR_REGEX, token: 'variable', next: 'property', sol: true}
],
property: [
{regex: STRING_REGEX, token: 'property', next: 'propertyID'},
],
propertyID: [
{regex: PROPERTY_ID_REGEX, token: 'property-id', next: 'entity'}
],
entity: [
{regex: STRING_REGEX, token: 'item', next: 'entityID'},
{regex: VAR_REGEX, token: 'variable', next: 'start'}
],
entityID: [
{regex: ITEM_ID_REGEX, token: 'item-id', next: 'start'}
],
});
|
Refactor and add new Events unit tests
|
var path = require('path');
module.exports = function() {
var Events = require(path.resolve(process.cwd(), 'lib/base/events'));
describe('Events', function() {
var events;
beforeEach(function() {
events = new Events();
});
describe('#off()', function() {
it('should deregister multiple space-separated events', function() {
function eventHandler() {
throw new Error('Expected event handler to have not been called');
}
events.on('A', eventHandler);
events.on('B', eventHandler);
events.off('A B');
events.trigger('A');
expect(events._eventsCount).to.equal(0);
});
});
describe('#trigger()', function() {
it('should pass additional arguments to the listener', function() {
events.on('event', function(name, arg1, arg2) {
expect(name).to.equal('event');
expect(arg1).to.equal(1);
expect(arg2).to.equal(2);
})
events.trigger('event', 1, 2);
});
});
});
};
|
var assert = require('assert');
var equal = assert.equal;
var path = require('path');
var basePath = process.cwd();
module.exports = function() {
var Events = require(path.resolve(basePath + '/lib/base/events'));
describe('Events', function() {
var events;
var handlersRun;
beforeEach(function() {
events = new Events();
handlersRun = [];
events.on('A', eventHandler('A'));
events.on('B', eventHandler('B'));
});
function eventHandler(event) {
return function() {
handlersRun.push(event);
}
}
describe('#off()', function() {
it('should deregister multiple, space-separated events', function() {
events.off('A B');
events.trigger('A');
events.trigger('B');
equal(handlersRun.length, 0);
});
});
});
};
|
Adjust server test message welcome page
|
// request-promise is just like the HTTP client 'Request', except Promises-compliant.
// See https://www.npmjs.com/package/request-promise.
var requestPromise = require('request-promise');
var request = require('request');
var expect = require('chai').expect;
require('./setup.js');
var db = require('./../../server/config/db');
var appUrl = process.env.PROTOCOL + process.env.HOST + ':' + process.env.PORT;
describe('Express Server', function() {
describe('Privileged Access', function(){
beforeEach(function() {
// Logout the user before each authentication test
request(appUrl + '/logout', function(err, res, body) {});
});
it('redirects to welcome page when an unauthenticated user tries to access the main page', function(done) {
request(appUrl + '/', function(error, res, body) {
// res comes from the request module, and may not follow express conventions
expect(res.statusCode).to.equal(200);
expect(res.req.path).to.equal('/welcome');
done();
});
});
});
});
|
// request-promise is just like the HTTP client 'Request', except Promises-compliant.
// See https://www.npmjs.com/package/request-promise.
var requestPromise = require('request-promise');
var request = require('request');
var expect = require('chai').expect;
require('./setup.js');
var db = require('./../../server/config/db');
var appUrl = process.env.PROTOCOL + process.env.HOST + ':' + process.env.PORT;
describe('Express Server', function() {
describe('Privileged Access', function(){
beforeEach(function() {
// Logout the user before each authentication test
request(appUrl + '/logout', function(err, res, body) {});
});
it('redirects to login page when an unauthenticated user tries to access the main page', function(done) {
request(appUrl + '/', function(error, res, body) {
// res comes from the request module, and may not follow express conventions
expect(res.statusCode).to.equal(200);
expect(res.req.path).to.equal('/welcome');
done();
});
});
});
});
|
Fix unit test for JDK 1.3.
|
package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
static class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
|
package com.thoughtworks.xstream.core;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;
public class TreeMarshallerTest extends AbstractAcceptanceTest {
class Thing {
Thing thing;
}
protected void setUp() throws Exception {
super.setUp();
xstream.setMode(XStream.NO_REFERENCES);
}
public void testThrowsExceptionWhenDetectingCircularReferences() {
Thing a = new Thing();
Thing b = new Thing();
a.thing = b;
b.thing = a;
try {
xstream.toXML(a);
fail("expected exception");
} catch (TreeMarshaller.CircularReferenceException expected) {
// good
}
}
}
|
Fix typo in error message
[#115369351]
|
import React, { Component } from 'react'
import pureRender from 'pure-render-decorator'
import '../../css/data-fetch-error.less'
@pureRender
export default class DataFetchError extends Component {
renderUnauthorized() {
return <div>
You are not authorized to access report data. Your access token might have expired.
Please go back to Portal and launch report again.
</div>
}
renderGenericInfo(error) {
return (
<div>
<div>URL: {error.url}</div>
<div>Status: {error.status}</div>
<div>Status text: {error.statusText}</div>
</div>
)
}
renderError(error) {
switch(error.status) {
case 401:
return this.renderUnauthorized()
default:
return this.renderGenericInfo(error)
}
}
render() {
const { error } = this.props
return (
<div className='data-fetch-error'>
<h2>Report data download failed</h2>
{this.renderError(error)}
</div>
)
}
}
|
import React, { Component } from 'react'
import pureRender from 'pure-render-decorator'
import '../../css/data-fetch-error.less'
@pureRender
export default class DataFetchError extends Component {
renderUnauthorized() {
return <div>
Your are not authorized to access report data. Your access token might have expired.
Please go back to Portal and launch report again.
</div>
}
renderGenericInfo(error) {
return (
<div>
<div>URL: {error.url}</div>
<div>Status: {error.status}</div>
<div>Status text: {error.statusText}</div>
</div>
)
}
renderError(error) {
switch(error.status) {
case 401:
return this.renderUnauthorized()
default:
return this.renderGenericInfo(error)
}
}
render() {
const { error } = this.props
return (
<div className='data-fetch-error'>
<h2>Report data download failed</h2>
{this.renderError(error)}
</div>
)
}
}
|
Use native Promise instead of $q
|
/* global require */
import platformInfo from './platform-info.js';
let StellarLedger;
if (platformInfo.isElectron) {
const electron = require('electron');
StellarLedger = electron.remote.require('stellar-ledger-api');
}
const bip32Path = (index) => `44'/148'/${index}'`;
const wrapper = (func, field) => new Promise((resolve, reject) => {
StellarLedger.comm.create_async()
.then(comm => {
const api = new StellarLedger.Api(comm);
func(api)
.then(result => resolve(result[field]))
.catch(err => reject(err))
.done(() => comm.close_async());
})
.catch(err => reject(err));
});
const getPublicKey = (index) => {
const func = api => api.getPublicKey_async(bip32Path(index));
return wrapper(func, 'publicKey');
};
const signTxHash = (index, txHash) => {
const func = api => api.signTxHash_async(bip32Path(index), txHash);
return wrapper(func, 'signature');
};
// No Device
// Invalid status 6d00 wrong app
export default {
getPublicKey: getPublicKey,
signTxHash: signTxHash
};
|
/* global angular, require */
import 'ionic-sdk/release/js/ionic.bundle';
import platformInfo from './platform-info.js';
angular.module('app.service.ledger-nano', [])
.factory('LedgerNano', function ($q) {
'use strict';
let StellarLedger;
if (platformInfo.isElectron) {
const electron = require('electron');
StellarLedger = electron.remote.require('stellar-ledger-api');
}
const bip32Path = (index) => `44'/148'/${index}'`;
const wrapper = (func, field) => $q((resolve, reject) => {
StellarLedger.comm.create_async()
.then(comm => {
const api = new StellarLedger.Api(comm);
func(api)
.then(result => resolve(result[field]))
.catch(err => reject(err))
.done(() => comm.close_async());
})
.catch(err => reject(err));
});
const getPublicKey = (index) => {
const func = api => api.getPublicKey_async(bip32Path(index))
return wrapper(func, 'publicKey');
};
const signTxHash = (index, txHash) => {
const func = api => api.signTxHash_async(bip32Path(index), txHash);
return wrapper(func, 'signature');
};
// No Device
// Invalid status 6d00 wrong app
return {
getPublicKey: getPublicKey,
signTxHash: signTxHash
};
});
|
Add int() wrapper to prevent floats
|
import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1
def f(gf,t):
x = int(max(0, min(xmax, x_start+ np.round(x_speed*t))))
y = int(max(0, min(ymax, y_start+ np.round(y_speed*t))))
return gf(t)[y:y+h, x:x+w]
return clip.fl(f, apply_to = apply_to)
|
import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1
def f(gf,t):
x = max(0, min(xmax, x_start+ np.round(x_speed*t)))
y = max(0, min(ymax, y_start+ np.round(y_speed*t)))
return gf(t)[y:y+h, x:x+w]
return clip.fl(f, apply_to = apply_to)
|
Fix profile creation. (Need tests badly).
|
from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.is_bound:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile
|
from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile
|
Fix crash due to missing uses
|
<?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use App;
use View;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
// delay loading this stuff after app has booted,
// to allow all modules to load their stuff first (e.g. register views)
App::booted(function()
{
try
{
// load language
$language = App::make('Language');
View::share('language', $language);
}
catch (\Exception $ex)
{
}
});
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function($router)
{
require app_path('Http/routes.php');
});
}
}
|
<?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
// delay loading this stuff after app has booted,
// to allow all modules to load their stuff first (e.g. register views)
App::booted(function()
{
try
{
// load language
$language = App::make('Language');
View::share('language', $language);
}
catch (\Exception $ex)
{
}
});
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function($router)
{
require app_path('Http/routes.php');
});
}
}
|
Make fields on model have defaults value
Like who cares for their default value
|
from django.db import models
from django.test import TestCase
from django.utils.baseconv import base64
from django_base64field.fields import Base64Field
class Planet(models.Model):
ek = Base64Field()
name = models.CharField(
default='Fucker',
max_length=103
)
class Continent(models.Model):
ek = Base64Field()
name = models.CharField(
default='Suckers!',
max_length=13
)
planet = models.ForeignKey(Planet, to_field='ek')
class TestBase64Field(TestCase):
def test_field_is_none_after_creation(self):
planet = Planet.objects.create(name='Fucking Earth')
self.assertIn(planet.ek, ['', None])
self.assertIsNotNone(planet.pk)
def test_field_not_none_after_saved(self):
planet = Planet.objects.create(name='Little Planet')
base64_key = base64.encode(planet.pk)
saved_planet = Planet.objects.get(pk=planet.pk)
self.assertEqual(saved_planet.ek, base64_key)
|
from django.db import models
from django.test import TestCase
from django.utils.baseconv import base64
from django_base64field.fields import Base64Field
class Planet(models.Model):
ek = Base64Field()
name = models.CharField(max_length=13)
class Continent(models.Model):
ek = Base64Field()
name = models.CharField(max_length=13)
planet = models.ForeignKey(Planet, to_field='ek')
class TestBase64Field(TestCase):
def test_field_is_none_after_creation(self):
planet = Planet.objects.create(name='Fucking Earth')
self.assertIn(planet.ek, ['', None])
self.assertIsNotNone(planet.pk)
def test_field_not_none_after_saved(self):
planet = Planet.objects.create(name='Little Planet')
base64_key = base64.encode(planet.pk)
saved_planet = Planet.objects.get(pk=planet.pk)
self.assertEqual(saved_planet.ek, base64_key)
|
Add error logging to aid tracking down future issues.
|
"""
Scan through the Samples table for oldish entries and remove them.
"""
import logging
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
def purge_item(item, batch):
response = batch.delete_item(
Key={
'event' : item['event'],
'id': item['id']
}
)
def purge_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
filter = Attr('time').lte(decimal.Decimal(time.time()-172800))
with table.batch_writer() as batch:
response = table.scan(
FilterExpression=filter
)
for item in response['Items']:
purge_item(item, batch)
while 'LastEvaluatedKey' in response:
response = scan(
FilterExpression=filter,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for item in response['Items']:
purge_item(item, batch)
|
"""
Scan through the Samples table for oldish entries and remove them.
"""
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def purge_item(item, batch):
response = batch.delete_item(
Key={
'event' : item['event'],
'id': item['id']
}
)
def purge_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
filter = Attr('time').lte(decimal.Decimal(time.time()-172800))
with table.batch_writer() as batch:
response = table.scan(
FilterExpression=filter
)
for item in response['Items']:
purge_item(item, batch)
while 'LastEvaluatedKey' in response:
response = scan(
FilterExpression=filter,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for item in response['Items']:
purge_item(item, batch)
|
Add scale to list of unitless CSS properties
|
// Taken from:
// https://github.com/necolas/react-native-web/blob/master/src/apis/StyleSheet/normalizeValue.js
const unitlessNumbers = {
boxFlex: true,
boxFlexGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related
fillOpacity: true,
strokeDashoffset: true,
strokeOpacity: true,
strokeWidth: true,
scaleX: true,
scaleY: true,
scaleZ: true,
scale: true,
};
const normalizeValue = (property, value) => {
if (!unitlessNumbers[property] && typeof value === 'number') {
return `${value}px`; // TODO(lmr): what if we used `em` or `rem` here?
}
return value;
};
module.exports = normalizeValue;
|
// Taken from:
// https://github.com/necolas/react-native-web/blob/master/src/apis/StyleSheet/normalizeValue.js
const unitlessNumbers = {
boxFlex: true,
boxFlexGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related
fillOpacity: true,
strokeDashoffset: true,
strokeOpacity: true,
strokeWidth: true,
scaleX: true,
scaleY: true,
scaleZ: true,
};
const normalizeValue = (property, value) => {
if (!unitlessNumbers[property] && typeof value === 'number') {
return `${value}px`; // TODO(lmr): what if we used `em` or `rem` here?
}
return value;
};
module.exports = normalizeValue;
|
Add Salmon Run (co-op mode) data
|
require('dotenv').config();
const axios = require('axios');
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const dataPath = path.resolve('public/data');
// SplatNet2 API
const api = axios.create({
baseURL: 'https://app.splatoon2.nintendo.net/api/',
headers: {'Cookie': `iksm_session=${process.env.NINTENDO_SESSION_ID}`},
});
const updateSchedules = function() {
console.info('Updating map schedules...');
api.get('schedules').then(response => {
// Make sure the data path exists
mkdirp(dataPath);
fs.writeFile(`${dataPath}/schedules.json`, JSON.stringify(response.data));
console.info('Updated map schedules.');
});
}
const updateTimeline = function() {
console.info('Updating timeline...');
api.get('timeline').then(response => {
// Make sure the data path exists
mkdirp(dataPath);
// Filter out everything but the data we need
let data = { coop: null };
if (response.data.coop && response.data.coop.importance > -1)
data.coop = response.data.coop;
fs.writeFile(`${dataPath}/timeline.json`, JSON.stringify(data));
console.info('Updated timeline.');
});
}
module.exports.update = function() {
updateSchedules();
updateTimeline();
}
|
require('dotenv').config();
const axios = require('axios');
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const dataPath = path.resolve('public/data');
// SplatNet2 API
const api = axios.create({
baseURL: 'https://app.splatoon2.nintendo.net/api/',
headers: {'Cookie': `iksm_session=${process.env.NINTENDO_SESSION_ID}`},
});
module.exports.update = function() {
// Make sure the data path exists
mkdirp(dataPath);
// Update map schedules
console.info('Updating map schedules...');
api.get('schedules').then(response => {
fs.writeFile(`${dataPath}/schedules.json`, JSON.stringify(response.data));
console.info('Updated map schedules.');
});
}
|
Use Router.TestLocation instead of bare string when testing.
|
import React from 'react';
import Router from 'react-router';
import routes from './routes';
// import SettingsActions from '../../actions/settings';
// import UserActions from '../actions/user';
// var Route = Router.Route;
// describe('Logged in', function () {
// helpStubAjax(SettingsActions);
// UserActions.login({
// data: {
// body: {
// email: "joe@example.com",
// displayName: "joe",
// jwt_token: "asdf"
// }
// }
// });
// jasmine.clock().tick(); // Advance the clock to the next tick
localStorage.setItem('jwt', "asdfsd");
describe('default route', function () {
it('renders home', function (done) {
var rootSlashLocation = new Router.TestLocation(['/']);
Router.run(routes, rootSlashLocation, function (Handler, state){
var html = React.renderToString(<Handler params={state.params} />);
expect(html).toContain("Canvas Starter App");
expect(html).toContain("Login");
expect(html).toContain("Atomic Jolt");
done();
});
});
});
|
import React from 'react';
import Router from 'react-router';
import routes from './routes';
// import SettingsActions from '../../actions/settings';
// import UserActions from '../actions/user';
// var Route = Router.Route;
// describe('Logged in', function () {
// helpStubAjax(SettingsActions);
// UserActions.login({
// data: {
// body: {
// email: "joe@example.com",
// displayName: "joe",
// jwt_token: "asdf"
// }
// }
// });
// jasmine.clock().tick(); // Advance the clock to the next tick
localStorage.setItem('jwt', "asdfsd");
describe('default route', function () {
it('renders home', function (done) {
Router.run(routes, '/', function (Handler, state){
var html = React.renderToString(<Handler params={state.params} />);
expect(html).toMatch(/Home/);
done();
});
});
});
|
Use six to improve python 3 compatibility.
* StringIO
Change-Id: I8471e525566a0353d9276529be4b0d0e0cbf6cd6
|
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from Crypto.PublicKey import RSA
from Crypto import Random
import paramiko
from six import StringIO
def generate_private_key(length=2048):
"""Generate RSA private key (str) with the specified length."""
rsa = RSA.generate(length, Random.new().read)
return rsa.exportKey('PEM')
def to_paramiko_private_key(pkey):
"""Convert private key (str) to paramiko-specific RSAKey object."""
return paramiko.RSAKey(file_obj=StringIO.StringIO(pkey))
def private_key_to_public_key(key):
"""Convert private key (str) to public key (str)."""
return RSA.importKey(key).exportKey('OpenSSH')
|
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from Crypto.PublicKey import RSA
from Crypto import Random
import paramiko
import StringIO
def generate_private_key(length=2048):
"""Generate RSA private key (str) with the specified length."""
rsa = RSA.generate(length, Random.new().read)
return rsa.exportKey('PEM')
def to_paramiko_private_key(pkey):
"""Convert private key (str) to paramiko-specific RSAKey object."""
return paramiko.RSAKey(file_obj=StringIO.StringIO(pkey))
def private_key_to_public_key(key):
"""Convert private key (str) to public key (str)."""
return RSA.importKey(key).exportKey('OpenSSH')
|
Use real mail address to make PyPi happy
|
from setuptools import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451@laposte.net',
maintainer='montag451',
maintainer_email='montag451@laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Python',
long_description=open('README.rst').read(),
version='2.3.0',
ext_modules=[Extension('pytun', ['pytun.c'])],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: C',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking'])
|
from setuptools import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451 at laposte.net',
maintainer='montag451',
maintainer_email='montag451 at laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Python',
long_description=open('README.rst').read(),
version='2.3.0',
ext_modules=[Extension('pytun', ['pytun.c'])],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: C',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking'])
|
Address PR comments on unit test for confirm delete
|
import Ember from "ember";
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:gist', {
needs: ['service:ember-cli'],
beforeEach() {
this._originalConfirm = window.confirm;
},
afterEach() {
window.confirm = this._originalConfirm;
}
});
test('deleting a gist requires confirmation', function(assert) {
let controller = this.subject({
transitionToRoute() {},
notify: {
info() {}
}
});
let gistClass = Ember.Object.extend({
called: false,
destroyRecord() {
this.set('called', true);
}
});
window.confirm = () => true;
let gist = gistClass.create();
controller.send('deleteGist', gist);
assert.ok(gist.get('called'), 'gist.destroyRecord was called when confirmed');
window.confirm = () => false;
gist = gistClass.create();
controller.send('deleteGist', gist);
assert.ok(!gist.get('called'), 'gist.destroyRecord was not called when not confirmed');
});
|
import Ember from "ember";
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:gist', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
needs: ['service:ember-cli']
});
// Replace this with your real tests.
test('it exists', function(assert) {
var controller = this.subject();
assert.ok(controller);
});
test('deleting a gist requires confirmation', function(assert) {
let cacheConfirm = window.confirm;
let controller = this.subject({
transitionToRoute() {},
notify: {
info() {}
}
});
let gistClass = Ember.Object.extend({
called: false,
destroyRecord() {
this.set('called', true);
}
});
window.confirm = () => true;
let gist = gistClass.create();
controller.send('deleteGist', gist);
assert.ok(gist.get('called'), 'gist.destroyRecord was called when confirmed');
window.confirm = () => false;
gist = gistClass.create();
controller.send('deleteGist', gist);
assert.ok(!gist.get('called'), 'gist.destroyRecord was not called when not confirmed');
window.confirm = cacheConfirm;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.