text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Print the traceback as well for debugging purposes. | #!/usr/bin/env python
import sys
import logging
import traceback
import click
from os import path
# Add top-level module path to sys.path before importing tubular code.
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from tubular import asgard
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(ami_id)
except Exception, e:
traceback.print_exc()
click.secho("Error Deploying AMI: {0}.\nMessage: {1}".format(ami_id, e.message), fg='red')
sys.exit(1)
sys.exit(0)
if __name__ == "__main__":
deploy()
| #!/usr/bin/env python
import sys
import logging
import click
from os import path
# Add top-level module path to sys.path before importing tubular code.
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from tubular import asgard
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(ami_id)
except Exception, e:
click.secho("Error Deploying AMI: {0}.\nMessage: {1}".format(ami_id, e.message), fg='red')
sys.exit(1)
sys.exit(0)
if __name__ == "__main__":
deploy()
|
Fix the telemetry statistics test
This test worked fine on devstack, but failed on the test gate
because not all meters have statistics. Look for a meter with
statistics.
Partial-bug: #1665495
Change-Id: Ife0f1f11c70e926801b48000dd0b4e9d863a865f | # 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.
import unittest
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestStatistics(base.BaseFunctionalTest):
def test_list(self):
for met in self.conn.telemetry.meters():
for stat in self.conn.telemetry.statistics(met):
self.assertTrue(stat.period_end_at is not None)
break
| # 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.
import unittest
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestStatistics(base.BaseFunctionalTest):
def test_list(self):
found_something = False
for met in self.conn.telemetry.meters():
try:
stat = next(self.conn.telemetry.statistics(met))
self.assertIn('period_end', stat)
found_something = True
except Exception:
pass
self.assertTrue(found_something)
|
Change let to var for node 5 support | // Babel required for es6 code in e2e tests
require('babel-register');
var config = {
baseUrl: 'http://localhost:8080',
specs: ['./src/**/*.e2e.js'],
capabilities: {
'browserName': 'chrome'
},
// Current firefox version does not navigate to page. Disable until problem
// fixed, though it seems to be a reocurring issue
// See: https://github.com/angular/protractor/issues/3150
// {
// 'browserName': 'firefox'
// }
onPrepare: function() {
browser.manage().window().setSize(1280, 1024);
}
};
if (process.env.TRAVIS) {
config.sauceUser = process.env.SAUCE_USERNAME;
config.sauceKey = process.env.SAUCE_ACCESS_KEY;
config.capabilities = {
'browserName': 'chrome',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER
};
}
exports.config = config;
| // Babel required for es6 code in e2e tests
require('babel-register');
let config = {
baseUrl: 'http://localhost:8080',
specs: ['./src/**/*.e2e.js'],
capabilities: {
'browserName': 'chrome'
},
// Current firefox version does not navigate to page. Disable until problem
// fixed, though it seems to be a reocurring issue
// See: https://github.com/angular/protractor/issues/3150
// {
// 'browserName': 'firefox'
// }
onPrepare: function() {
browser.manage().window().setSize(1280, 1024);
}
};
if (process.env.TRAVIS) {
config.sauceUser = process.env.SAUCE_USERNAME;
config.sauceKey = process.env.SAUCE_ACCESS_KEY;
config.capabilities = {
'browserName': 'chrome',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER
};
}
exports.config = config;
|
Refactor code using es6 syntax | import authControllers from '../controllers';
const usersController = authControllers.users;
const loginController = authControllers.login;
module.exports = (app) => {
app.get('/api', (req, res) => res.status(200).send({
message: 'Welcome to the Todos API!',
}));
app.post('/api/user/signin', loginController.login);
app.post('/api/user/signup', usersController.create);
// An API route that allow users create broadcast groups:
// POST: /api/group
app.post('/api/group', (req, res) => res.send('Create a group'));
// An API route that allow users add other users to groups:
app.post('/api/group/:groupid/user', (req, res) => res.send(`Added new user to ${req.params.groupid}.`));
// An API route that allows a logged in user post messages to created groups:
app.post('/api/group/:groupid/message', (req, res) => res.send(`Thanks for posting ur message to ${req.params.groupid}`));
// An API route that allows a logged in user retrieve messages that have been
// posted to groups he/she belongs to:
app.get('/api/group/:groupid/messages', (req, res) => res.send(`Welcome! here are the messages for ${req.params.groupid}`));
// Root route
app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist'));
};
| import usersControllers from '../controllers';
import loginControllers from '../controllers';
const usersController = usersControllers.users;
const loginController = loginControllers.login;
module.exports = (app) => {
app.get('/api', (req, res) => res.status(200).send({
message: 'Welcome to the Todos API!',
}));
app.post('/api/user/signin', loginController.login);
app.post('/api/user/signup', usersController.create);
// An API route that allow users create broadcast groups:
// POST: /api/group
app.post('/api/group', (req, res) => res.send('Create a group'));
// An API route that allow users add other users to groups:
app.post('/api/group/:groupid/user', (req, res) => res.send(`Added new user to ${req.params.groupid}.`));
// An API route that allows a logged in user post messages to created groups:
app.post('/api/group/:groupid/message', (req, res) => res.send(`Thanks for posting ur message to ${req.params.groupid}`));
// An API route that allows a logged in user retrieve messages that have been
// posted to groups he/she belongs to:
app.get('/api/group/:groupid/messages', (req, res) => res.send(`Welcome! here are the messages for ${req.params.groupid}`));
// Root route
app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist'));
};
|
Update serviceworker cache config for source files | module.exports = {
staticFileGlobs: [
'manifest.json',
'images/*',
'src/**/*',
],
importScripts: [
'push-handler.js'
],
runtimeCaching: [
{
urlPattern: /\/@webcomponents\/webcomponentsjs\//,
handler: 'fastest'
},
{
urlPattern: /\/data\/images\/.*/,
handler: 'cacheFirst',
options: {
cache: {
maxEntries: 200,
name: 'items-cache'
}
}
},
{
urlPattern: /\/api\//,
handler: 'networkFirst'
},
{
urlPattern: /\/omniauth\//,
handler: 'networkOnly'
}
]
};
| module.exports = {
navigateFallbackWhitelist: [/^\/nothing\//],
staticFileGlobs: [
'manifest.json',
'bower_components/webcomponentsjs/*.js',
'images/*'
],
importScripts: [
'push-handler.js'
],
runtimeCaching: [
{
urlPattern: /\/data\/images\/.*/,
handler: 'cacheFirst',
options: {
cache: {
maxEntries: 200,
name: 'items-cache'
}
}
},
{
urlPattern: /\/api\//,
handler: 'networkFirst'
},
{
urlPattern: /\/omniauth\//,
handler: 'networkOnly'
}
]
};
|
Add database router allow_migrate() for Django 1.7 | from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_migrate(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
def allow_syncdb(self, db, model):
# allow_syncdb was changed to allow_migrate in django 1.7
return self.allow_migrate(db, model)
| from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_syncdb(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
|
Increase abstractness for one test method | from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die")
| from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "Clencher (de.rouck.robrecht@gmail.com)"
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die")
|
Make it nicer and break it, to be a kata :). | // block scope - let
// To do: make all tests pass, leave the asserts unchanged!
describe('`let` restricts the scope of the variable to the current block', () => {
describe('`let` vs. `var`', () => {
it('`var` works as usual', () => {
if (true) {
let varX = true;
}
assert.equal(varX, true);
});
it('`let` restricts scope to inside the block', () => {
if (true) {
var letX = true;
}
assert.throws(() => console.log(letX));
});
});
describe('`let` usage', () => {
it('`let` use in `for` loops', () => {
let obj = {x: 1};
for (var key in obj) {}
assert.throws(() => console.log(key));
});
it('create artifical scope, using curly braces', () => {
{
var letX = true;
}
assert.throws(() => console.log(letX));
});
});
});
| // block scope - let
// To do: make all tests pass, leave the asserts unchanged!
describe('`let` restricts the scope of the variable to the current block', () => {
describe('`let` vs. `var`', () => {
it('`var` works as usual', () => {
if (true) {
var varX = true;
}
assert.equal(varX, true);
});
it('`let` restricts scope to inside the block', () => {
if(true) {
let letX = true;
}
assert.throws(() => console.log(letX));
});
});
it('`let` use in `for` loops', () => {
let obj = {x: 1};
for (let key in obj) {}
assert.throws(() => console.log(key));
});
it('create artifical scope, using curly braces', () => {
{
let letX = true;
}
assert.throws(() => console.log(letX));
});
});
|
Add _id getter as .id property | const BlacklistModel = require('../../models/Blacklist.js').model
const Base = require('./Base.js')
class Blacklist extends Base {
constructor (data, _saved) {
super(data, _saved)
if (!this._id) {
throw new TypeError('_id is undefined')
}
/**
* Type of blacklist. 0 for user, 1 for guild
* @type {number}
*/
this.type = this.getField('type')
if (this.type === undefined) {
throw new TypeError('type is undefined')
}
if (isNaN(this.type)) {
throw new TypeError('type is not a number')
}
/**
* Optional name of the target
* @type {string}
*/
this.name = this.getField('name')
}
/**
* Getter for _id
* @returns {string}
*/
get id () {
return this.getField('_id')
}
static get TYPES () {
return {
USER: 0,
GUILD: 1
}
}
toObject () {
return {
_id: this._id,
type: this.type,
name: this.name
}
}
static get Model () {
return BlacklistModel
}
}
module.exports = Blacklist
| const BlacklistModel = require('../../models/Blacklist.js').model
const Base = require('./Base.js')
class Blacklist extends Base {
constructor (data, _saved) {
super(data, _saved)
if (!this._id) {
throw new TypeError('_id is undefined')
}
/**
* Type of blacklist. 0 for user, 1 for guild
* @type {number}
*/
this.type = this.getField('type')
if (this.type === undefined) {
throw new TypeError('type is undefined')
}
if (isNaN(this.type)) {
throw new TypeError('type is not a number')
}
/**
* Optional name of the target
* @type {string}
*/
this.name = this.getField('name')
}
static get TYPES () {
return {
USER: 0,
GUILD: 1
}
}
toObject () {
return {
_id: this._id,
type: this.type,
name: this.name
}
}
static get Model () {
return BlacklistModel
}
}
module.exports = Blacklist
|
Drop header to avoid auth browser popup | var log4js = require('log4js');
var logger = log4js.getLogger();
var express = require('express');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ipaddress = process.env.OPENSHIFT_NODEJS_IP;
var loglevel = process.env.LOGLEVEL || 'DEBUG';
var app = express();
app.use(favicon(__dirname + '/public/favicon.ico'));
logger.setLevel(loglevel);
app.use(express.static('public'));
app.use(log4js.connectLogger(log4js.getLogger('http'), { level: 'auto' }));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.raw({limit: '10mb', type: 'image/jpeg'}));
app.use(function (req, res, next) {
res.removeHeader("WWW-Authenticate");
next();
});
app.use('/api/', require('./routes/').router);
/* app.use(function(error, req, res, next) {
if (error) {
logger.error('InvalidInput', error.message);
res.status(error.status).send({error: 'InvalidInput', description: error.message});
} else {
next();
}
}); */
app.listen(port, ipaddress, function () {
logger.info('starting rikitrakiws', this.address());
});
| var log4js = require('log4js');
var logger = log4js.getLogger();
var express = require('express');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ipaddress = process.env.OPENSHIFT_NODEJS_IP;
var loglevel = process.env.LOGLEVEL || 'DEBUG';
var app = express();
app.use(favicon(__dirname + '/public/favicon.ico'));
logger.setLevel(loglevel);
app.use(express.static('public'));
app.use(log4js.connectLogger(log4js.getLogger('http'), { level: 'auto' }));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.raw({limit: '10mb', type: 'image/jpeg'}));
app.use('/api/', require('./routes/').router);
app.use(function (req, res, next) {
res.removeHeader("WWW-Authenticate");
next();
});
/* app.use(function(error, req, res, next) {
if (error) {
logger.error('InvalidInput', error.message);
res.status(error.status).send({error: 'InvalidInput', description: error.message});
} else {
next();
}
}); */
app.listen(port, ipaddress, function () {
logger.info('starting rikitrakiws', this.address());
});
|
Check property existence to allow 0s | // @flow
import debug from 'debug'
import get from 'lodash/get'
const dbg = debug('woonerf:message')
/**
* Expose a Set of all the keys used
*/
export const KeysUsed = new Set()
/**
* Set the messages object
*/
export function setMessages (newMessages) {
messages = newMessages
}
let messages = {}
if (process.env.MESSAGES) {
setMessages(JSON.parse(process.env.MESSAGES))
}
/**
* Requires a key, defaultMessage and parameters are optional
*/
export default function getMessage (key: string, defaultMessage?: string | Object, parameters?: Object): string {
if (defaultMessage == null) {
defaultMessage = ''
parameters = {}
} else if (typeof defaultMessage === 'object') {
parameters = defaultMessage
defaultMessage = ''
}
// Store the used key
KeysUsed.add(key)
// Get the message with "lodash/get" to allow nested keys ('noun.action' => {noun: {action: 'value'}})
const msg = get(messages, key, defaultMessage)
const result = parameters ? replaceMessage(msg, parameters) : msg
dbg(key, result)
return result
}
function replaceMessage (msg, data) {
return msg.replace(
new RegExp('%\\((' + Object.keys(data).join('|') + ')\\)', 'g'),
(m, key) => data.hasOwnProperty(key) ? data[key] : m
)
}
| // @flow
import debug from 'debug'
import get from 'lodash/get'
const dbg = debug('woonerf:message')
/**
* Expose a Set of all the keys used
*/
export const KeysUsed = new Set()
/**
* Set the messages object
*/
export function setMessages (newMessages) {
messages = newMessages
}
let messages = {}
if (process.env.MESSAGES) {
setMessages(JSON.parse(process.env.MESSAGES))
}
/**
* Requires a key, defaultMessage and parameters are optional
*/
export default function getMessage (key: string, defaultMessage?: string | Object, parameters?: Object): string {
if (defaultMessage == null) {
defaultMessage = ''
parameters = {}
} else if (typeof defaultMessage === 'object') {
parameters = defaultMessage
defaultMessage = ''
}
// Store the used key
KeysUsed.add(key)
// Get the message with "lodash/get" to allow nested keys ('noun.action' => {noun: {action: 'value'}})
const msg = get(messages, key, defaultMessage)
const result = parameters ? replaceMessage(msg, parameters) : msg
dbg(key, result)
return result
}
function replaceMessage (msg, data) {
return msg.replace(new RegExp('%\\((' + Object.keys(data).join('|') + ')\\)', 'g'), (m, key) => data[key] || m)
}
|
Fix relative paths for spa | var path = require('path'),
fs = require('fs');
function FileUrlMapper(options) {
this.base = options.directory;
this.spa = options.spa;
}
FileUrlMapper.prototype.hasTrailingSlash = function(url) {
return url[url.length - 1] === '/';
};
FileUrlMapper.prototype.implicitIndexConversion = function(url) {
return url + 'index.html';
};
FileUrlMapper.prototype.relativeFilePath = function(url) {
return this.hasTrailingSlash(url) ? this.implicitIndexConversion(url) : url;
};
FileUrlMapper.prototype.pathFromUrl = function(url) {
if(this.spa) return path.join(this.base, this.relativeFilePath('index.html'));
return path.join(this.base, this.relativeFilePath(url));
};
FileUrlMapper.prototype.urlFromPath = function(filePath) {
return path.relative(this.base, filePath);
};
module.exports = FileUrlMapper;
| var path = require('path'),
fs = require('fs');
function FileUrlMapper(options) {
this.base = options.directory;
this.spa = options.spa;
}
FileUrlMapper.prototype.hasTrailingSlash = function(url) {
return url[url.length - 1] === '/';
};
FileUrlMapper.prototype.implicitIndexConversion = function(url) {
return url + 'index.html';
};
FileUrlMapper.prototype.relativeFilePath = function(url) {
return this.hasTrailingSlash(url) ? this.implicitIndexConversion(url) : url;
};
FileUrlMapper.prototype.pathFromUrl = function(url) {
if(this.spa) return path.relative(this.base, 'index.html');
return path.join(this.base, this.relativeFilePath(url));
};
FileUrlMapper.prototype.urlFromPath = function(filePath) {
return path.relative(this.base, filePath);
};
module.exports = FileUrlMapper;
|
JCR-1878: Use Apache Tika for text extraction
Automatically improve any configurations that use DefaultTextExtractor by making that class extend TikaTextExtractor.
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@762813 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/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 org.apache.jackrabbit.extractor;
/**
* Composite text extractor that by default contains the standard
* text extractors found in this package.
*
* @deprecated Use {@link TikaTextExtractor} instead
*/
public class DefaultTextExtractor extends TikaTextExtractor {
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/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 org.apache.jackrabbit.extractor;
/**
* Composite text extractor that by default contains the standard
* text extractors found in this package.
*/
public class DefaultTextExtractor extends CompositeTextExtractor {
/**
* Creates the default text extractor by adding instances of the standard
* text extractors as components.
*/
public DefaultTextExtractor() {
addTextExtractor(new PlainTextExtractor());
addTextExtractor(new XMLTextExtractor());
}
}
|
Create function for displaying success messages | /**
* Created by nkmathew on 23/06/2016.
*/
// Spinjs options for a big spinner
var BIG_SPINNER = {
lines: 13,
length: 33,
width: 14,
radius: 42,
scale: 0.5,
color: '#000',
};
// Display a success message
function alertSuccess(message) {
$('.alert-box .msg').html(message);
$('.alert-box').addClass('alert-success');
$('.alert-box').show();
$("#alert-box").fadeTo(3000, 500).slideUp(500, function () {
$("#alert-box").hide();
});
}
$(document).ready(function () {
// Initialize bootstrap tooltip plugin
$('[data-toggle="tooltip"]').tooltip();
// Save the id of the last clicked tab in a cookie
$('.tab-main > a[data-toggle="tab"]').click(function (e) {
Cookies.set('last_tab', $(e.target).attr('href'));
});
// Opens the last tab before the page reload
var lastTab = Cookies.get('last_tab');
if (lastTab) {
$('a[href=' + lastTab + ']').click();
}
});
| /**
* Created by nkmathew on 23/06/2016.
*/
// Spinjs options for a big spinner
var BIG_SPINNER = {
lines: 13,
length: 33,
width: 14,
radius: 42,
scale: 0.5,
color: '#000',
};
$(document).ready(function () {
// Initialize bootstrap tooltip plugin
$('[data-toggle="tooltip"]').tooltip();
// Save the id of the last clicked tab in a cookie
$('.tab-main > a[data-toggle="tab"]').click(function (e) {
Cookies.set('last_tab', $(e.target).attr('href'));
});
// Opens the last tab before the page reload
var lastTab = Cookies.get('last_tab');
if (lastTab) {
$('a[href=' + lastTab + ']').click();
}
});
|
Change version to 1.0.2 (stable) | # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0.2",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
A credit transfer config link a bank with a parser
A credit transfer parser link a parser with a template that you can upload
""",
"depends": [
'base',
'account_streamline',
],
"data": [
"security/ir.model.access.csv",
"views/config.xml",
"views/parser.xml",
"views/res.bank.xml",
],
'demo_xml': [],
'test': [],
'installable': True,
'active': False,
'external_dependencies': {
'python': ['genshi']
}
}
| # -*- coding: utf-8 -*-
{
"name": "Account Credit Transfer",
"version": "1.0.1",
"author": "XCG Consulting",
"website": "http://www.openerp-experts.com",
"category": 'Accounting',
"description": """Account Voucher Credit Transfer Payment.
You need to set up some things before using it.
A credit transfer config link a bank with a parser
A credit transfer parser link a parser with a template that you can upload
""",
"depends": [
'base',
'account_streamline',
],
"data": [
"security/ir.model.access.csv",
"views/config.xml",
"views/parser.xml",
"views/res.bank.xml",
],
'demo_xml': [],
'test': [],
'installable': True,
'active': False,
'external_dependencies': {
'python': ['genshi']
}
}
|
Add trove classifier for Python 3 | #!/usr/bin/env python
from distutils.core import setup
setup(
name='dbtools',
version=open("VERSION.txt").read().strip(),
description='Lightweight SQLite interface',
author='Jessica B. Hamrick',
author_email='jhamrick@berkeley.edu',
url='https://github.com/jhamrick/dbtools',
packages=['dbtools'],
keywords='sqlite pandas dataframe',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: SQL",
"Topic :: Database :: Front-Ends",
"Topic :: Utilities",
],
install_requires=[
'pandas',
'numpy'
]
)
| #!/usr/bin/env python
from distutils.core import setup
setup(
name='dbtools',
version=open("VERSION.txt").read().strip(),
description='Lightweight SQLite interface',
author='Jessica B. Hamrick',
author_email='jhamrick@berkeley.edu',
url='https://github.com/jhamrick/dbtools',
packages=['dbtools'],
keywords='sqlite pandas dataframe',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2.7",
"Programming Language :: SQL",
"Topic :: Database :: Front-Ends",
"Topic :: Utilities",
],
install_requires=[
'pandas',
'numpy'
]
)
|
[Cleanup] Replace 'list.extend' call with '+' operator
I knew there had to be an easier way for merging lists other than `extend`. Turns out the plus operator does exactly what I need. |
from console import Console
from rom import ROM
from functools import reduce
class ROMFinder(object):
def __init__(self, filesystem):
self.filesystem = filesystem
def roms_for_console(self, console):
"""
@param console - A console object
@returns A list of ROM objects representing all of the valid ROMs for a
given console.
Valid ROMs are defined as ROMs for which `console`'s `is_valid_rom` method
returns True.
Returns an empty list if `console` is not enabled
"""
if not console.is_enabled():
return []
paths = self.filesystem.files_in_directory(console.roms_directory())
valid_rom_paths = filter(console.is_valid_rom, paths)
return map(lambda path: ROM(path, console), valid_rom_paths)
def roms_for_consoles(self, consoles):
"""
@param consoles - An iterable list of consoles
@returns A list of all of the ROMs for all of the consoles in `consoles`
Equivalent to calling `roms_for_console` on every element of `consoles`
and combining the results
"""
return reduce(lambda roms, console: roms + self.roms_for_console(console), consoles, [])
|
from console import Console
from rom import ROM
from functools import reduce
class ROMFinder(object):
def __init__(self, filesystem):
self.filesystem = filesystem
def roms_for_console(self, console):
"""
@param console - A console object
@returns A list of ROM objects representing all of the valid ROMs for a
given console.
Valid ROMs are defined as ROMs for which `console`'s `is_valid_rom` method
returns True.
Returns an empty list if `console` is not enabled
"""
if not console.is_enabled():
return []
paths = self.filesystem.files_in_directory(console.roms_directory())
valid_rom_paths = filter(console.is_valid_rom, paths)
return map(lambda path: ROM(path, console), valid_rom_paths)
def roms_for_consoles(self, consoles):
"""
@param consoles - An iterable list of consoles
@returns A list of all of the ROMs for all of the consoles in `consoles`
Equivalent to calling `roms_for_console` on every element of `consoles`
and combining the results
"""
assert hasattr(
consoles, '__iter__'), "Expecting an iterable list of consoles"
def rom_collector(roms, console):
roms.extend(self.roms_for_console(console))
return roms
return reduce(rom_collector, consoles, [])
|
Add break-word property to error messages of long hex strings | import React from "react";
import { map } from "lodash-es";
import { Alert } from "../../base";
const JobError = ({ error }) => {
if (!error) {
return null;
}
// Traceback from a Python exception.
const tracebackLines = map(error.traceback, (line, index) =>
<div key={index} className="traceback-line">{line}</div>
);
// Only show a colon and exception detail after the exception name if there is detail present.
const details = error.details.length
? <span style={{display: "inline-block", wordBreak: "break-word"}}>: {error.details}</span>
: null;
// Content replicates format of Python exceptions shown in Python console.
return (
<Alert bsStyle="danger">
<div>Traceback (most recent call last):</div>
{tracebackLines}
<p>{error.type}{details}</p>
</Alert>
);
};
export default JobError;
| import React from "react";
import { map } from "lodash-es";
import { Alert } from "../../base";
const JobError = ({ error }) => {
if (!error) {
return null;
}
// Traceback from a Python exception.
const tracebackLines = map(error.traceback, (line, index) =>
<div key={index} className="traceback-line">{line}</div>
);
// Only show a colon and exception detail after the exception name if there is detail present.
const details = error.details.length ? <span>: {error.details}</span> : null;
// Content replicates format of Python exceptions shown in Python console.
return (
<Alert bsStyle="danger">
<div>Traceback (most recent call last):</div>
{tracebackLines}
<p>{error.type}{details}</p>
</Alert>
);
};
export default JobError;
|
Update test harness configuration for Travis CI. | #!/usr/bin/python
import sys, os, os.path
from subprocess import call
cur_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(cur_dir)
statuses = [
call(["echo", "Running python unit tests via nose..."]),
call([os.path.join(parent_dir, "manage.py"), "test", "harmony.apps.lab.tests"], env=os.environ.copy()),
call([os.path.join(cur_dir, "prepare_tests.py")], env=os.environ.copy()),
call(["/usr/bin/env", "phantomjs", os.path.join(cur_dir, "jasmine.js")], env=os.environ.copy()),
]
final_status = 0
for status in statuses:
if status != 0:
final_status = status
break
sys.exit(final_status)
| #!/usr/bin/python
import sys, os, os.path
from subprocess import call
cur_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(cur_dir)
statuses = [
call(["echo", "Running python unit tests via nose..."]),
call(["/usr/bin/env", "nosetests", parent_dir], env=os.environ.copy()),
call([os.path.join(cur_dir, "prepare_tests.py")], env=os.environ.copy()),
call(["/usr/bin/env", "phantomjs", os.path.join(cur_dir, "jasmine.js")], env=os.environ.copy()),
]
final_status = 0
for status in statuses:
if status != 0:
final_status = status
break
sys.exit(final_status)
|
[TASK] Use the anonymous function expression style to describe the default grunt tasks
This is to increase the readability of the code | module.exports = function(grunt) {
"use strict";
// Display the execution time of grunt tasks
require("time-grunt")(grunt);
// Load all grunt-tasks in 'Build/Grunt-Options'.
var gruntOptionsObj = require("load-grunt-configs")(grunt, {
"config" : {
src: "Build/Grunt-Options/*.js"
}
});
grunt.initConfig(gruntOptionsObj);
// Load all grunt-plugins that are specified in the 'package.json' file.
require('jit-grunt')(grunt, {
replace: 'grunt-text-replace',
cssmetrics: 'grunt-css-metrics',
bower: 'grunt-bower-task'
});
/**
* Default grunt task.
* Compiles all .scss/.sass files with ':dev' options and
* validates all js-files inside Resources/Private/Javascripts with JSHint.
*/
grunt.registerTask("default", function() {
grunt.task.run(["css", "jshint"]);
});
/**
* Travis CI task
* Test all specified grunt tasks.
*/
grunt.registerTask("travis", function() {
grunt.task.run(["init", "replace:init", "jshint", "deploy", "undeploy"]);
});
/**
* Load custom tasks
* Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir.
*/
grunt.loadTasks("Build/Grunt-Tasks");
};
| module.exports = function(grunt) {
"use strict";
// Display the execution time of grunt tasks
require("time-grunt")(grunt);
// Load all grunt-tasks in 'Build/Grunt-Options'.
var gruntOptionsObj = require("load-grunt-configs")(grunt, {
"config" : {
src: "Build/Grunt-Options/*.js"
}
});
grunt.initConfig(gruntOptionsObj);
// Load all grunt-plugins that are specified in the 'package.json' file.
require('jit-grunt')(grunt, {
replace: 'grunt-text-replace',
cssmetrics: 'grunt-css-metrics',
bower: 'grunt-bower-task'
});
/**
* Default grunt task.
* Compiles all .scss/.sass files with ':dev' options and
* validates all js-files inside Resources/Private/Javascripts with JSHint.
*/
grunt.registerTask("default", ["css", "jshint"]);
/**
* Travis CI task
* Test all specified grunt tasks.
*/
grunt.registerTask("travis", ["init", "replace:init", "jshint", "deploy", "undeploy"]);
/**
* Load custom tasks
* Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir.
*/
grunt.loadTasks("Build/Grunt-Tasks");
};
|
Fix setting wrong property on owl:inverseProperty | package de.linkvt.bachelor.features.properties;
import de.linkvt.bachelor.features.Feature;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.springframework.stereotype.Component;
/**
* An owl functional property.
*/
@Component
public class OwlInverseOfPropertyFeature extends Feature {
@Override
public void addToOntology() {
OWLClass domain = featurePool.getReusableClass();
OWLClass range = featurePool.getExclusiveClass("Child");
OWLObjectProperty property = featurePool.getExclusiveProperty("hasChild");
addProperty(property, domain, range);
OWLObjectProperty inverseProperty = featurePool.getExclusiveProperty("hasParent");
addProperty(inverseProperty, range, domain);
addAxiomToOntology(factory.getOWLInverseObjectPropertiesAxiom(property, inverseProperty));
}
@Override
public String getName() {
return "owl:inverseOf";
}
@Override
public String getToken() {
return "inverseprop";
}
}
| package de.linkvt.bachelor.features.properties;
import de.linkvt.bachelor.features.Feature;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.springframework.stereotype.Component;
/**
* An owl functional property.
*/
@Component
public class OwlInverseOfPropertyFeature extends Feature {
@Override
public void addToOntology() {
OWLClass domain = featurePool.getReusableClass();
OWLClass range = featurePool.getExclusiveClass("Child");
OWLObjectProperty property = featurePool.getExclusiveProperty("hasChild");
addProperty(property, domain, range);
OWLObjectProperty inverseProperty = featurePool.getExclusiveProperty("hasParent");
addProperty(property, range, domain);
addAxiomToOntology(factory.getOWLInverseObjectPropertiesAxiom(property, inverseProperty));
}
@Override
public String getName() {
return "owl:inverseOf";
}
@Override
public String getToken() {
return "inverseprop";
}
}
|
Test that keydown event resets the timeout | (function($) {
/*
======== A Handy Little QUnit Reference ========
http://docs.jquery.com/QUnit
Test methods:
expect(numAssertions)
stop(increment)
start(decrement)
Test assertions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
raises(block, [expected], [message])
*/
module("jQuery#idle-timer");
asyncTest( "default behavior", function() {
expect( 1 );
$( document ).on( "idle.idleTimer", function(){
ok( true, "idleTime fires at document by default" );
start();
$.idleTimer( "destroy" );
});
$.idleTimer( 100 );
});
asyncTest( "Should clear timeout on keydown event", function() {
expect( 3 );
// trigger event every now and then to prevent going inactive
var interval = setInterval( function()
{
$( document ).trigger( "keydown" );
equal( $( document ).data( "idleTimer" ), "active", "State should be active" );
}, 100);
setTimeout( function()
{
clearTimeout( interval );
start();
$.idleTimer( "destroy" );
}, 350);
$.idleTimer( 200 );
});
}(jQuery));
| (function($) {
/*
======== A Handy Little QUnit Reference ========
http://docs.jquery.com/QUnit
Test methods:
expect(numAssertions)
stop(increment)
start(decrement)
Test assertions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
raises(block, [expected], [message])
*/
module("jQuery#idle-timer");
asyncTest( "default behavior", function() {
expect( 1 );
$( document ).on( "idle.idleTimer", function(){
ok( true, "idleTime fires at document by default" );
start();
$.idleTimer( "destroy" );
});
$.idleTimer( 100 );
});
}(jQuery));
|
Fix missing space in autosizing info message.
BUG=
Review URL: https://codereview.chromium.org/1045933003
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@192791 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | function setWindowSizeOverride(width, height) {
if (window.internals)
window.internals.settings.setTextAutosizingWindowSizeOverride(width, height);
}
function setFontScaleFactor(scale) {
if (window.internals)
window.internals.settings.setAccessibilityFontScaleFactor(scale);
}
function initAutosizingTest() {
if (window.internals) {
window.internals.settings.setTextAutosizingEnabled(true);
setWindowSizeOverride(320, 480);
} else if (window.console && console.warn) {
console.warn("This test depends on Text Autosizing being enabled. Run with content shell "
+ "and --run-layout-test or manually enable Text Autosizing and either use a "
+ "mobile device with 320px device-width (like Nexus S or iPhone), or define "
+ "DEBUG_TEXT_AUTOSIZING_ON_DESKTOP.");
}
}
// Automatically call init. Users who want a different window size can use setWindowSizeOverride.
initAutosizingTest();
| function setWindowSizeOverride(width, height) {
if (window.internals)
window.internals.settings.setTextAutosizingWindowSizeOverride(width, height);
}
function setFontScaleFactor(scale) {
if (window.internals)
window.internals.settings.setAccessibilityFontScaleFactor(scale);
}
function initAutosizingTest() {
if (window.internals) {
window.internals.settings.setTextAutosizingEnabled(true);
setWindowSizeOverride(320, 480);
} else if (window.console && console.warn) {
console.warn("This test depends on Text Autosizing being enabled. Run with content shell"
+ "and --run-layout-test or manually enable Text Autosizing and either use a "
+ "mobile device with 320px device-width (like Nexus S or iPhone), or define "
+ "DEBUG_TEXT_AUTOSIZING_ON_DESKTOP.");
}
}
// Automatically call init. Users who want a different window size can use setWindowSizeOverride.
initAutosizingTest(); |
Use correct path for depth image | define( ["app", "scribbler"], function( app, scribbler ) {
var container = document.getElementById( 'buttons-container' );
var buttons = {
"Toggle auto-rotate": function() {
app.spin = !app.spin;
},
"Toggle carving": function() {
app.carve = !app.carve;
app.reset();
},
"Load depth image": function() {
scribbler.clear();
scribbler.loadImage( "js/textures/depth.png" );
},
"Clear canvas": function() {
scribbler.clear();
}
};
for ( var b in buttons ) {
var button = document.createElement( 'button' );
button.innerHTML = b;
button.addEventListener( "click", buttons[b] );
container.appendChild( button );
}
} );
| define( ["app", "scribbler"], function( app, scribbler ) {
var container = document.getElementById( 'buttons-container' );
var buttons = {
"Toggle auto-rotate": function() {
app.spin = !app.spin;
},
"Toggle carving": function() {
app.carve = !app.carve;
app.reset();
},
"Load depth image": function() {
scribbler.clear();
scribbler.loadImage( "/js/textures/depth.png" );
},
"Clear canvas": function() {
scribbler.clear();
}
};
for ( var b in buttons ) {
var button = document.createElement( 'button' );
button.innerHTML = b;
button.addEventListener( "click", buttons[b] );
container.appendChild( button );
}
} );
|
Add attribute for 'contact' in person shortcode | <?php
# Member template for the 'medlem' shortcode function
# The $meta includes member info
# Uses a $content variable if available, otherwise the meta description of the actual member.
$year = $meta['it_year'];
$userdata = get_userdata($id);
$description = ($content != null) ? $content : $meta['description'];
$avatar_size = ($args != null) ? $args['avatar_size'] : 96;
# Shown email may be overriden in the shortcode attribute 'contact'
$user_contact = ($contact != null) ? $contact : $userdata->data->user_email;
?>
<section class="member row">
<figure class="three columns">
<?php echo get_avatar($id, $avatar_size); ?>
</figure>
<div class="member-details nine columns">
<?php if($role) : ?>
<hgroup>
<h2><?php user_fullname($userdata);?></h2>
<h3 class="sub"><?php echo $role;?></h3>
</hgroup>
<?php else : ?>
<h2><?php user_fullname($userdata);?></h2>
<?php endif;?>
<p class="description">
<?php echo strip_tags($description);?>
</p>
<footer>
<?php if($user_contact) : ?>
<strong>Kontakt:</strong> <a href="mailto:<?php echo $user_contact;?>"><?php echo $user_contact;?></a>
<?php endif;?>
</footer>
</div>
</section>
| <?php
# Member template for the 'medlem' shortcode function
# The $meta includes member info
# Uses a $content variable if available, otherwise the meta description of the actual member.
$year = $meta['it_year'];
$description = ($content != null) ? $content : $meta['description'];
$avatar_size = ($args != null) ? $args['avatar_size'] : 96;
?>
<section class="member row">
<figure class="three columns">
<?php echo get_avatar($id, $avatar_size); ?>
</figure>
<div class="member-details nine columns">
<?php if($role) : ?>
<hgroup>
<h2><?php user_fullname(get_userdata($id));?></h2>
<h3 class="sub"><?php echo $role;?></h3>
</hgroup>
<?php else : ?>
<h2><?php user_fullname(get_userdata($id));?></h2>
<?php endif;?>
<p class="description">
<?php echo strip_tags($description);?>
</p>
</div>
</section>
|
test/js: Fix old style causing test to fail. | const encodings = require('encodings'),
asserts = require('test').asserts,
util = require('util');
require.paths.unshift('test/js/lib');
if (!this.exports) this.exports = {};
exports.test_generatorsInMoudles = function() {
var a = require('generator_test').run();
var it = (k for (k in [1,2,3]) );
asserts.same(a.toString(), "[object Generator]", "got a generator");
asserts.same(typeof it.next, typeof a.next, "both generators have a 'next' method");
}
exports.test_utilRange = function() {
var r = require('util').Range(1,10,2);
var a1 = [];
for (let i in r) { a1.push(i) };
asserts.same(a1, [1,3,5,7,9], "Util.Range works");
}
require('test').runner(exports);
| const encodings = require('encodings'),
asserts = require('test').asserts,
util = require('util');
require.paths.unshift('test/js/lib');
if (!this.exports) this.exports = {};
exports.test_generatorsInMoudles = function() {
var a = require('./generator_test').run();
var it = (k for (k in [1,2,3]) );
asserts.same(a.toString(), "[object Generator]", "got a generator");
asserts.same(typeof it.next, typeof a.next, "both generators have a 'next' method");
}
exports.test_utilRange = function() {
var r = Util.Range(1,10,2);
var a1 = [];
for (let i in r) { a1.push(i) };
asserts.same(a1, [1,3,5,7,9], "Util.Range works");
}
require('test').runner(exports);
|
Change the toString value for NOT_APPLICABLE to not 'applicable' | package uk.ac.ebi.quickgo.geneproduct.common;
/**
* An enumeration of the possible states of proteome membership a gene product can have.
* @author Tony Wardell
* Date: 06/03/2018
* Time: 10:33
* Created with IntelliJ IDEA.
*/
public enum ProteomeMembership {
REFERENCE("Reference"),
COMPLETE("Complete"),
NONE("None"),
NOT_APPLICABLE("Not applicable");
private String value;
ProteomeMembership(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
/**
* Define the predicates required and order of importance to work out which Proteome membership category is
* applicable.
* @param isProtein is the gene product a protein
* @param isReferenceProteome is the gene product a reference proteome
* @param isComplete is the gene product a member of a complete proteome.
* @return the String representation of the ProteomeMembership matching the applied constraints
*/
public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {
if (!isProtein) {
return NOT_APPLICABLE.toString();
} else if (isReferenceProteome) {
return REFERENCE.toString();
} else if (isComplete) {
return COMPLETE.toString();
}
return NONE.toString();
}
}
| package uk.ac.ebi.quickgo.geneproduct.common;
/**
* An enumeration of the possible states of proteome membership a gene product can have.
* @author Tony Wardell
* Date: 06/03/2018
* Time: 10:33
* Created with IntelliJ IDEA.
*/
public enum ProteomeMembership {
REFERENCE("Reference"),
COMPLETE("Complete"),
NONE("None"),
NOT_APPLICABLE("Not-applicable");
private String value;
ProteomeMembership(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
/**
* Define the predicates required and order of importance to work out which Proteome membership category is
* applicable.
* @param isProtein is the gene product a protein
* @param isReferenceProteome is the gene product a reference proteome
* @param isComplete is the gene product a member of a complete proteome.
* @return the String representation of the ProteomeMembership matching the applied constraints
*/
public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {
if (!isProtein) {
return NOT_APPLICABLE.toString();
} else if (isReferenceProteome) {
return REFERENCE.toString();
} else if (isComplete) {
return COMPLETE.toString();
}
return NONE.toString();
}
}
|
Remove adding of app to the window on initialization. | var Application = require('application');
module.exports = (function() {
function start() {
document.body.appendChild(document.createElement('gelato-application'));
new Application().start();
}
if (location.protocol === 'file:') {
$.ajax({
url: 'cordova.js',
dataType: 'script'
}).done(function() {
document.addEventListener('deviceready', start, false);
}).fail(function() {
console.error(new Error('Unable to load cordova.js file.'));
});
} else {
$(document).ready(start);
}
})(); | var Application = require('application');
module.exports = (function() {
function prepareDOM() {
document.body.appendChild(document.createElement('gelato-application'));
document.body.appendChild(document.createElement('gelato-dialogs'));
document.body.appendChild(document.createElement('gelato-navbars'));
document.body.appendChild(document.createElement('gelato-sidebars'));
}
function start() {
prepareDOM();
window.app = new Application();
window.app.start();
}
if (location.protocol === 'file:') {
$.ajax({
url: 'cordova.js',
dataType: 'script'
}).done(function() {
document.addEventListener('deviceready', start, false);
}).fail(function() {
console.error(new Error('Unable to load cordova.js file.'));
});
} else {
$(document).ready(start);
}
})(); |
Fix template name for this event | <?php
namespace App\Handlers\Events;
use App\Events\NewUserWasRegistered;
use App\TransMail;
class SendMailUserWelcome
{
private $transmail;
public function __construct(TransMail $transmail)
{
$this->transmail = $transmail;
}
/**
* Handle the event.
*
* @param NewUserWasRegistered $event
*
* @return void
*/
public function handle(NewUserWasRegistered $event)
{
logger()->info('Handle NewUserWasRegistered.SendMailUserWelcome()');
$params = [
'user' => $event->user,
];
$header = [
'name' => $event->user->name,
'email' => $event->user->email,
];
$this->transmail->template('welcome')
->subject('user.welcome.subject')
->send($header, $params);
}
}
| <?php
namespace App\Handlers\Events;
use App\Events\NewUserWasRegistered;
use App\TransMail;
class SendMailUserWelcome
{
private $transmail;
public function __construct(TransMail $transmail)
{
$this->transmail = $transmail;
}
/**
* Handle the event.
*
* @param NewUserWasRegistered $event
*
* @return void
*/
public function handle(NewUserWasRegistered $event)
{
logger()->info('Handle NewUserWasRegistered.SendMailUserWelcome()');
$params = [
'user' => $event->user,
];
$header = [
'name' => $event->user->name,
'email' => $event->user->email,
];
$this->transmail->template('appointments.manager._new')
->subject('user.welcome.subject')
->send($header, $params);
}
}
|
Add is_ignore_case and is_including_href fields to bitfield definition | /**
* Peer
*/
var WordPeer = function ()
{
new DbPeer();
};
WordPeer.prototype = new DbPeer();
WordPeer.getInstance = function ()
{
if (WordPeer.instance) return instance;
var instance = new WordPeer();
instance.tableName = 'word';
instance.addColumn('word_id', DbColumn.TYPE_PKEY, 1.0);
instance.addColumn('rule_id', DbColumn.TYPE_INTEGER, 1.0);
instance.addColumn('word', DbColumn.TYPE_TEXT, 1.0);
instance.addColumn('is_regexp', DbColumn.TYPE_BITFIELD, 1.0,
['is_regexp', 'is_complete_matching','is_ignore_case', 'is_including_href']);
instance.addColumn('insert_date', DbColumn.TYPE_TIMESTAMP, 1.0);
instance.addColumn('update_date', DbColumn.TYPE_TIMESTAMP, 1.0);
instance.addColumn('delete_date', DbColumn.TYPE_TIMESTAMP, 1.0);
WordPeer.instance = instance;
return WordPeer.instance;
}
WordPeer.prototype.createObject = function ()
{
return new Word();
}
/**
* Object
*/
var Word = function()
{
};
Word.prototype.getPeer = function ()
{
return WordPeer.getInstance();
} | /**
* Peer
*/
var WordPeer = function ()
{
new DbPeer();
};
WordPeer.prototype = new DbPeer();
WordPeer.getInstance = function ()
{
if (WordPeer.instance) return instance;
var instance = new WordPeer();
instance.tableName = 'word';
instance.addColumn('word_id', DbColumn.TYPE_PKEY, 1.0);
instance.addColumn('rule_id', DbColumn.TYPE_INTEGER, 1.0);
instance.addColumn('word', DbColumn.TYPE_TEXT, 1.0);
instance.addColumn('is_regexp', DbColumn.TYPE_BITFIELD, 1.0, ['is_regexp', 'is_complete_matching']);
instance.addColumn('insert_date', DbColumn.TYPE_TIMESTAMP, 1.0);
instance.addColumn('update_date', DbColumn.TYPE_TIMESTAMP, 1.0);
instance.addColumn('delete_date', DbColumn.TYPE_TIMESTAMP, 1.0);
WordPeer.instance = instance;
return WordPeer.instance;
}
WordPeer.prototype.createObject = function ()
{
return new Word();
}
/**
* Object
*/
var Word = function()
{
};
Word.prototype.getPeer = function ()
{
return WordPeer.getInstance();
} |
Add appropriately positioned wrapper for Tooltip story | import React from 'react';
import { storiesOf } from '@storybook/react';
import {
boolean, text, select
} from '@storybook/addon-knobs';
import OptionsHelper from '../../../utils/helpers/options-helper';
import Tooltip from '.';
import { notes, info } from './documentation';
function validTooltip({ children, isVisible }) {
return (children && isVisible);
}
const props = () => {
return {
isVisible: boolean('isVisible', true),
children: text('children', "I'm a helpful tooltip that can display more information to a user."),
align: select('align', OptionsHelper.alignAroundEdges, Tooltip.defaultProps.align),
position: select('position', OptionsHelper.positions, Tooltip.defaultProps.position),
type: select('type', ['error', 'warning', 'info'], 'info')
};
};
const content = () => { return validTooltip(props()) ? <Tooltip { ...props() } /> : null; };
storiesOf('Tooltip', module)
.addParameters({
knobs: { escapeHTML: false }
})
.add('default', () => {
return <div style={ { position: 'absolute' } }>{content()}</div>;
},
{
info: { text: info },
notes: { markdown: notes }
});
| import React from 'react';
import { storiesOf } from '@storybook/react';
import {
boolean, text, select
} from '@storybook/addon-knobs';
import OptionsHelper from '../../../utils/helpers/options-helper';
import Tooltip from '.';
import { notes, info } from './documentation';
function validTooltip({ children, isVisible }) {
return (children && isVisible);
}
const props = () => {
return {
isVisible: boolean('isVisible', true),
children: text('children', "I'm a helpful tooltip that can display more information to a user."),
align: select('align', OptionsHelper.alignAroundEdges, Tooltip.defaultProps.align),
position: select('position', OptionsHelper.positions, Tooltip.defaultProps.position),
type: select('type', ['error', 'warning', 'info'], 'info')
};
};
storiesOf('Tooltip', module)
.addParameters({
knobs: { escapeHTML: false }
})
.add('default', () => {
if (validTooltip(props())) return <Tooltip { ...props() } />;
return <div />;
},
{
info: { text: info },
notes: { markdown: notes }
});
|
Refactor - combine pacakges and files into arrays | Package.describe({
name: 'gq:openam',
version: '0.1.0',
summary: 'OpenAM ForgeRock authentication module'
});
Package.onUse(function (api) {
api.versionsFrom('1.2.1');
api.use([
'coffeescript',
'ecmascript'
]);
api.use([
'kadira:flow-router',
'stylus',
'templating',
'mquandalle:jade'
], 'client');
api.use([
'http'
], 'server');
api.addFiles([
'styles/signin.styl',
'views/login.jade',
'views/signup.jade',
'login.coffee',
'signup.coffee',
'routes.coffee'
], 'client');
api.addFiles([
'openam.coffee'
], 'server');
});
| Package.describe({
name: 'gq:openam',
version: '0.1.0',
summary: 'OpenAM ForgeRock authentication module'
});
Package.onUse(function (api) {
api.versionsFrom('1.2.1');
api.use('coffeescript');
api.use('ecmascript');
api.use('kadira:flow-router', 'client');
api.use('stylus', 'client');
api.use('templating', 'client');
api.use('mquandalle:jade', 'client');
api.use('http', 'server');
api.addFiles('styles/signin.styl', 'client');
api.addFiles('views/login.jade', 'client');
api.addFiles('views/signup.jade', 'client');
api.addFiles('login.coffee', 'client');
api.addFiles('signup.coffee', 'client');
api.addFiles('routes.coffee', 'client');
api.addFiles('openam.coffee', 'server');
});
|
Fix other names of packages | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
rack-ddnsm
~~~~~
Dynamic DNS metadata for Rackspace Cloud DNS,
manages TXT records containing metadata in the format of title,desc,data.
:copyright: (c) 2015 by Alex Edwards.
:license: MIT, see LICENSE for more details.
:repo: <https://github.com/sunshinekitty/rack-ddnsm>
:docs: <https://github.com/sunshinekitty/rack-ddnsm/wiki>
"""
from setuptools import setup
import re
with open("rackddnsm/version.py", "rt") as vfile:
version_text = vfile.read()
vmatch = re.search(r'version ?= ?"(.+)"$', version_text)
version = vmatch.groups()[0]
setup(
name="rackddnsm",
version=version,
description="Python language bindings for Encore.",
author="Alex Edwards",
author_email="edwards@linux.com",
url="https://github.com/sunshinekitty/rack-ddnsm>",
keywords="rackspace cloud dns meta ddns dns",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
],
install_requires=[
"requests>=2.2.1",
"dnspython>=1.12.0"
],
packages=[
"rackddnsm",
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
rack-ddnsm
~~~~~
Dynamic DNS metadata for Rackspace Cloud DNS,
manages TXT records containing metadata in the format of title,desc,data.
:copyright: (c) 2015 by Alex Edwards.
:license: MIT, see LICENSE for more details.
:repo: <https://github.com/sunshinekitty/rack-ddnsm>
:docs: <https://github.com/sunshinekitty/rack-ddnsm/wiki>
"""
from setuptools import setup
import re
with open("rackddnsm/version.py", "rt") as vfile:
version_text = vfile.read()
vmatch = re.search(r'version ?= ?"(.+)"$', version_text)
version = vmatch.groups()[0]
setup(
name="rack-ddnsm",
version=version,
description="Python language bindings for Encore.",
author="Alex Edwards",
author_email="edwards@linux.com",
url="https://github.com/sunshinekitty/rack-ddnsm>",
keywords="rackspace cloud dns meta ddns dns",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
],
install_requires=[
"requests>=2.2.1",
"dnspython>=1.12.0"
],
packages=[
"rack-ddnsm",
]
)
|
Use search.rnacentral.org as the sequence search endpoint | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or 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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
| """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or 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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
# SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
|
Add labels to the pub_date__lte pub_date__gte filters | from django.utils.translation import ugettext_lazy as _
from django_filters import FilterSet, DateTimeFilter
from antxetamedia.news.models import NewsPodcast
from antxetamedia.radio.models import RadioPodcast
from antxetamedia.projects.models import ProjectShow
# We do not want to accidentally discard anything, so be inclusive and always
# make gte and lte lookups instead of using gt or lt ones
class NewsPodcastFilterSet(FilterSet):
pub_date_after = DateTimeFilter('pub_date', lookup_type='gte', label=_('Published after'))
pub_date_before = DateTimeFilter('pub_date', lookup_type='lte', label=_('Published before'))
class Meta:
model = NewsPodcast
fields = ['show', 'categories', 'pub_date_after', 'pub_date_before']
class RadioPodcastFilterSet(FilterSet):
pub_date_after = DateTimeFilter('pub_date', lookup_type='gte', label=_('Published after'))
pub_date_before = DateTimeFilter('pub_date', lookup_type='lte', label=_('Published before'))
class Meta:
model = RadioPodcast
fields = ['show', 'show__category', 'show__producer', 'pub_date_after', 'pub_date_before']
class ProjectShowFilterSet(FilterSet):
class Meta:
model = ProjectShow
fields = {
'producer': ['exact'],
'creation_date': ['year__exact'],
}
| from django_filters import FilterSet
from antxetamedia.news.models import NewsPodcast
from antxetamedia.radio.models import RadioPodcast
from antxetamedia.projects.models import ProjectShow
# We do not want to accidentally discard anything, so be inclusive and always
# make gte and lte lookups instead of using gt or lt ones
class NewsPodcastFilterSet(FilterSet):
class Meta:
model = NewsPodcast
fields = {
'show': ['exact'],
'categories': ['exact'],
'pub_date': ['gte', 'lte'],
}
class RadioPodcastFilterSet(FilterSet):
class Meta:
model = RadioPodcast
fields = {
'show': ['exact'],
'show__category': ['exact'],
'show__producer': ['exact'],
'pub_date': ['gte', 'lte'],
}
class ProjectShowFilterSet(FilterSet):
class Meta:
model = ProjectShow
fields = {
'producer': ['exact'],
'creation_date': ['year__exact'],
}
|
Allow limiting of number of query results | <?php
$config = null; // We're doing this here so it can be instantiated once but used everywhere
final class Config
{
const MODE = 'staging'; // options are "development", "staging", "production"
private static $instance;
private function __construct()
{
}
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new Config();
}
return self::$instance;
}
public function getDbSettings()
{
$host = 'MySQLHostStringHere';
$user = 'UserName';
$pass = 'TheSecretPassword';
$database = 'TheDatabaseToUse';
$supportDatabase = 'PVSupport_dev';
return array('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'supportDatabase' => $supportDatabase);
}
public function getMaxPageSize()
{
return 10000;
}
public function getQueryResultLimit()
{
return 100000;
}
} | <?php
$config = null; // We're doing this here so it can be instantiated once but used everywhere
final class Config
{
const MODE = 'staging'; // options are "development", "staging", "production"
private static $instance;
private function __construct()
{
}
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new Config();
}
return self::$instance;
}
public function getDbSettings()
{
$host = 'MySQLHostStringHere';
$user = 'UserName';
$pass = 'TheSecretPassword';
$database = 'TheDatabaseToUse';
$supportDatabase = 'PVSupport_dev';
return array('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'supportDatabase' => $supportDatabase);
}
public function getMaxPageSize()
{
return 10000;
}
} |
Change the development status classifier to beta | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
import plata
setup(name='Plata',
version=plata.__version__,
description='Plata - the lean and mean Django-based Shop',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
author='Matthias Kestenholz',
author_email='mk@feinheit.ch',
url='https://github.com/matthiask/plata/',
license='BSD License',
platforms=['OS Independent'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Application Frameworks',
],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
)
| #!/usr/bin/env python
import os
from setuptools import setup, find_packages
import plata
setup(name='Plata',
version=plata.__version__,
description='Plata - the lean and mean Django-based Shop',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
author='Matthias Kestenholz',
author_email='mk@feinheit.ch',
url='https://github.com/matthiask/plata/',
license='BSD License',
platforms=['OS Independent'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Application Frameworks',
],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
)
|
Revert "Only run switches_and_select and sorttable.makeSortable on /player/"
This reverts commit 3fda189c332319e0aa0a6dea44ec569f2874500a. | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery-ui/autocomplete
//= require autocomplete-rails
//= require bootstrap-sprockets
//= require bootstrap-switch
//= require sorttable
//= require turbolinks
//= require_tree .
Turbolinks.ProgressBar.enable();
$(document).on('ready page:load page:restore', function(event) {
switches_and_select();
sorttable.makeSortable(document.getElementById('player-records'));
})
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery-ui/autocomplete
//= require autocomplete-rails
//= require bootstrap-sprockets
//= require bootstrap-switch
//= require sorttable
//= require turbolinks
//= require_tree .
Turbolinks.ProgressBar.enable();
$(document).on('ready page:load page:restore', function(event) {
if (/player/.test(window.location.href)) {
switches_and_select();
sorttable.makeSortable(document.getElementById('player-records'));
}
});
|
Use assertIsInstance() instead of assertTrue(isinstance()). | import unittest
import appdirs
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertIsInstance(
appdirs.user_data_dir('MyApp', 'MyCompany'), str)
self.assertIsInstance(
appdirs.site_data_dir('MyApp', 'MyCompany'), str)
self.assertIsInstance(
appdirs.user_cache_dir('MyApp', 'MyCompany'), str)
self.assertIsInstance(
appdirs.user_log_dir('MyApp', 'MyCompany'), str)
def test_dirs(self):
dirs = appdirs.AppDirs('MyApp', 'MyCompany', version='1.0')
self.assertIsInstance(dirs.user_data_dir, str)
self.assertIsInstance(dirs.site_data_dir, str)
self.assertIsInstance(dirs.user_cache_dir, str)
self.assertIsInstance(dirs.user_log_dir, str)
if __name__=="__main__":
unittest.main()
| import unittest
import appdirs
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertTrue(isinstance(
appdirs.user_data_dir('MyApp', 'MyCompany'), str))
self.assertTrue(isinstance(
appdirs.site_data_dir('MyApp', 'MyCompany'), str))
self.assertTrue(isinstance(
appdirs.user_cache_dir('MyApp', 'MyCompany'), str))
self.assertTrue(isinstance(
appdirs.user_log_dir('MyApp', 'MyCompany'), str))
def test_dirs(self):
dirs = appdirs.AppDirs('MyApp', 'MyCompany', version='1.0')
self.assertTrue(isinstance(dirs.user_data_dir, str))
self.assertTrue(isinstance(dirs.site_data_dir, str))
self.assertTrue(isinstance(dirs.user_cache_dir, str))
self.assertTrue(isinstance(dirs.user_log_dir, str))
if __name__=="__main__":
unittest.main()
|
Use import_module from standard library if exists
Django 1.8+ drops `django.utils.importlib`. I imagine because that is because an older version of Python (either 2.5 and/or 2.6) is being dropped. I haven't checked older versions but `importlib` exists in Python 2.7. | import sys
def import_attribute(import_path, exception_handler=None):
try:
from importlib import import_module
except ImportError:
from django.utils.importlib import import_module
module_name, object_name = import_path.rsplit('.', 1)
try:
module = import_module(module_name)
except: # pragma: no cover
if callable(exception_handler):
exctype, excvalue, tb = sys.exc_info()
return exception_handler(import_path, exctype, excvalue, tb)
else:
raise
try:
return getattr(module, object_name)
except: # pragma: no cover
if callable(exception_handler):
exctype, excvalue, tb = sys.exc_info()
return exception_handler(import_path, exctype, excvalue, tb)
else:
raise
| import sys
def import_attribute(import_path, exception_handler=None):
from django.utils.importlib import import_module
module_name, object_name = import_path.rsplit('.', 1)
try:
module = import_module(module_name)
except: # pragma: no cover
if callable(exception_handler):
exctype, excvalue, tb = sys.exc_info()
return exception_handler(import_path, exctype, excvalue, tb)
else:
raise
try:
return getattr(module, object_name)
except: # pragma: no cover
if callable(exception_handler):
exctype, excvalue, tb = sys.exc_info()
return exception_handler(import_path, exctype, excvalue, tb)
else:
raise
|
Convert README to Restructured Text for distribution. | """Setuptools file for a MultiMarkdown Python wrapper."""
from codecs import open
from os import path
from distutils.core import setup
from setuptools import find_packages
import pypandoc
here = path.abspath(path.dirname(__file__))
long_description = pypandoc.convert_file('README.md', 'rst')
setup(
name='scriptorium',
version='2.0.1',
description='Multimarkdown and LaTeX framework for academic papers.',
long_description=long_description,
license='MIT',
author='Jason Ziglar',
author_email='jasedit@gmail.com',
url="https://github.com/jasedit/scriptorium",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Text Processing :: Markup',
'Topic :: Text Processing :: Filters',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3'
],
packages=find_packages(),
entry_points = {
'console_scripts': ['scriptorium = scriptorium:main'],
},
package_data={'scriptorium': ['data/gitignore']}
)
| """Setuptools file for a MultiMarkdown Python wrapper."""
from codecs import open
from os import path
from distutils.core import setup
from setuptools import find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='scriptorium',
version='2.0.0',
description='Multimarkdown and LaTeX framework for academic papers.',
long_description=long_description,
license='MIT',
author='Jason Ziglar',
author_email='jasedit@gmail.com',
url="https://github.com/jasedit/scriptorium",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Text Processing :: Markup',
'Topic :: Text Processing :: Filters',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3'
],
packages=find_packages(),
entry_points = {
'console_scripts': ['scriptorium = scriptorium:main'],
},
package_data={'scriptorium': ['data/gitignore']}
)
|
tool-parent: Move progress in toolbar to left | package com.speedment.tool.core.internal.toolbar;
import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.generator.core.event.AfterGenerate;
import com.speedment.generator.core.event.BeforeGenerate;
import com.speedment.generator.core.event.FileGenerated;
import com.speedment.tool.core.toolbar.ToolbarItem;
import com.speedment.tool.core.toolbar.ToolbarSide;
import javafx.scene.control.Label;
import static javafx.application.Platform.runLater;
/**
* Displays the generation progress in the toolbar.
*
* @author Emil Forslund
* @since 3.1.5
*/
public final class GenerationProgressToolbarItem implements ToolbarItem<Label> {
@Inject
private EventComponent events;
@Override
public Label createNode() {
final Label label = new Label("");
events.on(BeforeGenerate.class, bg -> runLater(() -> label.setText("Generating...")));
events.on(FileGenerated.class, fg -> runLater(() -> label.setText(fg.meta().getModel().getName())));
events.on(AfterGenerate.class, ag -> runLater(() -> label.setText("")));
return label;
}
@Override
public ToolbarSide getSide() {
return ToolbarSide.LEFT;
}
}
| package com.speedment.tool.core.internal.toolbar;
import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.generator.core.event.AfterGenerate;
import com.speedment.generator.core.event.BeforeGenerate;
import com.speedment.generator.core.event.FileGenerated;
import com.speedment.tool.core.toolbar.ToolbarItem;
import com.speedment.tool.core.toolbar.ToolbarSide;
import javafx.scene.control.Label;
import static javafx.application.Platform.runLater;
/**
* Displays the generation progress in the toolbar.
*
* @author Emil Forslund
* @since 3.1.5
*/
public final class GenerationProgressToolbarItem implements ToolbarItem<Label> {
@Inject
private EventComponent events;
@Override
public Label createNode() {
final Label label = new Label("");
events.on(BeforeGenerate.class, bg -> runLater(() -> label.setText("Generating...")));
events.on(FileGenerated.class, fg -> runLater(() -> label.setText(fg.meta().getModel().getName())));
events.on(AfterGenerate.class, ag -> runLater(() -> label.setText("")));
return label;
}
@Override
public ToolbarSide getSide() {
return ToolbarSide.RIGHT;
}
}
|
fix: Allow refs on lazy components | import React from 'react'
import { enterHotUpdate } from '../global/generation'
import AppContainer from '../AppContainer.dev'
import { resolveType } from './resolver'
const lazyConstructor = '_ctor'
export const updateLazy = (target, type) => {
const ctor = type[lazyConstructor]
if (target[lazyConstructor] !== type[lazyConstructor]) {
// just execute `import` and RHL.register will do the job
ctor()
}
if (!target[lazyConstructor].isPatchedByReactHotLoader) {
target[lazyConstructor] = () =>
ctor().then(m => {
const C = resolveType(m.default)
// chunks has been updated - new hot loader process is taking a place
enterHotUpdate()
return {
default: React.forwardRef((props, ref) => (
<AppContainer>
<C {...props} ref={ref} />
</AppContainer>
)),
}
})
target[lazyConstructor].isPatchedByReactHotLoader = true
}
}
export const updateMemo = (target, { type }) => {
target.type = resolveType(type)
}
export const updateForward = (target, { render }) => {
target.render = render
}
export const updateContext = () => {
// nil
}
| import React from 'react'
import { enterHotUpdate } from '../global/generation'
import AppContainer from '../AppContainer.dev'
import { resolveType } from './resolver'
const lazyConstructor = '_ctor'
export const updateLazy = (target, type) => {
const ctor = type[lazyConstructor]
if (target[lazyConstructor] !== type[lazyConstructor]) {
// just execute `import` and RHL.register will do the job
ctor()
}
if (!target[lazyConstructor].isPatchedByReactHotLoader) {
target[lazyConstructor] = () =>
ctor().then(m => {
const C = resolveType(m.default)
// chunks has been updated - new hot loader process is taking a place
enterHotUpdate()
return {
default: props => (
<AppContainer>
<C {...props} />
</AppContainer>
),
}
})
target[lazyConstructor].isPatchedByReactHotLoader = true
}
}
export const updateMemo = (target, { type }) => {
target.type = resolveType(type)
}
export const updateForward = (target, { render }) => {
target.render = render
}
export const updateContext = () => {
// nil
}
|
Disable dartc diet parser test
Reviewed here: http://codereview.chromium.org/10696100/
Review URL: https://chromiumcodereview.appspot.com//10692081
git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@9380 260f80e4-7a28-3924-810f-c04153c831b5 | // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.google.dart.compiler.parser;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
public class ParserTests extends TestSetup {
public ParserTests(TestSuite test) {
super(test);
}
public static Test suite() {
TestSuite suite = new TestSuite("Dart parser test suite.");
suite.addTestSuite(SyntaxTest.class);
//diet-parsing is used only for incremental compilation which is turned off
//(and this test causes intermittent timeouts)
//suite.addTestSuite(DietParserTest.class);
suite.addTestSuite(CPParserTest.class);
suite.addTestSuite(ParserRoundTripTest.class);
suite.addTestSuite(LibraryParserTest.class);
suite.addTestSuite(NegativeParserTest.class);
suite.addTestSuite(ValidatingSyntaxTest.class);
suite.addTestSuite(CommentTest.class);
suite.addTestSuite(ErrorMessageLocationTest.class);
suite.addTestSuite(ParserEventsTest.class);
suite.addTestSuite(TruncatedSourceParserTest.class);
suite.addTestSuite(ParserRecoveryTest.class);
return new ParserTests(suite);
}
}
| // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.google.dart.compiler.parser;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
public class ParserTests extends TestSetup {
public ParserTests(TestSuite test) {
super(test);
}
public static Test suite() {
TestSuite suite = new TestSuite("Dart parser test suite.");
suite.addTestSuite(SyntaxTest.class);
suite.addTestSuite(DietParserTest.class);
suite.addTestSuite(CPParserTest.class);
suite.addTestSuite(ParserRoundTripTest.class);
suite.addTestSuite(LibraryParserTest.class);
suite.addTestSuite(NegativeParserTest.class);
suite.addTestSuite(ValidatingSyntaxTest.class);
suite.addTestSuite(CommentTest.class);
suite.addTestSuite(ErrorMessageLocationTest.class);
suite.addTestSuite(ParserEventsTest.class);
suite.addTestSuite(TruncatedSourceParserTest.class);
suite.addTestSuite(ParserRecoveryTest.class);
return new ParserTests(suite);
}
}
|
TEST moving rank outside loop | <div class="container">
<div class="row">
<div class="col-lg-12">
<ul class="nav nav-pills">
<li class="active"><a href="#">Top 10</a></li>
<li><a href="#">Top 50</a></li>
<li><a href="#">Top 100 </a></li>
</ul>
</div>
</div>
<?php
$rank = 1;
include 'includes/sqllogin.php';
$result = mysqli_query($con,"SELECT * FROM `Top Player` ORDER BY Distance DESC LIMIT 10");
echo "<table class='table table-striped'>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Distance</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $rank++ . "</td>";
echo "<td>" . $row['PlayerName'] . "</td>";
echo "<td>" . $row['Distance'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<hr>
</div>
<!-- /.container --> | <div class="container">
<div class="row">
<div class="col-lg-12">
<ul class="nav nav-pills">
<li class="active"><a href="#">Top 10</a></li>
<li><a href="#">Top 50</a></li>
<li><a href="#">Top 100 </a></li>
</ul>
</div>
</div>
<?php
include 'includes/sqllogin.php';
$result = mysqli_query($con,"SELECT * FROM `Top Player` ORDER BY Distance DESC LIMIT 10");
echo "<table class='table table-striped'>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Distance</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$rank = 1;
echo "<tr>";
echo "<td>" . $rank++ . "</td>";
echo "<td>" . $row['PlayerName'] . "</td>";
echo "<td>" . $row['Distance'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<hr>
</div>
<!-- /.container --> |
Set it to consume rewards | import json
import httplib2
from config import SERVER
http = httplib2.Http()
# print json.loads(http.request("http://172.28.101.30:8080/api/v1/family/1/?format=json", 'GET')[1])
def json_result(url, method='GET'):
response = http.request('http://%s%s?format=json' % (SERVER, url), method)[1]
# print 'URL', url
# print 'RESP', json.loads(response)
if response:
return json.loads(http.request('http://%s%s?format=json' % (SERVER, url), method)[1])
else:
return {}
def poll():
family = json_result('/api/v1/family/1/')
members = []
for m in family[u'members']:
member = json_result(m)
rewards = filter(lambda r: not r[u'consumed'],
[json_result(r) for r in member[u'rewards']])
for r in rewards:
json_result(r[u'resource_uri'] + 'consume/')
pass
# List of triplets (first name, username, list of rewards to consume)
members.append((member[u'first_name'], member[u'username'], rewards))
return members
# print poll()
| import json
import httplib2
from config import SERVER
http = httplib2.Http()
# print json.loads(http.request("http://172.28.101.30:8080/api/v1/family/1/?format=json", 'GET')[1])
def json_result(url, method='GET'):
response = http.request('http://%s%s?format=json' % (SERVER, url), method)[1]
# print 'URL', url
# print 'RESP', json.loads(response)
if response:
return json.loads(http.request('http://%s%s?format=json' % (SERVER, url), method)[1])
else:
return {}
def poll():
family = json_result('/api/v1/family/1/')
members = []
for m in family[u'members']:
member = json_result(m)
rewards = filter(lambda r: not r[u'consumed'],
[json_result(r) for r in member[u'rewards']])
for r in rewards:
# json_result(r[u'resource_uri'] + 'consume/')
pass
# List of triplets (first name, username, list of rewards to consume)
members.append((member[u'first_name'], member[u'username'], rewards))
return members
# print poll()
|
fix: Correct name of event header | const winston = require('winston');
const env = require('./env');
const GITLAB_TOKEN = env.GITLAB_TOKEN || Math.random(); // Seriously, you must have it set
const GITLAB_EVENT_NAME = 'Merge Request Hook';
module.exports = {
/**
* Middleware for processing Gitlab Merge Hook
*
* @param {object} req - Contains request information from express
* @param {object} res - Express object with interface for communicating back
* to client user
* @return {undefined} Should not be consumed
*/
gitlab: function(req, res, next) {
if (req.headers['x-gitlab-token'] !== GITLAB_TOKEN) {
winston.error(new Error('Token does not match team\'s '));
return res.sendStatus(500);
}
if (req.headers['x-gitlab-event'] !== GITLAB_EVENT_NAME) {
winston.error(new Error('Missing or invalid X-Gitlab-Event header'));
return res.sendStatus(500);
}
next();
}
};
| const winston = require('winston');
const env = require('./env');
const GITLAB_TOKEN = env.GITLAB_TOKEN || Math.random(); // Seriously, you must have it set
const GITLAB_EVENT_NAME = 'Push Hook';
module.exports = {
/**
* Middleware for processing Gitlab Merge Hook
*
* @param {object} req - Contains request information from express
* @param {object} res - Express object with interface for communicating back
* to client user
* @return {undefined} Should not be consumed
*/
gitlab: function(req, res, next) {
if (req.headers['x-gitlab-token'] !== GITLAB_TOKEN) {
winston.error(new Error('Token does not match team\'s '));
return res.sendStatus(500);
}
if (req.headers['x-gitlab-event'] !== GITLAB_EVENT_NAME) {
winston.error(new Error('Missing or invalid X-Gitlab-Event header'));
return res.sendStatus(500);
}
next();
}
};
|
Add test for concat template tag | from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
class ConcatTestCase(TestCase):
def test_concat(self):
expected = 'foo-bar'
assert explorer.concat('foo-', 'bar') == expected
| from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
|
build: Initialize algolia settings in script | import algolia from 'algoliasearch';
import icons from '../dist/icons.json';
import tags from '../src/tags.json';
const ALGOLIA_APP_ID = '5EEOG744D0';
if (
process.env.TRAVIS_PULL_REQUEST === 'false' &&
process.env.TRAVIS_BRANCH === 'master'
) {
syncAlgolia();
} else {
console.log('Skipped Algolia sync.');
}
function syncAlgolia() {
// ALGOLIA_ADMIN_KEY must be added as an environment variable in Travis CI
const client = algolia(ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_KEY);
console.log('Initializing target and temporary indexes...');
const index = client.initIndex('icons');
const indexTmp = client.initIndex('icons_tmp');
index.setSettings({
searchableAttributes: ['unordered(name)', 'unordered(tags)'],
customRanking: ['asc(name)'],
});
console.log('Copying target index settings into temporary index...');
client.copyIndex(index.indexName, indexTmp.indexName, ['settings'], err => {
if (err) throw err;
});
const records = Object.keys(icons).map(name => ({
name,
tags: tags[name] || [],
}));
console.log('Pushing data to the temporary index...');
indexTmp.addObjects(records, err => {
if (err) throw err;
});
console.log('Moving temporary index to target index...');
client.moveIndex(indexTmp.indexName, index.indexName, err => {
if (err) throw err;
});
}
| import algolia from 'algoliasearch';
import icons from '../dist/icons.json';
import tags from '../src/tags.json';
const ALGOLIA_APP_ID = '5EEOG744D0';
if (
process.env.TRAVIS_PULL_REQUEST === 'false' &&
process.env.TRAVIS_BRANCH === 'master'
) {
syncAlgolia();
} else {
console.log('Skipped Algolia sync.');
}
function syncAlgolia() {
// ALGOLIA_ADMIN_KEY must be added as an environment variable in Travis CI
const client = algolia(ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_KEY);
console.log('Initializing target and temporary indexes...');
const index = client.initIndex('icons');
const indexTmp = client.initIndex('icons_tmp');
console.log('Copying target index settings into temporary index...');
client.copyIndex(index.indexName, indexTmp.indexName, ['settings'], err => {
if (err) throw err;
});
const records = Object.keys(icons).map(name => ({
name,
tags: tags[name] || [],
}));
console.log('Pushing data to the temporary index...');
indexTmp.addObjects(records, err => {
if (err) throw err;
});
console.log('Moving temporary index to target index...');
client.moveIndex(indexTmp.indexName, index.indexName, err => {
if (err) throw err;
});
}
|
Fix accessors to pass unit tests | package com.grayben.riskExtractor.headingMarker.elector;
import java.util.List;
import com.grayben.riskExtractor.headingMarker.TextCandidate;
import com.grayben.riskExtractor.headingMarker.nominator.NomineesRetrievable;
public class ElectedTextList implements
NomineesRetrievable,
ElecteesRetrievable {
List<String> textList;
public List<String> getTextList() {
return textList;
}
public void setTextList(List<String> textList) {
this.textList = textList;
}
List<TextCandidate> nominees;
@Override
public List<TextCandidate> getNominees() {
// TODO Auto-generated method stub
return this.nominees;
}
public void setNominees(List<TextCandidate> nominees) {
this.nominees = nominees;
}
List<TextCandidate> electees;
@Override
public List<TextCandidate> getElectees() {
// TODO Auto-generated method stub
return this.electees;
}
public void setElectees(List<TextCandidate> electees) {
this.electees = electees;
}
public ElectedTextList(List<String> textList, List<TextCandidate> nominees, List<TextCandidate> electees){
super();
this.textList = textList;
this.nominees = nominees;
this.electees = electees;
}
}
| package com.grayben.riskExtractor.headingMarker.elector;
import java.util.List;
import com.grayben.riskExtractor.headingMarker.TextCandidate;
import com.grayben.riskExtractor.headingMarker.nominator.NomineesRetrievable;
public class ElectedTextList implements
NomineesRetrievable,
ElecteesRetrievable {
List<String> textList;
public List<String> getTextList() {
return textList;
}
public void setTextList(List<String> textList) {
this.textList = textList;
}
List<TextCandidate> nominees;
@Override
public List<TextCandidate> getNominees() {
// TODO Auto-generated method stub
return null;
}
public void setNominees(List<TextCandidate> nominees) {
this.nominees = nominees;
}
List<TextCandidate> electees;
@Override
public List<TextCandidate> getElectees() {
// TODO Auto-generated method stub
return null;
}
public void setElectees(List<TextCandidate> electees) {
this.electees = electees;
}
public ElectedTextList(List<String> textList, List<TextCandidate> nominees, List<TextCandidate> electees){
super();
this.textList = textList;
this.nominees = nominees;
this.electees = electees;
}
}
|
Change occurrence of addressbook to emeraldo | package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.emeraldo.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Emeraldo\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/addressbook.xml\n" +
"Emeraldo name : MyTaskManager";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
| package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.emeraldo.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Emeraldo\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/addressbook.xml\n" +
"AddressBook name : MyAddressBook";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
Fix env variable names in unit test
Signed-off-by: Max Ehrlich <c7cd0513ef0c504f678ca33c2b168f4f84cd4d51@gmail.com> | package acmedns
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
var (
acmednsLiveTest bool
acmednsHost string
acmednsAccountsJson []byte
acmednsDomain string
)
func init() {
acmednsHost = os.Getenv("ACME_DNS_HOST")
acmednsAccountsJson = []byte(os.Getenv("ACME_DNS_ACCOUNT_JSON"))
if len(acmednsHost) > 0 && len(acmednsAccountsJson) > 0 {
acmednsLiveTest = true
}
}
func TestLiveAzureDnsPresent(t *testing.T) {
if !acmednsLiveTest {
t.Skip("skipping live test")
}
provider, err := NewDNSProviderHostBytes(acmednsHost, acmednsAccountsJson)
assert.NoError(t, err)
err = provider.Present(acmednsDomain, "", "123d==")
assert.NoError(t, err)
}
| package acmedns
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
var (
acmednsLiveTest bool
acmednsHost string
acmednsAccountsJson []byte
acmednsDomain string
)
func init() {
acmednsHost = os.Getenv("")
acmednsAccountsJson = []byte(os.Getenv("AZURE_CLIENT_SECRET"))
if len(acmednsHost) > 0 && len(acmednsAccountsJson) > 0 {
acmednsLiveTest = true
}
}
func TestLiveAzureDnsPresent(t *testing.T) {
if !acmednsLiveTest {
t.Skip("skipping live test")
}
provider, err := NewDNSProviderHostBytes(acmednsHost, acmednsAccountsJson)
assert.NoError(t, err)
err = provider.Present(acmednsDomain, "", "123d==")
assert.NoError(t, err)
}
|
Remove double slash from path
The slash after content caused a double slash in the resulting path, standalone could not be loaded in a simple Android WebView app. See detailed error description here: https://h5p.org/node/104774
Thanks for providing! | H5P.getLibraryPath = function (library) {
return H5PIntegration.url + '/' + library.split('-')[0];
};
H5P.getPath = function (path, contentId) {
var hasProtocol = function (path) {
return path.match(/^[a-z0-9]+:\/\//i);
};
if (hasProtocol(path)) {
return path;
}
var prefix;
if (contentId !== undefined) {
prefix = H5PIntegration.url + '/content';
}
else if (window.H5PEditor !== undefined) {
prefix = H5PEditor.filesPath;
}
else {
return;
}
// if (!hasProtocol(prefix)) {
// // Use absolute urls
// prefix = window.location.protocol + "//" + window.location.host + prefix;
// }
return prefix + '/' + path;
};
| H5P.getLibraryPath = function (library) {
return H5PIntegration.url + '/' + library.split('-')[0];
};
H5P.getPath = function (path, contentId) {
var hasProtocol = function (path) {
return path.match(/^[a-z0-9]+:\/\//i);
};
if (hasProtocol(path)) {
return path;
}
var prefix;
if (contentId !== undefined) {
prefix = H5PIntegration.url + '/content/';
}
else if (window.H5PEditor !== undefined) {
prefix = H5PEditor.filesPath;
}
else {
return;
}
// if (!hasProtocol(prefix)) {
// // Use absolute urls
// prefix = window.location.protocol + "//" + window.location.host + prefix;
// }
return prefix + '/' + path;
};
|
Adjust for changes made by PAXWICKET-399 | /**
* Copyright OPS4J
*
* 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 org.ops4j.pax.wicket.samples.blueprint.filter.internal;
import javax.servlet.Filter;
import org.ops4j.pax.wicket.api.ConfigurableFilterConfig;
import org.ops4j.pax.wicket.api.FilterFactory;
public class SampleFilterFactory implements FilterFactory {
public Integer getPriority() {
return 1;
}
public String getApplicationName() {
return "blueprint.filter.paxwicket";
}
public Filter createFilter(ConfigurableFilterConfig filterConfig) {
return new IAmASysoutFilter();
}
}
| /**
* Copyright OPS4J
*
* 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 org.ops4j.pax.wicket.samples.blueprint.filter.internal;
import javax.servlet.Filter;
import org.ops4j.pax.wicket.api.ConfigurableFilterConfig;
import org.ops4j.pax.wicket.api.FilterFactory;
public class SampleFilterFactory implements FilterFactory {
public int compareTo(FilterFactory o) {
if (o.getPriority() < 1) {
return 1;
}
if (o.getPriority() > 1) {
return -1;
}
return 0;
}
public Integer getPriority() {
return 1;
}
public String getApplicationName() {
return "blueprint.filter.paxwicket";
}
public Filter createFilter(ConfigurableFilterConfig filterConfig) {
return new IAmASysoutFilter();
}
}
|
Allow to call extensin with click on icon. | (function(self) {
'use strict';
const optionsUrl = chrome.extension.getURL('index.html');
const createOrSelectTab = function(url) {
chrome.tabs.query({ url: url }, function(tabs) {
if (tabs.length) {
chrome.tabs.update(tabs[0].id, { active: true });
} else {
chrome.tabs.create({ url: url });
}
});
};
chrome.commands.onCommand.addListener(function(command) {
createOrSelectTab(optionsUrl);
});
chrome.browserAction.onClicked.addListener(function(tab) {
createOrSelectTab(optionsUrl);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === 'open_tab') {
createOrSelectTab(request.url);
}
});
})(this);
| (function(self) {
'use strict';
const optionsUrl = chrome.extension.getURL('index.html');
const createOrSelectTab = function(url) {
chrome.tabs.query({ url: url }, function(tabs) {
if (tabs.length) {
chrome.tabs.update(tabs[0].id, { active: true });
} else {
chrome.tabs.create({ url: url });
}
});
};
chrome.commands.onCommand.addListener(function(command) {
createOrSelectTab(optionsUrl);
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === 'open_tab') {
createOrSelectTab(request.url);
}
});
})(this);
|
Update httplib2 version, bump version, fix formatting | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
required = ['oauth2', 'httplib2==0.9.1', 'python-dateutil']
setup(
name='readability-api',
version='0.2.6',
description='Python wrapper for the Readability API.',
long_description=open('README.rst').read(),
author='The Readability Team',
author_email='feedback@readability.com',
url='https://www.readability.com/publishers/api',
packages=['readability'],
install_requires=required,
license='MIT',
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
# 'Programming Language :: Python :: 3.0',
# 'Programming Language :: Python :: 3.1',
# 'Programming Language :: Python :: 3.2',
),
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
required = ['oauth2', 'httplib2==0.8.0', 'python-dateutil']
setup(
name='readability-api',
version='0.2.5',
description='Python wrapper for the Readability API.',
long_description=open('README.rst').read(),
author='The Readability Team',
author_email='feedback@readability.com',
url='https://www.readability.com/publishers/api',
packages= ['readability'],
install_requires=required,
license='MIT',
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
# 'Programming Language :: Python :: 3.0',
# 'Programming Language :: Python :: 3.1',
# 'Programming Language :: Python :: 3.2',
),
)
|
Fix support for specifying module-dir | #!/usr/bin/env node
var program = require('commander'),
cjs = require(__dirname + '/../lib/');
program
.version(require(__dirname + '/../package.json').version)
.option('-i, --input <file>', 'input file (required)')
.option('-o, --output <file>', 'output file (defaults to <input>.out.js)')
.option('-x, --extension <ext>', 'default extension for requires (defaults to "js")')
.option('-m, --map [file]', 'file to store source map to (optional)')
.option('-c, --comments', 'preserve comments in output')
.option('-e, --exports <id>', 'top module exports destination (optional)')
.option('-d, --module-dir <dir>', 'top level location to search for external modules (optional)')
.option('-s, --external [hash]', 'external modules (names or JSON hashes)', function (value, obj) {
try {
var add = JSON.parse(value);
for (var name in add) {
obj[name] = add[name];
}
} catch (e) {
obj[value] = true;
}
return obj;
}, {})
.parse(process.argv);
if (!program.input) {
program.help();
}
console.log('Building...');
cjs.transform(program).then(function (result) {
console.log('Built to:', result.options.output);
}, function (error) {
console.error(error.stack);
});
| #!/usr/bin/env node
var program = require('commander'),
cjs = require(__dirname + '/../lib/');
program
.version(require(__dirname + '/../package.json').version)
.option('-i, --input <file>', 'input file (required)')
.option('-o, --output <file>', 'output file (defaults to <input>.out.js)')
.option('-x, --extension <ext>', 'default extension for requires (defaults to "js")')
.option('-m, --map [file]', 'file to store source map to (optional)')
.option('-c, --comments', 'preserve comments in output')
.option('-e, --exports <id>', 'top module exports destination (optional)')
.option('-s, --external [hash]', 'external modules (names or JSON hashes)', function (value, obj) {
try {
var add = JSON.parse(value);
for (var name in add) {
obj[name] = add[name];
}
} catch (e) {
obj[value] = true;
}
return obj;
}, {})
.parse(process.argv);
if (!program.input) {
program.help();
}
console.log('Building...');
cjs.transform(program).then(function (result) {
console.log('Built to:', result.options.output);
}, function (error) {
console.error(error.stack);
});
|
Make replace task class name dynamic, move imports | package de.thetaphi.forbiddenapis;
/*
* (C) Copyright Uwe Schindler (Generics Policeman) and others.
* Parts of this work are licensed to the Apache Software Foundation (ASF)
* under one or more contributor license agreements.
*
* 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.
*/
import java.util.Locale;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
/**
* {@inheritDoc}
* @deprecated Use {@link de.thetaphi.forbiddenapis.ant.AntTask} instead.
*/
@Deprecated
public final class AntTask extends de.thetaphi.forbiddenapis.ant.AntTask {
@Override
public void execute() throws BuildException {
log(String.format(Locale.ENGLISH, "DEPRECATED-WARNING: Please change your build.xml to use new task class '%s'",
getClass().getSuperclass().getName()), Project.MSG_WARN);
super.execute();
}
}
| package de.thetaphi.forbiddenapis;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
/*
* (C) Copyright Uwe Schindler (Generics Policeman) and others.
* Parts of this work are licensed to the Apache Software Foundation (ASF)
* under one or more contributor license agreements.
*
* 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.
*/
/**
* {@inheritDoc}
* @deprecated Use {@link de.thetaphi.forbiddenapis.ant.AntTask} instead.
*/
@Deprecated
public final class AntTask extends de.thetaphi.forbiddenapis.ant.AntTask {
@Override
public void execute() throws BuildException {
log("DEPRECATED-WARNING: Please change your build.xml to use new task class de.thetaphi.forbiddenapis.ant.AntTask", Project.MSG_WARN);
super.execute();
}
}
|
Use dots reporter for travis. | var files = require('../files');
module.exports = {
options: {
frameworks: [
'jasmine'
],
files: files.testEnvKarma.concat([files.unitTests])
},
all: {
options: {
browsers: ['PhantomJS', 'Chrome', 'Firefox'],
singleRun: true
}
},
headless: {
options: {
browsers: ['PhantomJS'],
singleRun: true
}
},
travis: {
options: {
browsers: ['PhantomJS', 'Firefox'],
reporters: ['dots'],
singleRun: true
}
},
watch: {
options: {
browsers: ['Chrome'],
background: true
}
}
};
| var files = require('../files');
module.exports = {
options: {
frameworks: [
'jasmine'
],
files: files.testEnvKarma.concat([files.unitTests])
},
all: {
options: {
browsers: ['PhantomJS', 'Chrome', 'Firefox'],
singleRun: true
}
},
headless: {
options: {
browsers: ['PhantomJS'],
singleRun: true
}
},
travis: {
options: {
browsers: ['PhantomJS', 'Firefox'],
singleRun: true
}
},
watch: {
options: {
browsers: ['Chrome'],
background: true
}
}
};
|
WebRTC: Make clean script return successful if clean dir is missing.
I thought it would be good to have the script fail for an
incorrectly specified directory, but the out/ dir is missing
on fresh installed slave machines, so better just skip cleaning
with a line printed to stdout instead when the dir is missing.
TESTED=Ran the script locally with an invalid dir argument.
Review URL: https://codereview.chromium.org/921633005
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@294057 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright 2015 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.
"""Script that deletes all files (but not directories) in a given directory."""
import os
import sys
def main(args):
if not args or len(args) != 1:
print >> sys.stderr, 'Please specify a single directory as an argument.'
return 1
clean_dir = args[0]
if not os.path.isdir(clean_dir):
print 'Cannot find any directory at %s. Skipping cleaning.' % clean_dir
return 0
for filename in os.listdir(clean_dir):
file_path = os.path.join(clean_dir, filename)
if os.path.isfile(file_path):
try:
os.remove(file_path)
print 'Removed %s' % file_path
except OSError as e:
# Don't fail if we cannot delete a file.
print e
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| #!/usr/bin/env python
# Copyright 2015 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.
"""Script that deletes all files (but not directories) in a given directory."""
import os
import sys
def main(args):
if not args or len(args) != 1:
print >> sys.stderr, 'Please specify a single directory as an argument.'
return 1
clean_dir = args[0]
if not os.path.isdir(clean_dir):
print >> sys.stderr, '%s does not exist or is not a directory!' % clean_dir
return 2
for filename in os.listdir(clean_dir):
file_path = os.path.join(clean_dir, filename)
if os.path.isfile(file_path):
try:
os.remove(file_path)
print 'Removed %s' % file_path
except OSError as e:
# Don't fail if we cannot delete a file.
print e
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
Replace ember-mobiletouch (deprecated) with ember-gestures (recommended replacement) | var path = require('path');
var chalk = require('chalk');
var Promise = require('../../lib/ext/promise');
var stringUtils = require('../../lib/utils/string');
var runCommand = require('../../lib/utils/run-command');
module.exports = {
// Allows the generator to not require an entity name
normalizeEntityName: function(entityName) {
return entityName;
},
locals: function(options) {
var name = options.project.pkg.name;
return {
namespace: stringUtils.classify(name),
modulePrefix: stringUtils.dasherize(name)
}
},
addPluginToProject: function(name) {
var ui = this.ui;
return runCommand('cordova plugin add ' + name, null, {
cwd: path.join(this.project.root, 'cordova')
})().then(function() {
if (ui) {
ui.writeLine(' ' + chalk.green('install plugin') + ' ' + name);
}
});
},
afterInstall: function() {
return Promise.all([
this.addPackageToProject('broccoli-sass'),
this.addPackageToProject('liquid-fire'),
this.addPackageToProject('ember-gestures')
]);
}
};
| var path = require('path');
var chalk = require('chalk');
var Promise = require('../../lib/ext/promise');
var stringUtils = require('../../lib/utils/string');
var runCommand = require('../../lib/utils/run-command');
module.exports = {
// Allows the generator to not require an entity name
normalizeEntityName: function(entityName) {
return entityName;
},
locals: function(options) {
var name = options.project.pkg.name;
return {
namespace: stringUtils.classify(name),
modulePrefix: stringUtils.dasherize(name)
}
},
addPluginToProject: function(name) {
var ui = this.ui;
return runCommand('cordova plugin add ' + name, null, {
cwd: path.join(this.project.root, 'cordova')
})().then(function() {
if (ui) {
ui.writeLine(' ' + chalk.green('install plugin') + ' ' + name);
}
});
},
afterInstall: function() {
return Promise.all([
this.addPackageToProject('broccoli-sass'),
this.addPackageToProject('liquid-fire'),
this.addPackageToProject('ember-mobiletouch')
]);
}
};
|
Fix style text hiding on ThemeScreen | import { StyleSheet } from 'react-native'
import { Colors, ApplicationStyles } from '../../Themes/'
export default StyleSheet.create({
...ApplicationStyles.screen,
groupContainer: {
...ApplicationStyles.groupContainer
},
sectionHeaderContainer: {
...ApplicationStyles.darkLabelContainer
},
sectionHeader: {
...ApplicationStyles.darkLabel
},
colorsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center'
},
backgroundContainer: {
position: 'relative',
width: 102,
height: 102,
borderWidth: 1,
borderColor: Colors.frost
},
backerImage: {
top: 0,
bottom: 0,
left: 0,
right: 0,
position: 'absolute',
resizeMode: 'stretch'
},
colorContainer: {
height: 130,
padding: 5,
marginBottom: 5
},
colorSquare: {
width: 100,
height: 100
},
colorName: {
width: 100,
height: 20,
lineHeight: 20,
color: Colors.charcoal,
textAlign: 'center'
},
fontRow: {
padding: 5,
marginHorizontal: 5,
color: Colors.snow
}
})
| import { StyleSheet } from 'react-native'
import { Colors, ApplicationStyles } from '../../Themes/'
export default StyleSheet.create({
...ApplicationStyles.screen,
groupContainer: {
...ApplicationStyles.groupContainer
},
sectionHeaderContainer: {
...ApplicationStyles.darkLabelContainer
},
sectionHeader: {
...ApplicationStyles.darkLabel
},
colorsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center'
},
backgroundContainer: {
position: 'relative',
width: 102,
height: 102,
borderWidth: 1,
borderColor: Colors.frost
},
backerImage: {
top: 0,
bottom: 0,
left: 0,
right: 0,
position: 'absolute',
resizeMode: 'stretch'
},
colorContainer: {
height: 130,
padding: 5,
marginBottom: 5
},
colorSquare: {
width: 100,
height: 100
},
colorName: {
width: 100,
height: 20,
lineHeight: 20,
color: Colors.charcoal,
textAlign: 'center'
},
fontRow: {
padding: 5,
fontSize: 24,
marginHorizontal: 5,
flex: 1,
color: Colors.snow
}
})
|
Add url / author email for PyPI regs | import tungsten
from distutils.core import setup
setup(
name='Tungsten',
version=tungsten.__version__,
author='Seena Burns',
author_email='hello@ethanbird.com',
url='https://github.com/seenaburns/Tungsten',
packages={'tungsten': 'tungsten'},
license=open('LICENSE.txt').read(),
description='Wolfram Alpha API built for Python.',
long_description=open('README.md').read(),
install_requires=[
"requests",
],
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
),
)
| import tungsten
from distutils.core import setup
setup(
name='Tungsten',
version=tungsten.__version__,
author='Seena Burns',
packages={'tungsten': 'tungsten'},
license=open('LICENSE.txt').read(),
description='Wolfram Alpha API built for Python.',
long_description=open('README.md').read(),
install_requires=[
"requests",
],
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
),
)
|
Add option to sort by term in descending order | // ==UserScript==
// @name All Courses Sort
// @namespace https://github.com/jamesjonesmath/canvancement
// @description Allows sorting on any column of the All Courses list
// @include https://*.instructure.com/courses
// @require https://cdn.jsdelivr.net/npm/tablesorter@2.31.1/dist/js/jquery.tablesorter.combined.min.js
// @version 1
// @grant none
// ==/UserScript==
(function() {
'use strict';
if (/^\/courses\/?$/.test(window.location.pathname)) {
const head = document.querySelector('head');
if (head) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'https://cdn.jsdelivr.net/npm/tablesorter@2.31.1/dist/css/theme.default.min.css';
head.appendChild(link);
}
document.querySelectorAll('table.ic-Table th.course-list-star-column').forEach(function(e) {
e.classList.add('filter-false');
});
$('table.ic-Table').tablesorter({
'widgets' : [ 'filter' ],
// 'sortList' : [[3,1]]
});
}
})();
| // ==UserScript==
// @name All Courses Sort
// @namespace https://github.com/jamesjonesmath/canvancement
// @description Allows sorting on any column of the All Courses list
// @include https://*.instructure.com/courses
// @require https://cdn.jsdelivr.net/npm/tablesorter@2.31.1/dist/js/jquery.tablesorter.combined.min.js
// @version 1
// @grant none
// ==/UserScript==
(function() {
'use strict';
if (/^\/courses\/?$/.test(window.location.pathname)) {
const head = document.querySelector('head');
if (head) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'https://cdn.jsdelivr.net/npm/tablesorter@2.31.1/dist/css/theme.default.min.css';
head.appendChild(link);
}
document.querySelectorAll('table.ic-Table th.course-list-star-column').forEach(function(e) {
e.classList.add('filter-false');
});
$('table.ic-Table').tablesorter({
'widgets' : [ 'filter' ]
});
}
})();
|
Python: Add iterable-unpacking in for test | # Add taintlib to PATH so it can be imported during runtime without any hassle
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__))))
from taintlib import *
# This has no runtime impact, but allows autocomplete to work
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..taintlib import *
# Actual tests
def test_access():
tainted_list = TAINTED_LIST
ensure_tainted(
tainted_list.copy(), # $ tainted
)
for ((x, y, *z), a, b) in tainted_list:
ensure_tainted(
x, # $ tainted
y, # $ tainted
z, # $ tainted
a, # $ tainted
b, # $ tainted
)
def list_clear():
tainted_string = TAINTED_STRING
tainted_list = [tainted_string]
ensure_tainted(tainted_list) # $ tainted
tainted_list.clear()
ensure_not_tainted(tainted_list) # $ SPURIOUS: tainted
# Make tests runable
test_access()
list_clear()
| # Add taintlib to PATH so it can be imported during runtime without any hassle
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__))))
from taintlib import *
# This has no runtime impact, but allows autocomplete to work
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..taintlib import *
# Actual tests
def test_access():
tainted_list = TAINTED_LIST
ensure_tainted(
tainted_list.copy(), # $ tainted
)
def list_clear():
tainted_string = TAINTED_STRING
tainted_list = [tainted_string]
ensure_tainted(tainted_list) # $ tainted
tainted_list.clear()
ensure_not_tainted(tainted_list) # $ SPURIOUS: tainted
# Make tests runable
test_access()
list_clear()
|
Fix bad version description if no env vars | 'use strict';
var conf = require('./conf');
var pjson = require('../package.json');
// variables for views, this must be before the views are rendered and after any necessary request variables are set
function locals (req, res, next) {
res.locals.user = req.user;
if (req.csrfToken) { // not every request has CSRF token
res.locals.csrfToken = req.csrfToken();
}
res.locals.lang = req.locale;
res.locals.persona = conf.persona.enabled;
res.locals.baseHref = conf.url + '/' + req.locale + '/'; // use proxy URL (if applicable), not req.url
res.locals.environment = conf.env;
res.locals.version = pjson.version;
res.locals.commit = process.env.COMMIT_HASH || '';
if (process.env.DEPLOY_DATE) {
// DEPLOY_DATE is in seconds since that's what date +"%s" returns
res.locals.deployDate = parseInt(process.env.DEPLOY_DATE, 10) * 1000;
} else {
res.locals.deployDate = '';
}
next();
}
module.exports = locals;
| 'use strict';
var conf = require('./conf');
var pjson = require('../package.json');
// variables for views, this must be before the views are rendered and after any necessary request variables are set
function locals (req, res, next) {
res.locals.user = req.user;
if (req.csrfToken) { // not every request has CSRF token
res.locals.csrfToken = req.csrfToken();
}
res.locals.lang = req.locale;
res.locals.persona = conf.persona.enabled;
res.locals.baseHref = conf.url + '/' + req.locale + '/'; // use proxy URL (if applicable), not req.url
res.locals.environment = conf.env;
res.locals.version = pjson.version;
res.locals.commit = process.env.COMMIT_HASH;
// DEPLOY_DATE is in seconds since that's what date +"%s" returns
res.locals.deployDate = parseInt(process.env.DEPLOY_DATE, 10) * 1000;
next();
}
module.exports = locals;
|
Add CM's markdown addon that extends enter key behavior | "use strict";
var CodeMirror = require('codemirror')
// Register CodeMirror modes for our markup
require('codemirror/addon/edit/continuelist');
require('./cm_en-markdown_mode');
module.exports = function (el, value='', opts={}) {
var actions = require('./cm_actions')
, editor
editor = CodeMirror(el, {
value,
mode: 'en-markdown',
lineWrapping: true,
extraKeys: {
'Enter': 'newlineAndIndentContinueMarkdownList'
}
});
Object.keys(opts).forEach(key => {
editor[key] = opts[key];
});
editor.on('inputRead', actions.checkEmptyReferences)
editor.on('change', function (cm, { from, to }) {
var fromLine = from.line
, toLine = to.line
//actions.updateDocumentMarks(cm, fromLine, toLine);
actions.updateInlineReferences(cm, fromLine, toLine);
});
// Update references on editor initialization
actions.updateInlineReferences(editor, 0, editor.doc.lineCount() - 1);
return editor;
}
| "use strict";
var CodeMirror = require('codemirror')
// Register CodeMirror modes for our markup
require('codemirror/mode/gfm/gfm');
require('./cm_en-markdown_mode');
module.exports = function (el, value='', opts={}) {
var actions = require('./cm_actions')
, editor
editor = CodeMirror(el, {
value,
mode: 'en-markdown',
lineWrapping: true
});
Object.keys(opts).forEach(key => {
editor[key] = opts[key];
})
editor.on('inputRead', actions.checkEmptyReferences)
editor.on('change', function (cm, { from, to }) {
var fromLine = from.line
, toLine = to.line
//actions.updateDocumentMarks(cm, fromLine, toLine);
actions.updateInlineReferences(cm, fromLine, toLine);
});
// Update references on editor initialization
actions.updateInlineReferences(editor, 0, editor.doc.lineCount() - 1);
return editor;
}
|
Rename the argument of Tensor | // Package linear provides a linear-algebra toolbox.
package linear
// Tensor computes the tensor product of a number of vectors.
func Tensor(vectors ...[]float64) []float64 {
nd := len(vectors)
dims := make([]int, nd)
for i := 0; i < nd; i++ {
dims[i] = len(vectors[i])
}
aprod := make([]int, nd)
aprod[0] = 1
for i := 1; i < nd; i++ {
aprod[i] = dims[i-1] * aprod[i-1]
}
dprod := make([]int, nd)
dprod[nd-1] = 1
for i := nd - 2; i >= 0; i-- {
dprod[i] = dims[i+1] * dprod[i+1]
}
np := dims[0] * dprod[0]
tensor := make([]float64, np*nd)
for i, z := 0, 0; i < nd; i++ {
for j := 0; j < dprod[i]; j++ {
for k := 0; k < dims[i]; k++ {
for l := 0; l < aprod[i]; l++ {
tensor[z] = vectors[i][k]
z++
}
}
}
}
return tensor
}
| // Package linear provides a linear-algebra toolbox.
package linear
// Tensor computes the tensor product of a number of vectors.
func Tensor(data ...[]float64) []float64 {
nd := len(data)
dims := make([]int, nd)
for i := 0; i < nd; i++ {
dims[i] = len(data[i])
}
aprod := make([]int, nd)
aprod[0] = 1
for i := 1; i < nd; i++ {
aprod[i] = dims[i-1] * aprod[i-1]
}
dprod := make([]int, nd)
dprod[nd-1] = 1
for i := nd - 2; i >= 0; i-- {
dprod[i] = dims[i+1] * dprod[i+1]
}
np := dims[0] * dprod[0]
tensor := make([]float64, np*nd)
for i, z := 0, 0; i < nd; i++ {
for j := 0; j < dprod[i]; j++ {
for k := 0; k < dims[i]; k++ {
for l := 0; l < aprod[i]; l++ {
tensor[z] = data[i][k]
z++
}
}
}
}
return tensor
}
|
Add filenameRelative to opts to support AMD module names | 'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var applySourceMap = require('vinyl-sourcemaps-apply');
var objectAssign = require('object-assign');
var to5 = require('6to5');
module.exports = function (opts) {
opts = opts || {};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new gutil.PluginError('gulp-6to5', 'Streaming not supported'));
return;
}
try {
var fileOpts = objectAssign({}, opts, {
filename: file.path,
filenameRelative: file.relative,
sourceMap: !!file.sourceMap
});
var res = to5.transform(file.contents.toString(), fileOpts);
if (file.sourceMap && res.map) {
applySourceMap(file, res.map);
}
file.contents = new Buffer(res.code);
this.push(file);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-6to5', err, {fileName: file.path}));
}
cb();
});
};
| 'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var applySourceMap = require('vinyl-sourcemaps-apply');
var objectAssign = require('object-assign');
var to5 = require('6to5');
module.exports = function (opts) {
opts = opts || {};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new gutil.PluginError('gulp-6to5', 'Streaming not supported'));
return;
}
try {
var fileOpts = objectAssign({}, opts, {
filename: file.path,
sourceMap: !!file.sourceMap
});
var res = to5.transform(file.contents.toString(), fileOpts);
if (file.sourceMap && res.map) {
applySourceMap(file, res.map);
}
file.contents = new Buffer(res.code);
this.push(file);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-6to5', err, {fileName: file.path}));
}
cb();
});
};
|
Update last seen if we found url in our database | # -*- coding: utf-8 -*-
"""
Checks if the given URL was already processed
"""
import logging
from datetime import date
from scrapy.exceptions import IgnoreRequest
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from ..settings import DATABASE_URL
from ..models import Advertisement
class CrawledURLCheck(object):
def __init__(self):
engine = create_engine(DATABASE_URL)
self.Session = sessionmaker(bind=engine)
def process_request(self, request, spider):
"""check if the url was already crawled
"""
session = self.Session()
advertisement = session.query(Advertisement).filter(Advertisement.url == request.url).first()
session.close()
if advertisement:
logging.info("This url %s was already crawled update last seen", request.url)
advertisement.last_seen = date.today()
session.add(advertisement)
session.commit()
raise IgnoreRequest
return
| # -*- coding: utf-8 -*-
"""
Checks if the given URL was already processed
"""
import logging
from scrapy.exceptions import IgnoreRequest
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from ..settings import DATABASE_URL
from ..models import Advertisement
class CrawledURLCheck(object):
def __init__(self):
engine = create_engine(DATABASE_URL)
self.Session = sessionmaker(bind=engine)
def process_request(self, request, spider):
"""check if the url was already crawled
"""
session = self.Session()
advertisement = session.query(Advertisement).filter(Advertisement.url == request.url).all()
session.close()
if advertisement:
logging.info("This url %s was already crawled update last seen", request.url)
raise IgnoreRequest
return
|
Throw warning on missing CSS rather than error, so that tests can still run on Dj1.7 | import os
from django.core.checks import Warning, register
@register()
def css_install_check(app_configs, **kwargs):
errors = []
css_path = os.path.join(
os.path.dirname(__file__), 'static', 'wagtailadmin', 'css', 'normalize.css'
)
if not os.path.isfile(css_path):
error_hint = """
Most likely you are running a development (non-packaged) copy of
Wagtail and have not built the static assets -
see http://docs.wagtail.io/en/latest/contributing/developing.html
File not found: %s
""" % css_path
errors.append(
Warning(
"CSS for the Wagtail admin is missing",
hint=error_hint,
id='wagtailadmin.W001',
)
)
return errors
| import os
from django.core.checks import Error, register
@register()
def css_install_check(app_configs, **kwargs):
errors = []
css_path = os.path.join(
os.path.dirname(__file__), 'static', 'wagtailadmin', 'css', 'normalize.css'
)
if not os.path.isfile(css_path):
error_hint = """
Most likely you are running a development (non-packaged) copy of
Wagtail and have not built the static assets -
see http://docs.wagtail.io/en/latest/contributing/developing.html
File not found: %s
""" % css_path
errors.append(
Error(
"CSS for the Wagtail admin is missing",
hint=error_hint,
id='wagtailadmin.E001',
)
)
return errors
|
Fix permission table creation migration | """Add permissions
Revision ID: 29a56dc34a2b
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:06:24.088307
"""
# revision identifiers, used by Alembic.
revision = '29a56dc34a2b'
down_revision = '5245d0b46f8'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('permissions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('repository_id', sa.Integer(), nullable=False),
sa.Column('admin', sa.Boolean(), nullable=False),
sa.Column('push', sa.Boolean(), nullable=False),
sa.Column('pull', sa.Boolean(), nullable=False),
sa.ForeignKeyConstraint(
['repository_id'], ['repositories.id'], ondelete='CASCADE',
),
sa.ForeignKeyConstraint(
['user_id'], ['users.id'], ondelete='CASCADE',
),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('permissions')
| """Add permissions
Revision ID: 29a56dc34a2b
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:06:24.088307
"""
# revision identifiers, used by Alembic.
revision = '29a56dc34a2b'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('permissions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('repository_id', sa.Integer(), nullable=False),
sa.Column('admin', sa.Boolean(), nullable=False),
sa.Column('push', sa.Boolean(), nullable=False),
sa.Column('pull', sa.Boolean(), nullable=False),
sa.ForeignKeyConstraint(['repository_id'], ['repositories.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('permissions')
|
Add die if invalid action is passed | <?php
//Indication, Copyright Josh Fradley (http://github.com/joshf/Indication)
if (!file_exists("../../config.php")) {
header("Location: ../../installer");
exit;
}
require_once("../../config.php");
session_start();
if (!isset($_SESSION["indication_user"])) {
header("Location: ../login.php");
exit;
}
if (!isset($_POST["id"])) {
header("Location: ../../admin");
exit;
}
//Connect to database
@$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
die("Error: Could not connect to database (" . mysqli_connect_error() . "). Check your database settings are correct.");
}
$id = mysqli_real_escape_string($con, $_POST["id"]);
if (isset($_POST["action"])) {
$action = $_POST["action"];
} else {
die("Error: No action passed");
}
if ($action == "delete") {
mysqli_query($con, "DELETE FROM `Data` WHERE `id` = \"$id\"");
} else {
die("Error: Action not recognised!");
}
mysqli_close($con);
?> | <?php
//Indication, Copyright Josh Fradley (http://github.com/joshf/Indication)
if (!file_exists("../../config.php")) {
header("Location: ../../installer");
exit;
}
require_once("../../config.php");
session_start();
if (!isset($_SESSION["indication_user"])) {
header("Location: ../login.php");
exit;
}
if (!isset($_POST["id"])) {
header("Location: ../../admin");
exit;
}
//Connect to database
@$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
die("Error: Could not connect to database (" . mysqli_connect_error() . "). Check your database settings are correct.");
}
$id = mysqli_real_escape_string($con, $_POST["id"]);
if (isset($_POST["action"])) {
$action = $_POST["action"];
} else {
die("Error: No action passed");
}
if ($action == "delete") {
mysqli_query($con, "DELETE FROM `Data` WHERE `id` = \"$id\"");
}
mysqli_close($con);
?> |
Test fix for node crash | var express = require('express');
var app = express();
const path = require('path');
// Environment variables
const node_env = process.env.NODE_ENV || "Local";
const env_var = process.env.ENV_VAR || "Local";
const env_color = process.env.ENV_COLOR || "DodgerBlue";
const env = {
NODE_ENV: node_env,
ENV_VAR: env_var,
ENV_COLOR: env_color
};
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/dist'));
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
app.get('/api/getEnvironment', function(request, response){
const envVar = {
name: env.ENV_VAR,
color: env.ENV_COLOR
};
response.json(envVar);
});
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
app.listen(app.get('port'), function(){
console.log('Node app is running on port', app.get('port'));
console.log('NODE_ENV: '+ process.env.NODE_ENV);
});
| var express = require('express');
var app = express();
const path = require('path');
// Environment variables
const node_env = process.env.NODE_ENV || "Local";
const env_var = process.env.ENV_VAR || "Local";
const env_color = process.env.ENV_COLOR || "DodgerBlue";
const env = {
NODE_ENV: node_env,
ENV_VAR: env_var,
ENV_COLOR: env_color
};
app.set('port', (env.PORT || 5000));
app.use(express.static(__dirname + '/dist'));
app.get('/api/getEnvironment', function(request, response){
const envVar = {
name: env.ENV_VAR,
color: env.ENV_COLOR
};
response.json(envVar);
});
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
app.listen(app.get('port'), function(){
console.log('Node app is running on port', app.get('port'));
console.log('NODE_ENV: '+ env.NODE_ENV);
});
|
Use only POST for http-bind route | <?php
/**
* ownCloud - JavaScript XMPP Chat
*
* Copyright (c) 2014 Klaus Herberth <klaus@jsxc.org> <br>
* Released under the MIT license
*
* @author Klaus Herberth
*/
use \OCA\OJSXC\AppInfo\Application;
$this->create('ojsxc_ajax_getsettings', 'ajax/getsettings.php')
->actionInclude('ojsxc/ajax/getsettings.php');
$this->create('ojsxc_ajax_getturncredentials', 'ajax/getturncredentials.php')
->actionInclude('ojsxc/ajax/getturncredentials.php');
$this->create('ojsxc_ajax_setsettings', 'ajax/setsettings.php')
->actionInclude('ojsxc/ajax/setsettings.php');
$this->create('ojsxc_ajax_setUserSettings', 'ajax/setUserSettings.php')
->actionInclude('ojsxc/ajax/setUserSettings.php');
$this->create('ojsxc_ajax_getUsers', 'ajax/getUsers.php')
->actionInclude('ojsxc/ajax/getUsers.php');
$application = new Application();
$application->registerRoutes($this, array(
'routes' => array(
array('name' => 'http_bind#index', 'url' => '/http-bind', 'verb' => 'POST'),
)
));
?>
| <?php
/**
* ownCloud - JavaScript XMPP Chat
*
* Copyright (c) 2014 Klaus Herberth <klaus@jsxc.org> <br>
* Released under the MIT license
*
* @author Klaus Herberth
*/
use \OCA\OJSXC\AppInfo\Application;
$this->create('ojsxc_ajax_getsettings', 'ajax/getsettings.php')
->actionInclude('ojsxc/ajax/getsettings.php');
$this->create('ojsxc_ajax_getturncredentials', 'ajax/getturncredentials.php')
->actionInclude('ojsxc/ajax/getturncredentials.php');
$this->create('ojsxc_ajax_setsettings', 'ajax/setsettings.php')
->actionInclude('ojsxc/ajax/setsettings.php');
$this->create('ojsxc_ajax_setUserSettings', 'ajax/setUserSettings.php')
->actionInclude('ojsxc/ajax/setUserSettings.php');
$this->create('ojsxc_ajax_getUsers', 'ajax/getUsers.php')
->actionInclude('ojsxc/ajax/getUsers.php');
$application = new Application();
$application->registerRoutes($this, array(
'routes' => array(
array('name' => 'http_bind#index', 'url' => '/http-bind', 'verb' => array('GET', 'POST')),
)
));
?>
|
Add field name to the enrollments export list | <!DOCTYPE html>
<html>
<table>
<tr>
<th>Course ID</th>
<th>Course</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Student E-mail</th>
<th>Enrollment Date</th>
</tr>
@foreach($enrollments as $enrollment)
<tr>
<td>{{ $enrollment->course->id }}</td>
<td>{{ $enrollment->course->name }}</td>
<td>{{ $enrollment->student->student_number }}</td>
<td>{{ $enrollment->student->user->name }}</td>
<td>{{ $enrollment->student->user->email }}</td>
<td>{{ $enrollment->student->created_at }}</td>
</tr>
@endforeach
</table>
</html>
| <!DOCTYPE html>
<html>
<table>
<tr>
<th>Course</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Student E-mail</th>
<th>Enrollment Date</th>
</tr>
@foreach($enrollments as $enrollment)
<tr>
<td>{{ $enrollment->course->id }}</td>
<td>{{ $enrollment->course->name }}</td>
<td>{{ $enrollment->student->student_number }}</td>
<td>{{ $enrollment->student->user->name }}</td>
<td>{{ $enrollment->student->user->email }}</td>
<td>{{ $enrollment->student->created_at }}</td>
</tr>
@endforeach
</table>
</html>
|
Fix the bug of **Tried to load angular more than once.**. | angular.module('specialBlogApp', [
'ngRoute',
'ngResource'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/index.html',
controller: 'HomeCtrl'
})
.when('/article/:articleId', {
templateUrl: '/views/article.html',
controller: 'ArticleCtrl'
})
.when('/articles', {
templateUrl: '/views/articles.html',
controller: 'ArticlesCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
| angular.module('specialBlogApp', [
'ngRoute',
'ngResource'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/index.html',
controller: 'HomeCtrl'
})
.when('/article/:articleId', {
templateUrl: 'views/article.html',
controller: 'ArticleCtrl'
})
.when('/articles', {
templateUrl: 'views/articles.html',
controller: 'ArticlesCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
|
Allow redirecting dock's logs to a given handler only | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
constants
"""
import logging
def set_logging(name="dock", level=logging.DEBUG, handler=None):
# create logger
logger = logging.getLogger(name)
logger.handlers = []
logger.setLevel(level)
if not handler:
# create console handler and set level to debug
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
handler.setFormatter(formatter)
# add ch to logger
logger.addHandler(handler)
set_logging(level=logging.WARNING) # override this however you want
| """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
constants
"""
import logging
def set_logging(name="dock", level=logging.DEBUG):
# create logger
logger = logging.getLogger(name)
logger.handlers = []
logger.setLevel(level)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
set_logging(level=logging.WARNING) # override this however you want |
Fix accidental overwrite of paperSize | 'use strict';
exports.run = function (options, cb) {
var page = require('webpage').create();
var port = options.port || 3000;
var id = options.id;
var size = options.size || '800x600';
var quality = options.quality || 100;
var format = options.format || 'jpeg';
var url = 'http://localhost:' + port + '/' + id;
var validFormats = ['jpeg', 'png', 'gif', 'pdf'];
if (validFormats.indexOf(format) === -1) {
return cb('Invalid format type, valid options include: ' + validFormats.join(', '));
}
page.viewportSize = { width: 600, height: 600 };
if (size) {
size = size.split('x');
page.viewportSize = { width: size[0], height: size[1] };
}
if (format === 'pdf') {
if (size) {
page.paperSize = { width: size[0], height: size[1], margin: '0px' };
}
else {
page.paperSize = { format: 'A4', orientation: 'landscape', margin: '1cm' };
}
page.viewportSize = undefined;
}
page.open(url, function () {
var filePath = '.tmp/' + id + '.' + format;
setTimeout(function () {
page.render(filePath, { format: format, quality: quality });
cb(undefined, filePath);
page.close();
phantom.exit();
}, 200);
});
};
| 'use strict';
exports.run = function (options, cb) {
var page = require('webpage').create();
var port = options.port || 3000;
var id = options.id;
var size = options.size || '800x600';
var quality = options.quality || 100;
var format = options.format || 'jpeg';
var url = 'http://localhost:' + port + '/' + id;
var validFormats = ['jpeg', 'png', 'gif', 'pdf'];
if (validFormats.indexOf(format) === -1) {
return cb('Invalid format type, valid options include: ' + validFormats.join(', '));
}
page.viewportSize = { width: 600, height: 600 };
if (size) {
size = size.split('x');
page.viewportSize = { width: size[0], height: size[1] };
}
if (format === 'pdf') {
if (size) {
page.paperSize = { width: size[0], height: size[1], margin: '0px' };
}
page.paperSize = { format: 'A4', orientation: 'landscape', margin: '1cm' };
page.viewportSize = undefined;
}
page.open(url, function () {
var filePath = '.tmp/' + id + '.' + format;
setTimeout(function () {
page.render(filePath, { format: format, quality: quality });
cb(undefined, filePath);
page.close();
phantom.exit();
}, 200);
});
};
|
Upgrade dependency appdirs to ==1.4.2 | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.2',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.1',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.1',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.1',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Change email address for sending email notifications | import nodemailer from 'nodemailer';
import smtpTransport from 'nodemailer-smtp-transport';
function sendEmail(emailParams) {
const mailOptions = {
from: emailParams.recepientAddress,
to: emailParams.senderAddress,
subject: emailParams.subject,
html: emailParams.emailBody
};
const transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
port: 465,
auth: {
user: 'noreply.swiftpost@gmail.com',
pass: process.env.EMAIL_PASSWORD
}
}));
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log(`Email sent:${info.response}`);
}
});
}
export default sendEmail;
| import nodemailer from 'nodemailer';
import smtpTransport from 'nodemailer-smtp-transport';
function sendEmail(emailParams) {
const mailOptions = {
from: emailParams.recepientAddress,
to: emailParams.senderAddress,
subject: emailParams.subject,
html: emailParams.emailBody
};
const transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
port: 465,
auth: {
user: 'mazi.mary.o@gmail.com',
pass: process.env.EMAIL_PASSWORD
}
}));
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log(`Email sent:${info.response}`);
}
});
}
export default sendEmail;
|
Update config for plugin (still needs moving outside this lib) | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { Router, Route } from 'react-router'
import config from 'react-global-configuration'
//views
import HomePage from './views/Home'
import ListPageContainer from './views/List'
//store
import { store, history } from './store'
//set up config
config.set(
{
baseUrl: '/api',
entities: {
ids: ['plugin'],
byId: {
'plugin': {},
}
}
}
);
class CrudApp extends React.Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={HomePage} />
<Route path="/:entity(/edit/:entityId)" component={ListPageContainer} />
</Router>
</Provider>
)
}
}
export default CrudApp | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { Router, Route } from 'react-router'
import config from 'react-global-configuration'
//views
import HomePage from './views/Home'
import ListPageContainer from './views/List'
//store
import { store, history } from './store'
//set up config
config.set(
{
baseUrl: '/api',
entities: {
ids: ['package'],
byId: {
'package': {},
}
}
}
);
class CrudApp extends React.Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={HomePage} />
<Route path="/:entity(/edit/:entityId)" component={ListPageContainer} />
</Router>
</Provider>
)
}
}
export default CrudApp |
Use Case for persona b (pet seeker) | <!DOCTYPE html>
<head>
<title>Conceptual-Model</title>
</head>
<body>
<main>
<h2>Entities and Attributes</h2>
<p><strong>Profile</strong></p>
<ul>
<li>profileId</li>
<li>profileAtHandle</li>
<li>profileEmail</li>
<li>profilePhone</li>
</ul>
<p><strong>Pet Profile</strong></p>
<ul>
<li>petId</li>
<li>petProfileId</li>
<li>petDescription</li>
<li>petType</li>
<li>petBreed</li>
<li>PetLocation</li>
</ul>
<p><strong>images</strong></p>
<ul>
<li>petProfileImage</li>
</ul>
<p><strong>Relations</strong></p>
<ul>
<li>One <strong>Profile </strong>favorites products - (m to n)</li>
</ul>
<br>
<img src="https://bootcamp-coders.cnm.edu/~mharrison13/data-design/public_html/images/erd-data-design.svg">
</main>
</body> | <!DOCTYPE html>
<head>
<title>Conceptual-Model</title>
</head>
<body>
<main>
<h2>Entities and Attributes</h2>
<p><strong>Profile</strong></p>
<ul>
<li>profileId</li>
<li>profileAtHandle</li>
<li>profileEmail</li>
<li>profilePhone</li>
</ul>
<p><strong>Pet Profile</strong></p>
<ul>
<li>petId</li>
<li>petProfileId</li>
<li>petDescription</li>
<li>petType</li>
<li>petBreed</li>
<li>PetLocation</li>
</ul>
<p><strong>images</strong></p>
<ul>
<li>petProfileImage</li>
</ul>
<p><strong>Relations</strong></p>
<ul>
<li>One <strong>Profile </strong>favorites products - (m to n)</li>
</ul>
<br>
<img src="https://bootcamp-coders.cnm.edu/~mharrison13/data-design/public_html/images/erd-data-design.svg">
</main>
</body> |
Use default Bach factory with its external tool finder | import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.ToolCall;
class format {
public static void main(String... args) throws Exception {
var bach = Bach.ofDefaults();
if (bach.configuration().finder().find("format@1.15.0").isEmpty()) {
bach.run(
"""
load-and-verify
.bach/external-tools/format@1.15.0/google-java-format-1.15.0-all-deps.jar
https://github.com/google/google-java-format/releases/download/v1.15.0/google-java-format-1.15.0-all-deps.jar\
#SIZE=3519780\
&SHA-256=a356bb0236b29c57a3ab678f17a7b027aad603b0960c183a18f1fe322e4f38ea
""");
}
var format = ToolCall.of("format@1.15.0").with("--replace").withFindFiles("**/*.java");
bach.run("banner", "Format %d .java files".formatted(format.arguments().size() - 1));
bach.run(format);
}
}
| import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.ToolCall;
import com.github.sormuras.bach.ToolFinder;
class format {
public static void main(String... args) throws Exception {
var bach = Bach.ofDefaults().with(ToolFinder.ofJavaTools(".bach/external-tools"));
if (bach.configuration().finder().find("format@1.15.0").isEmpty()) {
bach.run(
"""
load-and-verify
.bach/external-tools/format@1.15.0/google-java-format-1.15.0-all-deps.jar
https://github.com/google/google-java-format/releases/download/v1.15.0/google-java-format-1.15.0-all-deps.jar\
#SIZE=3519780\
&SHA-256=a356bb0236b29c57a3ab678f17a7b027aad603b0960c183a18f1fe322e4f38ea
""");
}
var format = ToolCall.of("format@1.15.0").with("--replace").withFindFiles("**/*.java");
bach.run("banner", "Format %d .java files".formatted(format.arguments().size() - 1));
bach.run(format);
}
}
|
Remove namespace_packages argument which works with declare_namespace. | from setuptools import setup, find_packages
import io
# List all of your Python package dependencies in the
# requirements.txt file
def readfile(filename, split=False):
with io.open(filename, encoding="utf-8") as stream:
if split:
return stream.read().split("\n")
return stream.read()
readme = readfile("README.rst", split=True)[3:] # skip title
requires = readfile("requirements.txt", split=True)
software_licence = readfile("LICENSE")
setup(
name='opencmiss.utils',
version='0.1.1',
description='OpenCMISS Utilities for Python.',
long_description='\n'.join(readme) + software_licence,
classifiers=[],
author='Hugh Sorby',
author_email='',
url='',
license='APACHE',
packages=find_packages(exclude=['ez_setup',]),
include_package_data=True,
zip_safe=False,
install_requires=requires,
)
| from setuptools import setup, find_packages
import io
# List all of your Python package dependencies in the
# requirements.txt file
def readfile(filename, split=False):
with io.open(filename, encoding="utf-8") as stream:
if split:
return stream.read().split("\n")
return stream.read()
readme = readfile("README.rst", split=True)[3:] # skip title
requires = readfile("requirements.txt", split=True)
software_licence = readfile("LICENSE")
setup(
name='opencmiss.utils',
version='0.1.1',
description='OpenCMISS Utilities for Python.',
long_description='\n'.join(readme) + software_licence,
classifiers=[],
author='Hugh Sorby',
author_email='',
url='',
license='APACHE',
packages=find_packages(exclude=['ez_setup',]),
namespace_packages=['opencmiss'],
include_package_data=True,
zip_safe=False,
install_requires=requires,
)
|
Remove Redux logs in production | import { applyMiddleware, createStore, compose } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import persistState, { mergePersistedState } from 'redux-localstorage';
import adapter from 'redux-localstorage/lib/adapters/localStorage';
import filter from 'redux-localstorage-filter';
import rootReducer from '../reducers';
export default function configureStore(history) {
const logger = createLogger({
level: process.env.NODE_ENV === 'production' ? 'error' : 'log',
collapsed: true,
});
const reduxRouterMiddleware = routerMiddleware(history);
const reducers = compose(mergePersistedState())(rootReducer);
const storageAuth = compose(filter('authentication'))(adapter(window.localStorage));
const storageLang = compose(filter('language'))(adapter(window.localStorage));
let createCustomStore = compose(
persistState(storageAuth, 'authentication'),
persistState(storageLang, 'language'),
)(createStore);
const middlewares = [
reduxRouterMiddleware,
thunk,
];
if (process.env.NODE_ENV !== 'production') {
middlewares.push(logger);
}
createCustomStore = applyMiddleware(...middlewares)(createCustomStore);
const store = createCustomStore(reducers);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers'); // eslint-disable-line
store.replaceReducer(nextReducer);
});
}
return store;
}
| import { applyMiddleware, createStore, compose } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import persistState, { mergePersistedState } from 'redux-localstorage';
import adapter from 'redux-localstorage/lib/adapters/localStorage';
import filter from 'redux-localstorage-filter';
import rootReducer from '../reducers';
export default function configureStore(history) {
const logger = createLogger({
level: process.env.NODE_ENV === 'production' ? 'error' : 'log',
collapsed: true,
});
const reduxRouterMiddleware = routerMiddleware(history);
const reducers = compose(mergePersistedState())(rootReducer);
const storageAuth = compose(filter('authentication'))(adapter(window.localStorage));
const storageLang = compose(filter('language'))(adapter(window.localStorage));
let createCustomStore = compose(
persistState(storageAuth, 'authentication'),
persistState(storageLang, 'language'),
)(createStore);
createCustomStore = applyMiddleware(
reduxRouterMiddleware,
thunk,
logger,
)(createCustomStore);
const store = createCustomStore(reducers);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers'); // eslint-disable-line
store.replaceReducer(nextReducer);
});
}
return store;
}
|
Fix LinearMean bias when bias=False | #!/usr/bin/env python3
import torch
from .mean import Mean
class LinearMean(Mean):
def __init__(self, input_size, batch_shape=torch.Size(), bias=True):
super().__init__()
self.register_parameter(name='weights',
parameter=torch.nn.Parameter(torch.randn(*batch_shape, input_size, 1)))
if bias:
self.register_parameter(name='bias', parameter=torch.nn.Parameter(torch.randn(*batch_shape, 1)))
else:
self.bias = None
def forward(self, x):
res = x.matmul(self.weights).squeeze(-1)
if self.bias is not None:
res = res + self.bias
return res
| #!/usr/bin/env python3
import torch
from .mean import Mean
class LinearMean(Mean):
def __init__(self, input_size, batch_shape=torch.Size(), bias=True):
super().__init__()
self.register_parameter(name='weights',
parameter=torch.nn.Parameter(torch.randn(*batch_shape, input_size, 1)))
if bias:
self.register_parameter(name='bias', parameter=torch.nn.Parameter(torch.randn(*batch_shape, 1)))
def forward(self, x):
res = x.matmul(self.weights).squeeze(-1)
if self.bias is not None:
res = res + self.bias
return res
|
Use PEP 508 URL dependencies to specify patched jsonpatch
Signed-off-by: Chris Harris <a361e89d1eba6c570561222d75facbbf7aaeeafe@kitware.com> | from setuptools import setup, find_packages
setup(
name='tomviz-pipeline',
version='0.0.1',
description='Tomviz python external pipeline execution infrastructure.',
author='Kitware, Inc.',
author_email='kitware@kitware.com',
url='https://www.tomviz.org/',
license='BSD 3-Clause',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD 3-Clause',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5'
],
packages=find_packages(),
install_requires=['tqdm', 'h5py', 'numpy==1.16.4', 'click', 'scipy'],
extras_require={
'interactive': ['jsonpatch@https://github.com/cjh1/python-json-patch/archive/tomviz.zip', 'marshmallow'],
'itk': ['itk'],
'pyfftw': ['pyfftw']
},
entry_points={
'console_scripts': [
'tomviz-pipeline = tomviz.cli:main'
]
}
)
| from setuptools import setup, find_packages
setup(
name='tomviz-pipeline',
version='0.0.1',
description='Tomviz python external pipeline execution infrastructure.',
author='Kitware, Inc.',
author_email='kitware@kitware.com',
url='https://www.tomviz.org/',
license='BSD 3-Clause',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD 3-Clause',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5'
],
packages=find_packages(),
install_requires=['tqdm', 'h5py', 'numpy==1.16.4', 'click', 'scipy'],
extras_require={
'interactive': ['jsonpatch', 'marshmallow'],
'itk': ['itk'],
'pyfftw': ['pyfftw']
},
entry_points={
'console_scripts': [
'tomviz-pipeline = tomviz.cli:main'
]
}
)
|
[FIX] pylint: Fix error String statement has no effect | # -*- coding: utf-8 -*-
"""
This module create model of Wizard
"""
from openerp import fields, models, api
class Wizard(models.TransientModel):
""""
This class create model of Wizard
"""
_name = 'openacademy.wizard'
def _default_sessions(self):
return self.env['openacademy.session'].browse(
self._context.get('active_ids'))
session_ids = fields.Many2many('openacademy.session',
string="Sessions", required=True,
default=_default_sessions)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
@api.multi
def subscribe(self):
for session in self.session_ids:
session.attendee_ids |= self.attendee_ids
return {}
| # -*- coding: utf-8 -*-
from openerp import fields, models, api
"""
This module create model of Wizard
"""
class Wizard(models.TransientModel):
""""
This class create model of Wizard
"""
_name = 'openacademy.wizard'
def _default_sessions(self):
return self.env['openacademy.session'].browse(
self._context.get('active_ids'))
session_ids = fields.Many2many('openacademy.session',
string="Sessions", required=True,
default=_default_sessions)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
@api.multi
def subscribe(self):
for session in self.session_ids:
session.attendee_ids |= self.attendee_ids
return {}
|
Change debug logger to be synchronous. | import fs from "fs";
import InputStream from "./InputStream";
export function isGreyspace(string) {
if (string === "" ||
string === " " ||
string === "\n" ||
/^\s*$/.test(string)) {
return true;
}
if (string === undefined || string === null)
throw new Error("passed undefined or null to isGreyspace");
let stream = new InputStream(string);
while (!stream.atEnd()) {
let consumed = stream.consume(/\s+/) ||
stream.consume(/\/\/[^\n]*/) ||
stream.consume(/\/\*[\W\S]*?\*\//);
if (!consumed) return false;
}
return stream.atEnd();
}
export function log(...messages) {
let data = messages.join(" ") + "\n";
fs.writeSync(3, data);
}
| import fs from "fs";
import InputStream from "./InputStream";
export function isGreyspace(string) {
if (string === "" ||
string === " " ||
string === "\n" ||
/^\s*$/.test(string)) {
return true;
}
if (string === undefined || string === null)
throw new Error("passed undefined or null to isGreyspace");
let stream = new InputStream(string);
while (!stream.atEnd()) {
let consumed = stream.consume(/\s+/) ||
stream.consume(/\/\/[^\n]*/) ||
stream.consume(/\/\*[\W\S]*?\*\//);
if (!consumed) return false;
}
return stream.atEnd();
}
let stream = fs.createWriteStream("", {
fd: 3,
encoding: "utf8"
});
function handleError(error) {
if (error) {
if (error.code === "EBADF") {
stream = null;
} else {
throw error;
}
}
}
stream.on("error", handleError);
export function log(...messages) {
if (!stream) return;
stream.write(messages.join("") + "\n", "utf8", handleError);
}
|
Add viewport meta tag to layout view | <!DOCTYPE html>
<html>
<head>
<title>Budget</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:300,300i" />
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="navigation">
<ul>
<li>
<a href="/dashboard">Dashboard</a>
</li>
</ul>
<ul>
<li>
<a href="/settings">Settings</a>
</li>
<li>
<a href="/logout">Log out</a>
</li>
</ul>
</div>
<div class="body">
@yield('body')
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<title>Budget</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:300,300i" />
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="navigation">
<ul>
<li>
<a href="/dashboard">Dashboard</a>
</li>
</ul>
<ul>
<li>
<a href="/settings">Settings</a>
</li>
<li>
<a href="/logout">Log out</a>
</li>
</ul>
</div>
<div class="body">
@yield('body')
</div>
</body>
</html>
|
Fix Bug From Model Publicity | /**
* Created by K on 10/2/2016.
*/
var mongoose = require('mongoose');
var PublicitySchema = mongoose.Schema({
publicity_name: {
type: String
},
publicity_desciption: {
type: String
},
photos: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'photo'
}],
publicity_price: {
type: Number
}
});
var Publicity = module.exports = mongoose.model('publicity', PublicitySchema);
/*Create Publicity*/
module.exports.createPublicity = function (newPublicity, callback) {
newPublicity.save(callback);
};
module.exports.getAllPublicity = function (callback) {
Publicity.findAdmin(callback);
};
module.exports.getPublicityById = function (id, callback) {
Publicity.findById(id, callback);
};
module.exports.getPublicityByName = function (name, callback) {
var query = {publicity_name: name};
Publicity.find(query, callback);
};
/**Find all photos belong to this Publicity */
module.exports.findPhotosBelong = function (id, callback) {
Publicity.findById(id).populate('photos').exec(callback);
};
/*Remove Publicity*/
module.exports.removePublicity = function (id, callback) {
Publicity.findByIdAndRemove(id, callback);
}; | /**
* Created by K on 10/2/2016.
*/
var mongoose = require('mongoose');
var PublicitySchema = mongoose.Schema({
publicity_name: {
type: String
},
publicity_desciption: {
type: String
},
photos: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'photo'
}],
publicity_price: {
type: Number
}
});
var Publicity = module.exports = moongose.model('publicity', PublicitySchema);
/*Create Publicity*/
module.exports.createPublicity = function (newPublicity, callback) {
newPublicity.save(callback);
};
module.exports.getAllPublicity = function (callback) {
Publicity.findAdmin(callback);
};
module.exports.getPublicityById = function (id, callback) {
Publicity.findById(id, callback);
};
module.exports.getPublicityByName = function (name, callback) {
var query = {publicity_name: name};
Publicity.find(query, callback);
};
/**Find all photos belong to this Publicity */
module.exports.findPhotosBelong = function (id, callback) {
Publicity.findById(id).populate('photos').exec(callback);
};
/*Remove Publicity*/
module.exports.removePublicity = function (id, callback) {
Publicity.findByIdAndRemove(id, callback);
}; |
chore(website): Fix display issue with Layout examples | /* @flow */
import { createStyledComponent, pxToEm } from '../../../../../library/styles';
import _Flex from '../../../../../library/Flex';
type Props = {
gutterWidth?: number | string,
theme: Object
};
export const containerStyles = ({
gutterWidth: propGutterSize,
theme
}: Props) => {
const gutterWidth = propGutterSize === undefined ? 'md' : propGutterSize;
const gutter =
typeof gutterWidth === 'number'
? pxToEm(gutterWidth / 2)
: `${parseFloat(theme[`space_inline_${gutterWidth}`] || gutterWidth) /
2}em`;
const offset = gutterWidth ? `calc(${gutter} - 4px)` : -4;
return {
position: 'relative',
zIndex: 1,
'&::before': {
border: `1px dotted ${theme.color_theme_30}`,
bottom: -4,
content: '""',
left: offset,
position: 'absolute',
right: offset,
top: -4,
zIndex: -1
}
};
};
export default createStyledComponent(_Flex, (props) => ({
...containerStyles(props)
}));
| /* @flow */
import { createStyledComponent, pxToEm } from '../../../../../library/styles';
import _Flex from '../../../../../library/Flex';
type Props = {
gutterWidth?: number | string,
theme: Object
};
export const containerStyles = ({
gutterWidth: propGutterSize,
theme
}: Props) => {
const gutterWidth = propGutterSize === undefined ? 'md' : propGutterSize;
const gutter =
typeof gutterWidth === 'number'
? pxToEm(gutterWidth / 2)
: `${parseFloat(theme[`space_inline_${gutterWidth}`] || gutterWidth) /
2}em`;
const offset = gutterWidth ? `calc(${gutter} - 4px)` : -4;
return {
position: 'relative',
'&::before': {
border: `1px dotted ${theme.color_theme_30}`,
bottom: -4,
content: '""',
left: offset,
position: 'absolute',
right: offset,
top: -4,
zIndex: -1
}
};
};
export default createStyledComponent(_Flex, (props) => ({
...containerStyles(props)
}));
|
Fix Parquet encoding for timestamps before epoch | package org.apache.hadoop.hive.ql.io.parquet.timestamp;
import org.apache.hadoop.hive.common.type.Timestamp;
import static java.lang.Math.floorDiv;
import static java.lang.Math.floorMod;
import static java.lang.Math.toIntExact;
import static java.util.concurrent.TimeUnit.SECONDS;
public final class NanoTimeUtils
{
private NanoTimeUtils() {}
private static final int JULIAN_EPOCH_OFFSET_DAYS = 2_440_588;
private static final long SECONDS_PER_DAY = 86400L;
public static NanoTime getNanoTime(Timestamp timestamp, @SuppressWarnings("unused") boolean ignored)
{
long epochSeconds = timestamp.toEpochSecond();
int epochDay = toIntExact(floorDiv(epochSeconds, SECONDS_PER_DAY));
int julianDay = JULIAN_EPOCH_OFFSET_DAYS + epochDay;
long timeOfDaySeconds = floorMod(epochSeconds, SECONDS_PER_DAY);
long timeOfDayNanos = SECONDS.toNanos(timeOfDaySeconds) + timestamp.getNanos();
return new NanoTime(julianDay, timeOfDayNanos);
}
}
| package org.apache.hadoop.hive.ql.io.parquet.timestamp;
import org.apache.hadoop.hive.common.type.Timestamp;
import static java.lang.Math.toIntExact;
import static java.util.concurrent.TimeUnit.SECONDS;
public final class NanoTimeUtils
{
private NanoTimeUtils() {}
private static final int JULIAN_EPOCH_OFFSET_DAYS = 2_440_588;
public static NanoTime getNanoTime(Timestamp timestamp, @SuppressWarnings("unused") boolean ignored)
{
int epochDay = toIntExact(SECONDS.toDays(timestamp.toEpochSecond()));
int julianDay = JULIAN_EPOCH_OFFSET_DAYS + epochDay;
long timeOfDaySeconds = timestamp.toEpochSecond() % 86400;
long timeOfDayNanos = SECONDS.toNanos(timeOfDaySeconds) + timestamp.getNanos();
return new NanoTime(julianDay, timeOfDayNanos);
}
}
|
Add header logo, index route, and navbar classes | import React from 'react';
import { Link, IndexLink } from 'react-router';
class App extends React.Component {
render() {
return (
<div className="app">
<div className="logo-wrapper">
<img className="logo" src="../../assets/WebsiteHeader.png" alt="Kristin Miller Jewelry"/>
</div>
<div className="navbar container">
<IndexLink to={"/"} className="navlink" activeClassName="active">Jewelry Products</IndexLink>
<Link to={"/materials"} className="navlink" activeClassName="active">Materials</Link>
<Link to={"/products"} className="navlink" activeClassName="active">Other Products</Link>
<Link to={"/purchaseorders"} className="navlink" activeClassName="active">Purchase Orders</Link>
<Link to={"/sales"} className="navlink" activeClassName="active">Sales</Link>
<Link to={"/vendors"} className="navlink" activeClassName="active">Vendors</Link>
<Link to={"/settings"} className="navlink" activeClassName="active">Settings</Link>
</div>
{this.props.children}
</div>
);
}
}
export default App;
| import React from 'react';
import { Link } from 'react-router';
class App extends React.Component {
render() {
return (
<div className="app">
<h1>Welcome to KIM!</h1>
<ul className="navbar">
<li><Link to={'/jewelry'}>Jewelry Products</Link></li>
<li><Link to={'/materials'}>Materials</Link></li>
<li><Link to={'/products'}>Other Products</Link></li>
<li><Link to={'/purchaseorders'}>Purchase Orders</Link></li>
<li><Link to={'/sales'}>Sales</Link></li>
<li><Link to={'/vendors'}>Vendors</Link></li>
<li><Link to={'/settings'}>Settings</Link></li>
</ul>
{this.props.children}
</div>
);
}
}
export default App;
|
Put resumptiontoken in OAI ListRecords template.
refs #3888
Added resumptionToken display in th OAI-PMH ListRecords template. | <?php if($recordsCount == 0):?>
<error code="noRecordsMatch">The combination of the values of the from, until, set and metadataPrefix arguments results in an empty list.</error>
<?php else:?>
<ListRecords>
<?php foreach($publishedRecords as $record): ?>
<?php $requestname->setAttribute('informationObject', $record) ?>
<record>
<header>
<identifier><?php echo $record->getOaiIdentifier() ?></identifier>
<datestamp><?php echo QubitOai::getDate($record->getUpdatedAt())?></datestamp>
<setSpec><?php echo QubitOai::getSetSpec($record->getLft(), $collectionsTable)?></setSpec>
</header>
<metadata>
<?php echo get_component('sfDcPlugin', 'dc', array('resource' => $record)) ?>
</metadata>
</record>
<?php endforeach ?>
</ListRecords>
<?php if($remaining > 0):?>
<resumptionToken><?php echo $resumptionToken?></resumptionToken>
<?php endif?>
<?php endif?>
| <?php if($recordsCount == 0):?>
<error code="noRecordsMatch">The combination of the values of the from, until, set and metadataPrefix arguments results in an empty list.</error>
<?php else:?>
<ListRecords>
<?php foreach($publishedRecords as $record): ?>
<?php $requestname->setAttribute('informationObject', $record) ?>
<record>
<header>
<identifier><?php echo $record->getOaiIdentifier() ?></identifier>
<datestamp><?php echo QubitOai::getDate($record->getUpdatedAt())?></datestamp>
<setSpec><?php echo QubitOai::getSetSpec($record->getLft(), $collectionsTable)?></setSpec>
</header>
<metadata>
<?php echo get_component('sfDcPlugin', 'dc', array('resource' => $record)) ?>
</metadata>
</record>
<?php endforeach ?>
</ListRecords>
<?php endif?>
|
Add support to the float slider | // Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.
define([
"widgets/js/widget",
"widgets/js/widget_int",
], function(widget, int_widgets){
var IntSliderView = int_widgets.IntSliderView;
var IntTextView = int_widgets.IntTextView;
var FloatSliderView = IntSliderView.extend({
_validate_text_input: function(x) {
return parseFloat(x);
},
_validate_slide_value: function(x) {
// Validate the value of the slider before sending it to the back-end
// and applying it to the other views on the page.
return x;
},
});
var FloatTextView = IntTextView.extend({
_parse_value: function(value) {
// Parse the value stored in a string.
return parseFloat(value);
},
});
return {
'FloatSliderView': FloatSliderView,
'FloatTextView': FloatTextView,
};
});
| // Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.
define([
"widgets/js/widget",
"widgets/js/widget_int",
], function(widget, int_widgets){
var IntSliderView = int_widgets.IntSliderView;
var IntTextView = int_widgets.IntTextView;
var FloatSliderView = IntSliderView.extend({
_validate_slide_value: function(x) {
// Validate the value of the slider before sending it to the back-end
// and applying it to the other views on the page.
return x;
},
});
var FloatTextView = IntTextView.extend({
_parse_value: function(value) {
// Parse the value stored in a string.
return parseFloat(value);
},
});
return {
'FloatSliderView': FloatSliderView,
'FloatTextView': FloatTextView,
};
});
|
Remove exception used for debugging. | package bio.terra.cli.command;
import bio.terra.cli.context.GlobalContext;
import bio.terra.cli.context.WorkspaceContext;
import java.nio.file.FileAlreadyExistsException;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command;
/** This class corresponds to the second-level "terra status" command. */
@Command(name = "status", description = "Print details about the current workspace.")
public class Status implements Callable<Integer> {
private static final Logger logger = LoggerFactory.getLogger(Status.class);
@Override
public Integer call() {
GlobalContext globalContext = GlobalContext.readFromFile();
WorkspaceContext workspaceContext = WorkspaceContext.readFromFile();
System.out.println("Terra server: " + globalContext.server.name);
// check if current workspace is defined
if (workspaceContext.isEmpty()) {
System.out.println("There is no current Terra workspace defined.");
} else {
System.out.println("Terra workspace: " + workspaceContext.getWorkspaceId());
System.out.println("Google project: " + workspaceContext.getGoogleProject());
}
return 0;
}
}
| package bio.terra.cli.command;
import bio.terra.cli.context.GlobalContext;
import bio.terra.cli.context.WorkspaceContext;
import java.nio.file.FileAlreadyExistsException;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command;
/** This class corresponds to the second-level "terra status" command. */
@Command(name = "status", description = "Print details about the current workspace.")
public class Status implements Callable<Integer> {
private static final Logger logger = LoggerFactory.getLogger(Status.class);
@Override
public Integer call() throws FileAlreadyExistsException {
GlobalContext globalContext = GlobalContext.readFromFile();
WorkspaceContext workspaceContext = WorkspaceContext.readFromFile();
System.out.println("Terra server: " + globalContext.server.name);
// check if current workspace is defined
if (workspaceContext.isEmpty()) {
System.out.println("There is no current Terra workspace defined.");
} else {
System.out.println("Terra workspace: " + workspaceContext.getWorkspaceId());
System.out.println("Google project: " + workspaceContext.getGoogleProject());
}
return 0;
}
}
|
Tidy up and add comment | package com.example.rxappfocus;
import android.app.Application;
import android.widget.Toast;
import com.gramboid.rxappfocus.AppFocusProvider;
import rx.functions.Action1;
public class App extends Application {
private AppFocusProvider focusProvider;
@Override
public void onCreate() {
super.onCreate();
focusProvider = new AppFocusProvider(this);
// show a toast every time the app becomes visible or hidden
focusProvider.getAppFocus()
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean visible) {
Toast.makeText(App.this, visible ? "App visible" : "App hidden", Toast.LENGTH_SHORT).show();
}
});
}
public AppFocusProvider getFocusProvider() {
return focusProvider;
}
}
| package com.example.rxappfocus;
import android.app.Application;
import android.widget.Toast;
import com.gramboid.rxappfocus.AppFocusProvider;
import rx.functions.Action1;
public class App extends Application {
private AppFocusProvider focusProvider;
@Override
public void onCreate() {
super.onCreate();
focusProvider = new AppFocusProvider(this);
focusProvider
.getAppFocus()
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean visible) {
Toast.makeText(App.this, visible ? "App visible" : "App hidden", Toast.LENGTH_SHORT).show();
}
});
}
public AppFocusProvider getFocusProvider() {
return focusProvider;
}
}
|
Move the URL generation to a separate method | <?php
namespace duncan3dc\Proxy;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
class App
{
public function run(): void
{
$client = new Client([
"http_errors" => false,
]);
$url = $this->generateUrl();
$response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
"headers" => [
"User-Agent" => $_SERVER["HTTP_USER_AGENT"],
],
"form_params" => $_POST,
]);
$this->respond($response);
}
private function generateUrl(): string
{
return "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
}
private function respond(ResponseInterface $response): void
{
http_response_code($response->getStatusCode());
header("Content-Type: " . $response->getHeader("content-type")[0]);
echo $response->getBody();
}
}
| <?php
namespace duncan3dc\Proxy;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
class App
{
public function run(): void
{
$client = new Client([
"http_errors" => false,
]);
$url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
"headers" => [
"User-Agent" => $_SERVER["HTTP_USER_AGENT"],
],
"form_params" => $_POST,
]);
$this->respond($response);
}
private function respond(ResponseInterface $response): void
{
http_response_code($response->getStatusCode());
header("Content-Type: " . $response->getHeader("content-type")[0]);
echo $response->getBody();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.