text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Remove day of the week row | # This file copied from https://github.com/unmonoqueteclea/calendar-telegram
from telebot import types
import calendar
def create_calendar(year,month):
markup = types.InlineKeyboardMarkup()
#First row - Month and Year
row=[]
row.append(types.InlineKeyboardButton(calendar.month_name[month]+" "+str(year),callback_data="ignore"))
markup.row(*row)
my_calendar = calendar.monthcalendar(year, month)
for week in my_calendar:
row=[]
for day in week:
if(day==0):
row.append(types.InlineKeyboardButton(" ",callback_data="ignore"))
else:
row.append(types.InlineKeyboardButton(str(day),callback_data="calendar-day-"+str(day)))
markup.row(*row)
#Last row - Buttons
row=[]
row.append(types.InlineKeyboardButton("<",callback_data="previous-month"))
row.append(types.InlineKeyboardButton(" ",callback_data="ignore"))
row.append(types.InlineKeyboardButton(">",callback_data="next-month"))
markup.row(*row)
return markup | # This file copied from https://github.com/unmonoqueteclea/calendar-telegram
from telebot import types
import calendar
def create_calendar(year,month):
markup = types.InlineKeyboardMarkup()
#First row - Month and Year
row=[]
row.append(types.InlineKeyboardButton(calendar.month_name[month]+" "+str(year),callback_data="ignore"))
markup.row(*row)
#Second row - Week Days
week_days=["M","T","W","R","F","S","U"]
row=[]
for day in week_days:
row.append(types.InlineKeyboardButton(day,callback_data="ignore"))
markup.row(*row)
my_calendar = calendar.monthcalendar(year, month)
for week in my_calendar:
row=[]
for day in week:
if(day==0):
row.append(types.InlineKeyboardButton(" ",callback_data="ignore"))
else:
row.append(types.InlineKeyboardButton(str(day),callback_data="calendar-day-"+str(day)))
markup.row(*row)
#Last row - Buttons
row=[]
row.append(types.InlineKeyboardButton("<",callback_data="previous-month"))
row.append(types.InlineKeyboardButton(" ",callback_data="ignore"))
row.append(types.InlineKeyboardButton(">",callback_data="next-month"))
markup.row(*row)
return markup |
Remove contents of cluster on change
Fixes #166 | var util = require("./util"),
addLabel = require("./label/add-label");
module.exports = createClusters;
function createClusters(selection, g) {
var clusters = g.nodes().filter(function(v) { return util.isSubgraph(g, v); }),
svgClusters = selection.selectAll("g.cluster")
.data(clusters, function(v) { return v; });
svgClusters.selectAll("*").remove();
svgClusters.enter()
.append("g")
.attr("class", "cluster")
.style("opacity", 0)
.append("rect");
util.applyTransition(svgClusters.exit(), g)
.style("opacity", 0)
.remove();
util.applyTransition(svgClusters, g)
.style("opacity", 1);
svgClusters.each(function(v) {
var node = g.node(v),
thisGroup = d3.select(this),
labelGroup = thisGroup.append("g").attr("class", "label");
addLabel(labelGroup, node, node.clusterLabelPos);
});
svgClusters.selectAll("rect").each(function(c) {
var node = g.node(c);
var domCluster = d3.select(this);
util.applyStyle(domCluster, node.style);
});
}
| var util = require("./util"),
addLabel = require("./label/add-label");
module.exports = createClusters;
function createClusters(selection, g) {
var clusters = g.nodes().filter(function(v) { return util.isSubgraph(g, v); }),
svgClusters = selection.selectAll("g.cluster")
.data(clusters, function(v) { return v; });
svgClusters.enter()
.append("g")
.attr("class", "cluster")
.style("opacity", 0)
.append("rect");
util.applyTransition(svgClusters.exit(), g)
.style("opacity", 0)
.remove();
util.applyTransition(svgClusters, g)
.style("opacity", 1);
svgClusters.each(function(v) {
var node = g.node(v),
thisGroup = d3.select(this),
labelGroup = thisGroup.append("g").attr("class", "label");
addLabel(labelGroup, node, node.clusterLabelPos);
});
svgClusters.selectAll("rect").each(function(c) {
var node = g.node(c);
var domCluster = d3.select(this);
util.applyStyle(domCluster, node.style);
});
}
|
Add some jsdoc to _childDidSuspend | import { Component } from './component';
import { createElement } from './create-element';
// having a "custom class" here saves 50bytes gzipped
export function s(props) {}
s.prototype = new Component();
/**
* @param {Promise} promise The thrown promise
*/
s.prototype._childDidSuspend = function(promise) {
this.setState({ _loading: true });
const cb = () => { this.setState({ _loading: false }); };
// Suspense ignores errors thrown in Promises as this should be handled by user land code
promise.then(cb, cb);
};
s.prototype.render = function(props, state) {
return state._loading ? props.fallback : props.children;
};
// exporting s as Suspense instead of naming the class iself Suspense saves 4 bytes gzipped
// TODO: does this add the need of a displayName?
export const Suspense = s;
export function lazy(loader) {
let prom;
let component;
let error;
return function L(props) {
if (!prom) {
prom = loader();
prom.then(
({ default: c }) => { component = c; },
e => error = e,
);
}
if (error) {
throw error;
}
if (!component) {
throw prom;
}
return createElement(component, props);
};
} | import { Component } from './component';
import { createElement } from './create-element';
// having a "custom class" here saves 50bytes gzipped
export function s(props) {}
s.prototype = new Component();
s.prototype._childDidSuspend = function(e) {
this.setState({ _loading: true });
const cb = () => { this.setState({ _loading: false }); };
// Suspense ignores errors thrown in Promises as this should be handled by user land code
e.then(cb, cb);
};
s.prototype.render = function(props, state) {
return state._loading ? props.fallback : props.children;
};
// exporting s as Suspense instead of naming the class iself Suspense saves 4 bytes gzipped
// TODO: does this add the need of a displayName?
export const Suspense = s;
export function lazy(loader) {
let prom;
let component;
let error;
return function L(props) {
if (!prom) {
prom = loader();
prom.then(
({ default: c }) => { component = c; },
e => error = e,
);
}
if (error) {
throw error;
}
if (!component) {
throw prom;
}
return createElement(component, props);
};
} |
Exclude /actuator/health from the authenticated resources | package com.rbmhtechnology.apidocserver.security;
import org.mitre.openid.connect.client.OIDCAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
@Configuration
@Profile("openid")
public class OpenIdConnectSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final AuthenticationEntryPoint authenticationEntryPoint;
private final OIDCAuthenticationFilter authenticationFilter;
public OpenIdConnectSecurityConfiguration(
AuthenticationEntryPoint authenticationEntryPoint,
@Lazy OIDCAuthenticationFilter authenticationFilter) {
this.authenticationEntryPoint = authenticationEntryPoint;
this.authenticationFilter = authenticationFilter;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationFilter, AbstractPreAuthenticatedProcessingFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
.and().authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.anyRequest().authenticated();
}
}
| package com.rbmhtechnology.apidocserver.security;
import org.mitre.openid.connect.client.OIDCAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
@Configuration
@Profile("openid")
public class OpenIdConnectSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final AuthenticationEntryPoint authenticationEntryPoint;
private final OIDCAuthenticationFilter authenticationFilter;
public OpenIdConnectSecurityConfiguration(
AuthenticationEntryPoint authenticationEntryPoint,
@Lazy OIDCAuthenticationFilter authenticationFilter) {
this.authenticationEntryPoint = authenticationEntryPoint;
this.authenticationFilter = authenticationFilter;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationFilter, AbstractPreAuthenticatedProcessingFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
.and().authorizeRequests()
.antMatchers("/health").permitAll()
.anyRequest().authenticated();
}
}
|
Add 3rd parameter to addEventListener for backwards browser compatibility.
See notes in https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Syntax | //= require openseadragon
(function($) {
var __osd_counter = 0;
function generateOsdId() {
__osd_counter++;
return "Openseadragon" + __osd_counter;
}
function initOpenSeadragon() {
$('picture[data-openseadragon]').each(function() {
var $picture = $(this);
if (typeof $picture.attr('id') === "undefined") {
$picture.attr('id', generateOsdId());
}
var collectionOptions = $picture.data('openseadragon');
var sources = $picture.find('source[media="openseadragon"]');
var tilesources = $.map(sources, function(e) {
if ($(e).data('openseadragon')) {
return $(e).data('openseadragon');
} else {
return $(e).attr('src');
}
});
$picture.css("display", "block");
$picture.css("height", "500px");
$picture.data('osdViewer', OpenSeadragon(
$.extend({ id: $picture.attr('id') }, collectionOptions, { tileSources: tilesources })
));
});
};
window.onload = initOpenSeadragon;
document.addEventListener("page:load", initOpenSeadragon, false);
})(jQuery); | //= require openseadragon
(function($) {
var __osd_counter = 0;
function generateOsdId() {
__osd_counter++;
return "Openseadragon" + __osd_counter;
}
function initOpenSeadragon() {
$('picture[data-openseadragon]').each(function() {
var $picture = $(this);
if (typeof $picture.attr('id') === "undefined") {
$picture.attr('id', generateOsdId());
}
var collectionOptions = $picture.data('openseadragon');
var sources = $picture.find('source[media="openseadragon"]');
var tilesources = $.map(sources, function(e) {
if ($(e).data('openseadragon')) {
return $(e).data('openseadragon');
} else {
return $(e).attr('src');
}
});
$picture.css("display", "block");
$picture.css("height", "500px");
$picture.data('osdViewer', OpenSeadragon(
$.extend({ id: $picture.attr('id') }, collectionOptions, { tileSources: tilesources })
));
});
};
window.onload = initOpenSeadragon;
document.addEventListener("page:load", initOpenSeadragon);
})(jQuery); |
Add new API for v0.8.0 | // Import everything
import parse from './lib/parser.js'
import typeOf from 'ef-core/src/lib/utils/type-of.js'
import { mixStr } from 'ef-core/src/lib/utils/literals-mix.js'
import parseEft from 'eft-parser'
import { version } from '../package.json'
// Import core components
import {
create as createComponent,
onNextRender,
inform,
exec,
bundle,
isPaused,
mountOptions
} from 'ef-core'
// Set parser
let parser = parseEft
const create = (value) => {
const valType = typeOf(value)
if (valType === 'string') value = parse(value, parser)
else if (valType !== 'array') throw new TypeError('Cannot create new component without proper template or AST!')
return createComponent(value)
}
// Change parser
const setParser = (newParser) => {
parser = newParser
}
const t = (...args) => create(mixStr(...args))
export {
t,
create,
onNextRender,
inform,
exec,
bundle,
isPaused,
setParser,
parseEft,
mountOptions,
version
}
if (process.env.NODE_ENV !== 'production') console.info('[EF]', `ef.js v${version} initialized!`)
| // Import everything
import parse from './lib/parser.js'
import typeOf from 'ef-core/src/lib/utils/type-of.js'
import { mixStr } from 'ef-core/src/lib/utils/literals-mix.js'
import parseEft from 'eft-parser'
import { version } from '../package.json'
// Import core components
import {create as createComponent, onNextRender, inform, exec, bundle} from 'ef-core'
// Set parser
let parser = parseEft
const create = (value) => {
const valType = typeOf(value)
if (valType === 'string') value = parse(value, parser)
else if (valType !== 'array') throw new TypeError('Cannot create new component without proper template or AST!')
return createComponent(value)
}
// Change parser
const setParser = (newParser) => {
parser = newParser
}
const t = (...args) => create(mixStr(...args))
export { create, onNextRender, inform, exec, bundle, setParser, parseEft, t, version }
if (process.env.NODE_ENV !== 'production') console.info('[EF]', `ef.js v${version} initialized!`)
|
Reorder URLs, catchall at the end | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^users/new$', 'main.views.new_user', name="new_user"),
url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'),
# url(r'^checklisthq/', include('checklisthq.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^.*$', 'main.views.home', name='home'),
)
| from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^users/new$', 'main.views.new_user', name="new_user"),
url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'),
url(r'^.*$', 'main.views.home', name='home'),
# url(r'^checklisthq/', include('checklisthq.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
|
Fix bug with segment parsing | const number2ip = number => [
(number & (0xff << 24)) >>> 24,
(number & (0xff << 16)) >>> 16,
(number & (0xff << 8)) >>> 8,
number & 0xff
].join('.');
const isIP = (ip) => {
const ipArray = (ip + '').split('.');
return !(ipArray.length === 0 || ipArray.length > 4);
}
const ip2number = ip => {
const ipArray = (ip + '').split('.');
if (ipArray.length === 0 || ipArray.length > 4) {
throw new Error('Invalid IP');
return;
} else {
return ipArray
.map((segment, i) => {
if (isNaN(+segment) || segment < 0 || segment > 255) {
throw new Error('One or more segments of IP-address is invalid');
return;
}
return (segment || 0) << (8 * (3 - i));
})
.reduce((acc, cur) => acc | cur, 0) >>> 0;
}
}
module.exports = {number2ip, ip2number, isIP}; | const number2ip = number => [
(number & (0xff << 24)) >>> 24,
(number & (0xff << 16)) >>> 16,
(number & (0xff << 8)) >>> 8,
number & 0xff
].join('.');
const isIP = (ip) => {
const ipArray = (ip + '').split('.');
return !(ipArray.length === 0 || ipArray.length > 4);
}
const ip2number = ip => {
const ipArray = (ip + '').split('.');
if (ipArray.length === 0 || ipArray.length > 4) {
throw new Error('Invalid IP');
return;
} else {
return ipArray
.map((segment, i) => {
if (isNaN(parseInt(segment, 10)) || segment < 0 || segment > 255) {
throw new Error('One or more segments of IP-address is invalid');
return;
}
return (segment || 0) << (8 * (3 - i));
})
.reduce((acc, cur) => acc | cur, 0) >>> 0;
}
}
module.exports = {number2ip, ip2number, isIP}; |
Use Object.create to make it safe to mutate options hash | 'use strict';
var postcssCached = require('postcss-cached');
var through = require('through2');
var applySourceMap = require('vinyl-sourcemaps-apply');
var gulpUtil = require('gulp-util');
module.exports = function(options) {
options = Object(options);
var postcssCachedInstance = postcssCached();
var gulpPlugin = through.obj(function(file, encoding, callback) {
var fileOptions = Object.create(options);
fileOptions.from = file.path;
fileOptions.map = fileOptions.map || file.sourceMap;
try {
var result = postcssCachedInstance
.process(file.contents.toString('utf8'), fileOptions);
file.contents = new Buffer(result.css);
if (fileOptions.map) {
applySourceMap(file, result.map);
}
this.push(file);
callback();
} catch(e) {
callback(new gulpUtil.PluginError('gulp-postcss-cached', e));
}
});
gulpPlugin.use = function(postcssPlugin) {
postcssCachedInstance.use(postcssPlugin);
return this;
};
return gulpPlugin;
};
| 'use strict';
var postcssCached = require('postcss-cached');
var through = require('through2');
var applySourceMap = require('vinyl-sourcemaps-apply');
var gulpUtil = require('gulp-util');
module.exports = function(options) {
options = Object(options);
var postcssCachedInstance = postcssCached();
var gulpPlugin = through.obj(function(file, encoding, callback) {
var fileOptions = Object(options);
fileOptions.from = file.path;
fileOptions.map = fileOptions.map || file.sourceMap;
try {
var result = postcssCachedInstance
.process(file.contents.toString('utf8'), fileOptions);
file.contents = new Buffer(result.css);
if (fileOptions.map) {
applySourceMap(file, result.map);
}
this.push(file);
callback();
} catch(e) {
callback(new gulpUtil.PluginError('gulp-postcss-cached', e));
}
});
gulpPlugin.use = function(postcssPlugin) {
postcssCachedInstance.use(postcssPlugin);
return this;
};
return gulpPlugin;
};
|
Fix login JS files not being output to right dir | var browserify = require('browserify');
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var gutil = require('gulp-util');
var pump = require('pump');
function react_browserify(infile, outfile, outdir, debug) {
outfile = (outfile === undefined) ? infile : outfile;
outdir = (outdir === undefined) ? 'static/js' : outdir;
debug = (debug === undefined) ? false : debug;
var b = browserify('client-js/'+infile+'.jsx', {transform: 'babelify', debug:true});
b = watchify(b);
function bundlefn(cb) {
pump([
b.bundle(),
source(outfile+'.js'),
debug ? gutil.noop() : streamify(uglify()),
gulp.dest(outdir)
], cb);
}
b.on('update', bundlefn);
b.on('log', gutil.log);
return bundlefn;
}
gulp.task('build-login', react_browserify('login', 'login', 'public/js'));
gulp.task('build-inventory', react_browserify('inventory'));
gulp.task('build-users', react_browserify('users'));
gulp.task('build-nav', react_browserify('CommonNav', 'navbar'));
gulp.task('build', ['build-login', 'build-inventory', 'build-users', 'build-nav']);
| var browserify = require('browserify');
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var gutil = require('gulp-util');
var pump = require('pump');
function react_browserify(infile, outfile, debug) {
outfile = (outfile === undefined) ? infile : outfile;
debug = (debug === undefined) ? false : debug;
var b = browserify('client-js/'+infile+'.jsx', {transform: 'babelify', debug:true});
b = watchify(b);
function bundlefn(cb) {
pump([
b.bundle(),
source(outfile+'.js'),
debug ? gutil.noop() : streamify(uglify()),
gulp.dest('static/js')
], cb);
}
b.on('update', bundlefn);
b.on('log', gutil.log);
return bundlefn;
}
gulp.task('build-login', react_browserify('login'));
gulp.task('build-inventory', react_browserify('inventory'));
gulp.task('build-users', react_browserify('users'));
gulp.task('build-nav', react_browserify('CommonNav', 'navbar'));
gulp.task('build', ['build-login', 'build-inventory', 'build-users', 'build-nav']);
|
Change description message on internal migration
First step to address #258 | <?php declare(strict_types = 1);
namespace PharIo\Phive;
use PharIo\FileSystem\Filename;
class HomePharsXmlMigration extends InternalFileMigration {
public function __construct(Config $config) {
parent::__construct(
$config->getHomeDirectory()->file('phars.xml'),
$config->getRegistry()
);
}
public function mustMigrate(): bool {
return true;
}
public function getDescription(): string {
return 'Rename internal storage file from `phars.xml` to `registry.xml`.';
}
protected function doMigrate(Filename $legacy, Filename $new): void {
$new->putContent($legacy->read()->getContent());
}
}
| <?php declare(strict_types = 1);
namespace PharIo\Phive;
use PharIo\FileSystem\Filename;
class HomePharsXmlMigration extends InternalFileMigration {
public function __construct(Config $config) {
parent::__construct(
$config->getHomeDirectory()->file('phars.xml'),
$config->getRegistry()
);
}
public function mustMigrate(): bool {
return true;
}
public function getDescription(): string {
return 'Change the name of the list of all installed Phars file.';
}
protected function doMigrate(Filename $legacy, Filename $new): void {
$new->putContent($legacy->read()->getContent());
}
protected function getFileDescription(): string {
return 'list of installed phars';
}
}
|
Move Timber class check to the top of the file
The check is supossed to happen before the attempt to use. Also this
way the error message displays as it should. | <?php
use Roots\Sage\Setup;
/**
* Check if Timber is activated
*/
if ( ! class_exists( 'Timber' ) ) {
add_action( 'admin_notices', function() {
echo '<div class="error"><p>Timber not activated. Make sure you activate the plugin in <a href="' . esc_url( admin_url( 'plugins.php#timber' ) ) . '">' . esc_url( admin_url( 'plugins.php' ) ) . '</a></p></div>';
} );
return;
}
/**
* Timber
*/
class TwigSageTheme extends TimberSite {
function __construct() {
add_filter( 'timber_context', array( $this, 'add_to_context' ) );
parent::__construct();
}
function add_to_context( $context ) {
/* Add extra data */
$context['foo'] = 'I am some other typical value set in your functions.php file, unrelated to the menu';
/* Menu */
$context['menu'] = new TimberMenu('primary_navigation');
/* Site info */
$context['site'] = $this;
/* Site info */
$context['display_sidebar'] = Setup\display_sidebar();
$context['sidebar_primary'] = Timber::get_widgets('sidebar-primary');
return $context;
}
}
new TwigSageTheme();
| <?php
use Roots\Sage\Setup;
/**
* Timber
*/
class TwigSageTheme extends TimberSite {
function __construct() {
add_filter( 'timber_context', array( $this, 'add_to_context' ) );
parent::__construct();
}
function add_to_context( $context ) {
/* Add extra data */
$context['foo'] = 'I am some other typical value set in your functions.php file, unrelated to the menu';
/* Menu */
$context['menu'] = new TimberMenu('primary_navigation');
/* Site info */
$context['site'] = $this;
/* Site info */
$context['display_sidebar'] = Setup\display_sidebar();
$context['sidebar_primary'] = Timber::get_widgets('sidebar-primary');
return $context;
}
}
new TwigSageTheme();
/**
* Timber
*
* Check if Timber is activated
*/
if ( ! class_exists( 'Timber' ) ) {
add_action( 'admin_notices', function() {
echo '<div class="error"><p>Timber not activated. Make sure you activate the plugin in <a href="' . esc_url( admin_url( 'plugins.php#timber' ) ) . '">' . esc_url( admin_url( 'plugins.php' ) ) . '</a></p></div>';
} );
return;
} |
Swap deprecation warnings for deprecation | /*
* #%L
* Simmetrics Core
* %%
* Copyright (C) 2014 - 2015 Simmetrics Authors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by 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.
* #L%
*/
package org.simmetrics.tokenizers;
import org.simmetrics.tokenizers.Tokenizer;
@SuppressWarnings("javadoc")
@Deprecated
public class WhitespaceTokenizerTest extends TokenizerTest {
@Override
protected Tokenizer getTokenizer() {
return new Whitespace();
}
@Override
protected T[] getTests() {
return new T[] {
new T(""),
new T(" "),
new T(" A","A"),
new T("A B C", "A", "B", "C"),
new T("A B C", "A", "B", "C"),
new T("A\nB", "A", "B"),
new T("A\tB", "A", "B"),
new T("A\t\nB", "A", "B"),
};
}
}
| /*
* #%L
* Simmetrics Core
* %%
* Copyright (C) 2014 - 2015 Simmetrics Authors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by 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.
* #L%
*/
package org.simmetrics.tokenizers;
import org.simmetrics.tokenizers.Tokenizer;
@SuppressWarnings({"javadoc","deprecation"})
public class WhitespaceTokenizerTest extends TokenizerTest {
@Override
protected Tokenizer getTokenizer() {
return new Whitespace();
}
@Override
protected T[] getTests() {
return new T[] {
new T(""),
new T(" "),
new T(" A","A"),
new T("A B C", "A", "B", "C"),
new T("A B C", "A", "B", "C"),
new T("A\nB", "A", "B"),
new T("A\tB", "A", "B"),
new T("A\t\nB", "A", "B"),
};
}
}
|
Add way to notify the task when finished. | var fs = require('fs');
var lodash = require('lodash');
var path = require('path');
var package = require(path.join(process.cwd(), 'package.json'));
var initDir = path.join(__dirname, '..', 'init');
var files = [
'src/index.js',
'src/version.js',
'.editorconfig',
'.eslintignore',
'.eslintrc',
'.gitignore',
'.gulprc',
'.travis.yml',
'README.md',
'bower.json',
'gulpfile.js'
];
module.exports = function (done) {
var finished = 1;
function doneify () {
finished++
if (finished === files.length) {
done();
}
}
files.forEach(function (file, idx) {
var src = path.join(initDir, file)
var dst = path.join(process.cwd(), file);
fs.readFile(src, function (err, content) {
fs.exists(dst, function (exists) {
if (exists) {
doneify();
} else {
fs.writeFile(dst, lodash.template(content)(package), doneify);
}
});
});
});
};
| var fs = require('fs');
var lodash = require('lodash');
var path = require('path');
var package = require(path.join(process.cwd(), 'package.json'));
var initDir = path.join(__dirname, '..', 'init');
var files = [
'src/index.js',
'src/version.js',
'.editorconfig',
'.eslintignore',
'.eslintrc',
'.gitignore',
'.gulprc',
'.travis.yml',
'README.md',
'bower.json',
'gulpfile.js'
];
module.exports = function () {
files.forEach(function (file, idx) {
var src = path.join(initDir, file)
var dst = path.join(process.cwd(), file);
fs.readFile(src, function (err, content) {
fs.exists(dst, function (exists) {
if (!exists) {
fs.writeFile(dst, replace(content, package));
}
});
});
});
};
|
Support to specify the valid external network name
In some deployments, the retrieved external network by the
def get_external_networks in Snaps checked by "router:external"
is not available. So it is necessary to specify the available
external network as an env by user.
Change-Id: I333e91dd106ed307541a9a197280199fde86bd30
Signed-off-by: Linda Wang <81613bebe84fa394bbc7c5cc1c21989c9bff2c52@huawei.com> | # Copyright (c) 2015 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
from functest.utils.constants import CONST
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the configured external network name or
the first retrieved external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
if (hasattr(CONST, 'EXTERNAL_NETWORK')):
extnet_config = CONST.__getattribute__('EXTERNAL_NETWORK')
for ext_net in ext_nets:
if ext_net.name == extnet_config:
return extnet_config
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
| # Copyright (c) 2015 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the first external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
|
Trim the output of vagrantFile.php to get rid of stray new line at the end | <?php
use Jalle19\VagrantRegistryGenerator\Registry\Manifest\Provider;
/* @var Provider $provider */
/* @var string $boxName */
/* @var string $manifestUrl */
?>
<div class="provider">
<?php
if ($provider->hasMetadata()) {
$metadata = $provider->getFileMetadata();
?>
<div class="fileMetadata">
<span class="fileName"><?php echo $metadata->getFileName(); ?></span>
<span class="fileSize"><?php echo (int)($metadata->getSize() / 1024 / 1024); ?> MiB</span>
<span class="lastModified"><?php echo $metadata->getTimestamp()->format('c'); ?></span>
</div>
<?php
}
?>
<pre class="vagrantFile">
<?php echo trim($this->fetch('vagrantFile', [
'boxName' => $boxName,
'provider' => $provider->getName(),
'manifestUrl' => $manifestUrl,
])); ?>
</pre>
</div>
| <?php
use Jalle19\VagrantRegistryGenerator\Registry\Manifest\Provider;
/* @var Provider $provider */
/* @var string $boxName */
/* @var string $manifestUrl */
?>
<div class="provider">
<?php
if ($provider->hasMetadata()) {
$metadata = $provider->getFileMetadata();
?>
<div class="fileMetadata">
<span class="fileName"><?php echo $metadata->getFileName(); ?></span>
<span class="fileSize"><?php echo (int)($metadata->getSize() / 1024 / 1024); ?> MiB</span>
<span class="lastModified"><?php echo $metadata->getTimestamp()->format('c'); ?></span>
</div>
<?php
}
?>
<pre class="vagrantFile">
<?php $this->insert('vagrantFile', [
'boxName' => $boxName,
'provider' => $provider->getName(),
'manifestUrl' => $manifestUrl,
]); ?>
</pre>
</div>
|
Add default to movement date | from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
@python_2_unicode_compatible
class Tag(models.Model):
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.slug
@python_2_unicode_compatible
class Wallet(models.Model):
CURRENCIES = (
("EUR", "EUR"),
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
label = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)
def __str__(self):
return "{} ({})".format(self.label, self.currency)
@python_2_unicode_compatible
class Movement(models.Model):
wallet = models.ForeignKey(Wallet, related_name="movements")
date = models.DateTimeField(default=timezone.now())
amount = models.DecimalField(max_digits=11, decimal_places=2)
tags = models.ManyToManyField(Tag, related_name="movements")
def __str__(self):
return "{} - {:.2f} for {} on {}".format(
self.type, self.amount, self.wallet, self.date)
| from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
@python_2_unicode_compatible
class Tag(models.Model):
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.slug
@python_2_unicode_compatible
class Wallet(models.Model):
CURRENCIES = (
("EUR", "EUR"),
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
label = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)
def __str__(self):
return "{} ({})".format(self.label, self.currency)
@python_2_unicode_compatible
class Movement(models.Model):
wallet = models.ForeignKey(Wallet, related_name="movements")
date = models.DateTimeField()
amount = models.DecimalField(max_digits=11, decimal_places=2)
tags = models.ManyToManyField(Tag, related_name="movements")
def __str__(self):
return "{} - {:.2f} for {} on {}".format(
self.type, self.amount, self.wallet, self.date)
|
Fix crash when using default folder |
var Router = require('routes');
var router = new Router();
var st = require('st');
var fs = require('fs');
var mount = st({
path: __dirname + '/static/', // resolved against the process cwd
url: 'boot/', // defaults to '/'
// indexing options
index: 'index', // auto-index, the default
dot: false // default: return 403 for any url with a dot-file part
});
router.addRoute('/chain', function(req, res, params, splats) {
console.log("Got a CHAIN request");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("#!ipxe\n\necho Attempting to boot into the chain... \nchain http://${next-server}/boot/${mac}\n");
});
router.addRoute('/boot/:macaddr', function boot(req, res, params, splats) {
console.log("Got a BOOT request");
console.log("Just got word that "+params.params.macaddr+" just booted");
try {
var stat = fs.statSync(__dirname + '/static/' + params.params.macaddr);
} catch (error){
if(error.code != 'ENOENT')
throw error;
}
if(stat && stat.isDirectory()){
mount(req, res);
} else {
req.url = '/boot/default';
mount(req, res);
}
});
module.exports = router;
|
var Router = require('routes');
var router = new Router();
var st = require('st');
var fs = require('fs');
var mount = st({
path: __dirname + '/static/', // resolved against the process cwd
url: 'boot/', // defaults to '/'
// indexing options
index: 'index', // auto-index, the default
dot: false // default: return 403 for any url with a dot-file part
});
router.addRoute('/chain', function(req, res, params, splats) {
console.log("Got a CHAIN request");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("#!ipxe\n\necho Attempting to boot into the chain... \nchain http://${next-server}/boot/${mac}\n");
});
router.addRoute('/boot/:macaddr', function boot(req, res, params, splats) {
console.log("Got a BOOT request");
console.log("Just got word that "+params.params.macaddr+" just booted");
var stat = fs.statSync(__dirname + '/static/' + params.params.macaddr);
if(stat && stat.isDirectory()){
mount(req, res);
} else {
req.url = '/boot/default';
mount(req, res);
}
});
module.exports = router;
|
Join _modsquad channel (my personal config) | ChatConfig = {
join: ["uidev"],
leave: [],
hideDeathSpam: false,
autoexec: [
"/closeui perfhud",
"jumpdelay 0",
"/sleep 1000",
"/openui mehuge-lb",
"/openui mehuge-heatmap",
"/openui mehuge-perf",
"/openui mehuge-pop",
"/openui mehuge-bct",
"/openui mehuge-announcer",
"/openui mehuge-deathspam",
"/openui mehuge-loc",
"/openui mehuge-group",
"/openui mehuge-combatlog",
"/openui castbar",
"/openui ortu-compass",
"/join _modsquad",
]
};
| ChatConfig = {
join: ["uidev"],
leave: [],
hideDeathSpam: false,
autoexec: [
"/closeui perfhud",
"jumpdelay 0",
"/sleep 1000",
"/openui mehuge-lb",
"/openui mehuge-heatmap",
"/openui mehuge-perf",
"/openui mehuge-pop",
"/openui mehuge-bct",
"/openui mehuge-announcer",
"/openui mehuge-deathspam",
"/openui mehuge-loc",
"/openui mehuge-group",
"/openui mehuge-combatlog",
"/openui castbar",
"/openui ortu-compass"
]
};
|
tests/api: Add support for passing json keyword arguments to request methods | import pytest
from werkzeug.datastructures import Headers
from flask import Response, json
from flask.testing import FlaskClient
import config
from skylines import create_api_app
@pytest.fixture(scope="session")
def app():
"""Set up global front-end app for functional tests
Initialized once per test-run
"""
app = create_api_app(config.TESTING_CONF_PATH)
app.test_client_class = ApiClient
app.response_class = ApiResponse
return app
class ApiClient(FlaskClient):
def open(self, *args, **kwargs):
headers = kwargs.pop('headers', Headers())
headers.setdefault('User-Agent', 'py.test')
kwargs['headers'] = headers
json_data = kwargs.pop('json', None)
if json_data is not None:
kwargs['data'] = json.dumps(json_data)
kwargs['content_type'] = 'application/json'
return super(ApiClient, self).open(*args, **kwargs)
class ApiResponse(Response):
@property
def json(self):
return json.loads(self.data)
@pytest.yield_fixture
def client(app):
with app.test_client(use_cookies=False) as client:
yield client
| import pytest
from werkzeug.datastructures import Headers
from flask import Response, json
from flask.testing import FlaskClient
import config
from skylines import create_api_app
@pytest.fixture(scope="session")
def app():
"""Set up global front-end app for functional tests
Initialized once per test-run
"""
app = create_api_app(config.TESTING_CONF_PATH)
app.test_client_class = ApiClient
app.response_class = ApiResponse
return app
class ApiClient(FlaskClient):
def open(self, *args, **kwargs):
headers = kwargs.pop('headers', Headers())
headers.setdefault('User-Agent', 'py.test')
kwargs['headers'] = headers
return super(ApiClient, self).open(*args, **kwargs)
class ApiResponse(Response):
@property
def json(self):
return json.loads(self.data)
@pytest.yield_fixture
def client(app):
with app.test_client(use_cookies=False) as client:
yield client
|
Set the version for testing. | <?php
/**
* The main Slimdown namespace.
*/
namespace Slimdown;
class Slimdown {
/**
* The config object.
* @var \Slimdown\Config
*/
protected static $config;
/**
* Application version.
*/
const VERSION = '0.1.0';
/**
* Sets and retrieves global configuration.
*
* If called with a block, the config object will be passed to the block and
* allow settings to be modified.
*
* \Slimdown\Slimdown::config(function($config) {
* $config->set_location('pages');
* }
*
* The settings object is always returned.
*
* @param callable $block Anonymous function to call with config object.
* @return \Slimdown\Config Object with configuration params.
*/
public static function config(\Closure $block = null) {
if (!self::$config) {
self::$config = new \Slimdown\Config();
}
// Allow configuration via a block.
if ($block) {
$block(self::$config);
}
return self::$config;
}
}
| <?php
/**
* The main Slimdown namespace.
*/
namespace Slimdown;
class Slimdown {
/**
* The config object.
* @var \Slimdown\Config
*/
protected static $config;
/**
* Application version.
*/
const VERSION = '1.0.0';
/**
* Sets and retrieves global configuration.
*
* If called with a block, the config object will be passed to the block and
* allow settings to be modified.
*
* \Slimdown\Slimdown::config(function($config) {
* $config->set_location('pages');
* }
*
* The settings object is always returned.
*
* @param callable $block Anonymous function to call with config object.
* @return \Slimdown\Config Object with configuration params.
*/
public static function config(\Closure $block = null) {
if (!self::$config) {
self::$config = new \Slimdown\Config();
}
// Allow configuration via a block.
if ($block) {
$block(self::$config);
}
return self::$config;
}
}
|
qa: Remove race between connecting and shutdown on separate connections | #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy, wait_until
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
# Force connection establishment by executing a dummy command.
node.getblockcount()
Thread(target=test_long_call, args=(node,)).start()
# Wait until the server is executing the above `waitfornewblock`.
wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2)
# Wait 1 second after requesting shutdown but not before the `stop` call
# finishes. This is to ensure event loop waits for current connections
# to close.
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
| #!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
Thread(target=test_long_call, args=(node,)).start()
# wait 1 second to ensure event loop waits for current connections to close
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
|
FIX Import RunBuildTaskJob namespace to fix undefined class error | <?php
use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Jobs\RunBuildTaskJob;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;
/**
* These nightly updates can clean up anything that might have been missed by the other tasks
*/
class NightlyUpdatesCron implements CronTask
{
/**
* Run at 1am every morning
*
* @return string
*/
public function getSchedule()
{
return "0 1 * * *";
}
/**
* Run the build task to update addons
* @return void
*/
public function process()
{
$taskClasses = [
[BuildAddonsTask::class, null], // rebuild all addons
];
foreach ($taskClasses as $taskInfo) {
list($taskClass, $taskQuerystring) = $taskInfo;
$job = new RunBuildTaskJob($taskClass, $taskQuerystring);
$jobID = Injector::inst()->get(QueuedJobService::class)->queueJob($job);
echo 'Added ' . $taskClass . ' to job queue (job ID ' . $jobID . ")\n";
}
}
}
| <?php
use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;
/**
* These nightly updates can clean up anything that might have been missed by the other tasks
*/
class NightlyUpdatesCron implements CronTask
{
/**
* Run at 1am every morning
*
* @return string
*/
public function getSchedule()
{
return "0 1 * * *";
}
/**
* Run the build task to update addons
* @return void
*/
public function process()
{
$taskClasses = [
[BuildAddonsTask::class, null], // rebuild all addons
];
foreach ($taskClasses as $taskInfo) {
list($taskClass, $taskQuerystring) = $taskInfo;
$job = new RunBuildTaskJob($taskClass, $taskQuerystring);
$jobID = Injector::inst()->get(QueuedJobService::class)->queueJob($job);
echo 'Added ' . $taskClass . ' to job queue (job ID ' . $jobID . ")\n";
}
}
}
|
Add `style` method for custom style | // Stringify styles
function stringify(style) {
if (typeof style === 'string') {
return style
}
return Object.keys(style)
.map(key => {
return `${key}:${style[key]}`
})
.join(';')
}
function cholk(text) {
return {
style: stringify(cholk._style),
text,
}
}
cholk._style = {}
cholk.log = (...args) => {
const results = []
const styles = []
args.forEach(arg => {
if (typeof arg === 'object' && arg.style) {
results.push(`%c${arg.text}`)
styles.push(arg.style)
} else {
results.push(`%c${arg}`)
styles.push('')
}
})
console.log(results.join(''), ...styles)
}
const proto = Object.create(null)
// Add common colors
const colors = ['red', 'blue', 'green']
const properties = colors.reduce((props, color) => {
props[color] = {
get() {
cholk._style.color = color
return cholk
},
}
return props
}, {})
// Custom style
proto.style = styleString => {
cholk._style = styleString
return cholk
}
Object.defineProperties(proto, properties)
cholk.__proto__ = proto
export default cholk
| const colors = ['red', 'blue', 'green']
// Stringify styles
function stringify(obj) {
return Object.keys(obj)
.map(key => {
return `${key}:${obj[key]}`
})
.join(';')
}
function cholk(text) {
return {
style: cholk._style,
text,
}
}
cholk._style = {}
cholk.log = (...args) => {
const results = []
const styles = []
args.forEach(arg => {
if (typeof arg === 'object' && arg.style) {
results.push(`%c${arg.text}`)
styles.push(stringify(arg.style))
} else {
results.push(`%c${arg}`)
styles.push('')
}
})
console.log(results.join(''), ...styles)
}
const proto = Object.create(null)
const properties = colors.reduce((props, color) => {
props[color] = {
get() {
cholk._style.color = color
return cholk
},
}
return props
}, {})
Object.defineProperties(proto, properties)
cholk.__proto__ = proto
export default cholk
|
Use current date and time as version number | # coding: utf-8
"""
Plotting and analysis tools for the ARTIS 3D supernova radiative transfer code.
"""
import datetime
import os
from setuptools import find_packages, setup
print(datetime.datetime.now().isoformat())
setup(name="artistools",
version=datetime.datetime.now().isoformat(),
author="Luke Shingles",
author_email="luke.shingles@gmail.com",
packages=find_packages(),
url="https://www.github.com/lukeshingles/artis-tools/",
license="MIT",
description="Plotting and analysis tools for the ARTIS 3D supernova radiative transfer code.",
long_description=open(os.path.join(os.path.dirname(__file__), "README.md")).read(),
install_requires=open(os.path.join(os.path.dirname(__file__), "requirements.txt")).read(),
python_requires='>==3.6',
# test_suite='tests',
setup_requires=['pytest-runner', 'pytest-cov'],
tests_require=['pytest', 'pytest-runner', 'pytest-cov'],)
| # coding: utf-8
"""
Plotting and analysis tools for the ARTIS 3D supernova radiative transfer code.
"""
import os
from setuptools import find_packages, setup
setup(name="artistools",
version=0.1,
author="Luke Shingles",
author_email="luke.shingles@gmail.com",
packages=find_packages(),
url="https://www.github.com/lukeshingles/artis-tools/",
license="MIT",
description="Plotting and analysis tools for the ARTIS 3D supernova radiative transfer code.",
long_description=open(os.path.join(os.path.dirname(__file__), "README.md")).read(),
install_requires=open(os.path.join(os.path.dirname(__file__), "requirements.txt")).read(),
python_requires='>==3.6',
# test_suite='tests',
setup_requires=['pytest-runner', 'pytest-cov'],
tests_require=['pytest', 'pytest-runner', 'pytest-cov'],)
|
Fix output, now properly reports part 2 | let data = "1113222113";
function sameHead(input, startAt) {
let firstChar = input.charAt(startAt);
let howMany = 1;
for (let i = startAt + 1; i < input.length; i++) { // Skip first letter b/c already in accumulate
if (firstChar === input.charAt(i)) {
howMany++;
} else {
break;
}
}
return howMany;
}
function applyOperation(input) {
let result = "";
let summativeHeadLength = 0;
while (summativeHeadLength < input.length) {
const howMany = sameHead(input, summativeHeadLength);
result += howMany + input.charAt(summativeHeadLength);
summativeHeadLength += howMany;
}
return result;
}
let currentData = data;
for (let i = 1; i <= 50; i++) {
currentData = applyOperation(currentData);
if (i == 40) console.log("Part 1:", currentData.length);
if (i == 50) console.log("Part 2:", currentData.length);
}
| let data = "1113222113";
function sameHead(input, startAt) {
let firstChar = input.charAt(startAt);
let howMany = 1;
for (let i = startAt + 1; i < input.length; i++) { // Skip first letter b/c already in accumulate
if (firstChar === input.charAt(i)) {
howMany++;
} else {
break;
}
}
return howMany;
}
function applyOperation(input) {
let result = "";
let summativeHeadLength = 0;
while (summativeHeadLength < input.length) {
const howMany = sameHead(input, summativeHeadLength);
result += howMany + input.charAt(summativeHeadLength);
summativeHeadLength += howMany;
}
return result;
}
let currentData = data;
for (let i = 1; i <= 50; i++) {
currentData = applyOperation(currentData);
if (i == 40) console.log("Part 1:", currentData.length);
if (i == 50) console.log("Part 1:", currentData.length);
}
|
Use YAML params instead of XML params | # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package.
class CountryTaxBenefitSystem(TaxBenefitSystem):
def __init__(self):
# We initialize our tax and benefit system with the general constructor
super(CountryTaxBenefitSystem, self).__init__(entities.entities)
# We add to our tax and benefit system all the variables
self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables'))
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
param_path = os.path.join(COUNTRY_DIR, 'parameters')
self.add_legislation_params(param_path)
| # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package.
class CountryTaxBenefitSystem(TaxBenefitSystem):
def __init__(self):
# We initialize our tax and benefit system with the general constructor
super(CountryTaxBenefitSystem, self).__init__(entities.entities)
# We add to our tax and benefit system all the variables
self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables'))
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
param_files = [
'__root__.xml',
'benefits.xml',
'general.xml',
'taxes.xml',
]
for param_file in param_files:
param_path = os.path.join(COUNTRY_DIR, 'parameters', param_file)
self.add_legislation_params(param_path)
|
Add title to e2e screen for testing purposes | const React = require('react');
const { Component } = require('react');
const { View, Button } = require('react-native');
const { Navigation } = require('react-native-navigation');
const testIDs = require('../../testIDs');
class BottomTabSideMenuScreen extends Component {
static get options() {
return {
topBar: {
title: {
text: 'test',
}
}
}
}
onOpenSideMenuPress = () => {
Navigation.mergeOptions(this.props.componentId, {
sideMenu: {
left: {
visible: true
}
}
});
}
render() {
return (
<View style={styles.root}>
<Button
title="Open SideMenu"
color="blue"
onPress={this.onOpenSideMenuPress}
testID={testIDs.OPEN_SIDE_MENU}
/>
</View>
);
}
}
module.exports = BottomTabSideMenuScreen;
const styles = {
root: {
flexGrow: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5fcff'
}
};
| const React = require('react');
const { Component } = require('react');
const { View, Button } = require('react-native');
const { Navigation } = require('react-native-navigation');
const testIDs = require('../../testIDs');
class BottomTabSideMenuScreen extends Component {
onOpenSideMenuPress = () => {
Navigation.mergeOptions(this.props.componentId, {
sideMenu: {
left: {
visible: true
}
}
});
}
render() {
return (
<View style={styles.root}>
<Button
title="Open SideMenu"
color="blue"
onPress={this.onOpenSideMenuPress}
testID={testIDs.OPEN_SIDE_MENU}
/>
</View>
);
}
}
module.exports = BottomTabSideMenuScreen;
const styles = {
root: {
flexGrow: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5fcff'
}
};
|
tests/thread: Make stack-size test run correctly and reliable on uPy. | # test setting the thread stack size
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import sys
import _thread
# different implementations have different minimum sizes
if sys.implementation.name == 'micropython':
sz = 2 * 1024
else:
sz = 32 * 1024
def foo():
pass
def thread_entry():
foo()
with lock:
global n_finished
n_finished += 1
# reset stack size to default
_thread.stack_size()
# test set/get of stack size
print(_thread.stack_size())
print(_thread.stack_size(sz))
print(_thread.stack_size() == sz)
print(_thread.stack_size())
lock = _thread.allocate_lock()
n_thread = 2
n_finished = 0
# set stack size and spawn a few threads
_thread.stack_size(sz)
for i in range(n_thread):
_thread.start_new_thread(thread_entry, ())
# busy wait for threads to finish
while n_finished < n_thread:
pass
print('done')
| # test setting the thread stack size
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import sys
import _thread
# different implementations have different minimum sizes
if sys.implementation == 'micropython':
sz = 2 * 1024
else:
sz = 32 * 1024
def foo():
pass
def thread_entry():
foo()
with lock:
global n_finished
n_finished += 1
# test set/get of stack size
print(_thread.stack_size())
print(_thread.stack_size(sz))
print(_thread.stack_size() == sz)
print(_thread.stack_size())
lock = _thread.allocate_lock()
n_thread = 2
n_finished = 0
# set stack size and spawn a few threads
_thread.stack_size(sz)
for i in range(n_thread):
_thread.start_new_thread(thread_entry, ())
# busy wait for threads to finish
while n_finished < n_thread:
pass
print('done')
|
Revert deprecated function to support PHP 7.3 | <?php
namespace Illuminate\Http\Client;
class RequestException extends HttpClientException
{
/**
* The response instance.
*
* @var \Illuminate\Http\Client\Response
*/
public $response;
/**
* Create a new exception instance.
*
* @param \Illuminate\Http\Client\Response $response
* @return void
*/
public function __construct(Response $response)
{
parent::__construct($this->prepareMessage($response), $response->status());
$this->response = $response;
}
/**
* Prepare the exception message.
*
* @param \Illuminate\Http\Client\Response $response
* @return string
*/
protected function prepareMessage(Response $response)
{
$message = "HTTP request returned status code {$response->status()}";
$summary = \GuzzleHttp\Psr7\get_message_body_summary($response->toPsrResponse());
return is_null($summary) ? $message : $message .= ":\n{$summary}\n";
}
}
| <?php
namespace Illuminate\Http\Client;
use GuzzleHttp\Psr7\Message;
class RequestException extends HttpClientException
{
/**
* The response instance.
*
* @var \Illuminate\Http\Client\Response
*/
public $response;
/**
* Create a new exception instance.
*
* @param \Illuminate\Http\Client\Response $response
* @return void
*/
public function __construct(Response $response)
{
parent::__construct($this->prepareMessage($response), $response->status());
$this->response = $response;
}
/**
* Prepare the exception message.
*
* @param \Illuminate\Http\Client\Response $response
* @return string
*/
protected function prepareMessage(Response $response)
{
$message = "HTTP request returned status code {$response->status()}";
$summary = Message::bodySummary($response->toPsrResponse());
return is_null($summary) ? $message : $message .= ":\n{$summary}\n";
}
}
|
Fix path uniformization in backup | <?php
namespace Isaac\Services\Filesystem;
use League\Flysystem\Plugin\AbstractPlugin;
use League\Flysystem\Util;
/**
* Grants the ability to copy a directory in its entirety.
*/
class CopyDirectory extends AbstractPlugin
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod()
{
return 'copyDirectory';
}
/**
* Copies a directory someplace else.
*
* @param string $from
* @param string $to
*/
public function handle(string $from, string $to)
{
// Unify slashes
$from = Util::normalizePath($from);
$to = Util::normalizePath($to);
$contents = $this->filesystem->listContents($from, true);
foreach ($contents as $file) {
$destination = str_replace($from, $to, $file['path']);
if ($file['type'] === 'file') {
$this->filesystem->copy($file['path'], $destination);
} else {
$this->filesystem->createDir($destination);
}
}
}
}
| <?php
namespace Isaac\Services\Filesystem;
use League\Flysystem\Plugin\AbstractPlugin;
/**
* Grants the ability to copy a directory in its entirety.
*/
class CopyDirectory extends AbstractPlugin
{
/**
* Get the method name.
*
* @return string
*/
public function getMethod()
{
return 'copyDirectory';
}
/**
* Copies a directory someplace else.
*
* @param string $from
* @param string $to
*/
public function handle(string $from, string $to)
{
// Unify slashes
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$contents = $this->filesystem->listContents($from, true);
foreach ($contents as $file) {
$destination = str_replace($from, $to, $file['path']);
if ($file['type'] === 'file') {
$this->filesystem->forceCopy($file['path'], $destination);
} else {
$this->filesystem->createDir($destination);
}
}
}
}
|
Add default images for podcasts if necessary | import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
if re.search('podcast', filename):
if re.search('^hero: ', contents[6]):
print filename
contents.insert(6, 'hero: /blog/images/category/podcasts.jpg\n')
f = file.open(filename, "w")
f.write("".join(contents))
f.close()
| import os, re, requests
rootdir = '_posts'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filename = os.path.join(subdir, file)
f = open(filename, "r")
contents = f.readlines()
f.close()
# Find first image
for key, line in enumerate(contents):
src = re.search('\!\[.*?\]\((.*?)\)', line)
if src:
wordpress_src = re.search('/blog/images/wordpress/(.*)', src.group(1))
if wordpress_src:
image_src = wordpress_src.group(1)
path = 'images/wordpress/'+image_src
print 'Retrieving ' + path + '...'
if not os.path.isfile(path):
print path
f = open(path, "w")
f.write(requests.get("http://blog.stackoverflow.com/wp-content/uploads/" + wordpress_src.group(1)).content)
f.close()
continue
f = open(filename, "w")
contents = "".join(contents)
f.write(contents)
f.close() |
Tidy up the bidding when you're outbid | import React from 'react';
import {connect} from 'react-redux';
import socksend from './websocket';
export default connect()(class Property extends React.Component {
update(e) {
e.preventDefault();
socksend("bid", {name: this.props.name, value: this.refs.bid.value});
}
render() {
let minbid = this.props.bidder ? ((this.props.highbid|0) + 10) : (this.props.facevalue|0);
//If you've been outbid, blank the field.
if (this.refs.bid && (this.refs.bid.value|0) < minbid) this.refs.bid.value = "";
return <form onSubmit={this.update.bind(this)}>
<h3 style={{backgroundColor: this.props.color, color: this.props.fg || "black"}}>{this.props.name}</h3>
<p>
Current high bid:<br />
{this.props.bidder || "(nobody)"} {this.props.highbid || this.props.facevalue}
</p>
<div>
<input type="number" ref="bid" defaultValue={this.props.bidder ? "" : this.props.facevalue} />
<input type="submit" value="Bid" />
</div>
<div>{this.props.bidder ? <input type="submit" value={"Bid " + minbid} /> : "\xa0"}</div>
</form>;
}
})
| import React from 'react';
import {connect} from 'react-redux';
import socksend from './websocket';
export default connect()(class Property extends React.Component {
update(e) {
e.preventDefault();
socksend("bid", {name: this.props.name, value: this.refs.bid.value});
}
render() {
let minbid = this.props.bidder ? ((this.props.highbid|0) + 10) : (this.props.facevalue|0);
if (this.refs.bid && (this.refs.bid.value|0) < minbid) this.refs.bid.value = minbid;
return <form onSubmit={this.update.bind(this)}>
<h3 style={{backgroundColor: this.props.color, color: this.props.fg || "black"}}>{this.props.name}</h3>
<p>
Current high bid:<br />
{this.props.bidder || "(nobody)"} {this.props.highbid || this.props.facevalue}
</p>
<div>
<input type="number" ref="bid" defaultValue={minbid} />
<input type="submit" value="Bid" />
</div>
</form>;
}
})
|
Update Slack notifier to use new data format. | 'use strict';
const assert = require('assert');
const util = require('util');
/**
* @param {secret} SLACK_WEBHOOK_URL
* @param {secret} SLACK_CHANNEL_NAME
* @param JSON body
*
* body: [{name: 'GitHub', accounts: ['john', 'mark']}]
*/
module.exports = (ctx, cb) => {
assert(ctx.secrets.SLACK_CHANNEL_NAME, 'SLACK_CHANNEL_NAME secret is missing!');
assert(ctx.secrets.SLACK_WEBHOOK_URL, 'SLACK_WEBHOOK_URL secret is missing!');
assert(Array.isArray(ctx.body), 'Body content is not an Array!');
const slack = require('slack-notify')(ctx.secrets.SLACK_WEBHOOK_URL);
slack.onError = (err) => cb(err);
ctx.body.forEach(service => {
let accounts = service.accounts.map(account => `*${account}*`).join(', ');
let message = `Users without MFA on \`${service.name}\` are ${accounts}`;
slack.send({
channel: ctx.secrets.SLACK_CHANNEL_NAME,
icon_emoji: ':warning:',
username: 'MFA Agent',
text: message
});
});
cb();
};
| 'use strict';
var util = require('util');
/**
* @param {secret} SLACK_WEBHOOK_URL
* @param {secret} SLACK_CHANNEL_NAME
*/
module.exports = function(ctx, cb) {
var params = ctx.body;
if (!ctx.secrets.SLACK_WEBHOOK_URL || !ctx.secrets.SLACK_CHANNEL_NAME) {
return cb(new Error('"SLACK_WEBHOOK_URL" and "SLACK_CHANNEL_NAME" parameters required'));
}
if (!params.service || !params.members) {
return cb(new Error('"service" and "members" parameters required'));
}
var SLACK_WEBHOOK_URL = ctx.secrets.SLACK_WEBHOOK_URL;
var SLACK_CHANNEL_NAME = ctx.secrets.SLACK_CHANNEL_NAME;
var slack = require('slack-notify')(SLACK_WEBHOOK_URL);
var service = params.service;
var members = params.members.join(', ');
var messages = {
tfa_disabled: util.format('Users without TFA on `%s` are %s', service, members)
};
slack.send({
channel: SLACK_CHANNEL_NAME,
icon_emoji: ':warning:',
text: messages.tfa_disabled,
unfurl_links: 0,
username: 'TFA Monitor'
});
cb();
};
|
Change send email to contact namespace | # -*- coding: utf-8 -*-
"""
File: tests.py
Creator: MazeFX
Date: 12-7-2016
Tests written for testing main website pages (home, about, contact, etc)
Contact page has the ability to send emails through anymail/mailgun.
"""
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.template.loader import render_to_string
from website.pages.views import home_page, contact
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('pages/home.html')
self.assertEqual(response.content.decode(), expected_html)
class ContactTest(TestCase):
def test_contact_url_resolves_to_contact_view(self):
found = resolve('/contact/')
self.assertEqual(found.func, contact)
def test_contact_returns_correct_html(self):
request = HttpRequest()
response = contact(request)
expected_html = render_to_string('pages/contact.html')
self.assertEqual(response.content.decode(), expected_html)
| # -*- coding: utf-8 -*-
"""
File: tests.py
Creator: MazeFX
Date: 12-7-2016
Tests written for testing main website pages (home, about, contact, etc)
"""
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.template.loader import render_to_string
from website.pages.views import home_page, send_email
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('pages/home.html')
self.assertEqual(response.content.decode(), expected_html)
class SendEmailTest(TestCase):
def test_send_email_url_resolves_to_send_email_view(self):
found = resolve('/send-email/')
self.assertEqual(found.func, send_email)
def test_send_email_returns_correct_html(self):
request = HttpRequest()
response = send_email(request)
expected_html = render_to_string('pages/send_email.html')
self.assertEqual(response.content.decode(), expected_html)
|
Remove robots from pytest path ignore, as requested by @gonzalocasas. | import pytest
import compas
import math
import numpy
def pytest_ignore_collect(path):
if "rhino" in str(path):
return True
if "blender" in str(path):
return True
if "ghpython" in str(path):
return True
if "matlab" in str(path):
return True
if str(path).endswith('_cli.py'):
return True
@pytest.fixture(autouse=True)
def add_compas(doctest_namespace):
doctest_namespace["compas"] = compas
@pytest.fixture(autouse=True)
def add_math(doctest_namespace):
doctest_namespace["math"] = math
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
| import pytest
import compas
import math
import numpy
def pytest_ignore_collect(path):
if "rhino" in str(path):
return True
if "blender" in str(path):
return True
if "ghpython" in str(path):
return True
if "matlab" in str(path):
return True
if "robots" in str(path):
return True
if str(path).endswith('_cli.py'):
return True
@pytest.fixture(autouse=True)
def add_compas(doctest_namespace):
doctest_namespace["compas"] = compas
@pytest.fixture(autouse=True)
def add_math(doctest_namespace):
doctest_namespace["math"] = math
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
|
Fix imports for void tests | """test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
| """test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
|
Remove debug statement and setTimeout. Its annoying that exceptions get caught on the rtjp layer - would probably be better to hand off control somewhere in the stack with a setTimeout | jsio.path.common = 'js';
jsio.path.browser = 'js';
jsio('from common.javascript import bind');
jsio('import net, logging');
jsio('import common.Item');
jsio('import common.itemFactory');
jsio('import browser.ItemView');
jsio('import browser.UbiquityClient');
gClient = new browser.UbiquityClient();
gClient.connect('csp', "http://" + (document.domain || "127.0.0.1") + ":5555", function(itemSubscriptions){
var connecting = document.getElementById('connecting');
connecting.parentNode.removeChild(connecting);
var placeHolder = document.getElementById('placeholder');
for (var i=0, itemId; itemId = itemSubscriptions[i]; i++) {
var item = common.itemFactory.getItem(itemId);
var itemView = new browser.ItemView(item);
placeHolder.appendChild(itemView.getPropertyView('name'))
placeHolder.appendChild(itemView.getPropertyView('age'))
placeHolder.appendChild(document.createElement('br'));
placeHolder.appendChild(itemView.getPropertyView('name'))
placeHolder.appendChild(itemView.getPropertyView('age'))
placeHolder.appendChild(document.createElement('br'));
placeHolder.appendChild(document.createElement('br'));
item.subscribe('PropertySet', bind(gClient, 'onItemPropertySet', item.getId()));
gClient.subscribeToItem(item);
}
});
| jsio.path.common = 'js';
jsio.path.browser = 'js';
jsio('from common.javascript import bind');
jsio('import net, logging');
jsio('import common.Item');
jsio('import common.itemFactory');
jsio('import browser.ItemView');
jsio('import browser.UbiquityClient');
gClient = new browser.UbiquityClient();
gClient.connect('csp', "http://" + (document.domain || "127.0.0.1") + ":5555", function(itemSubscriptions){
window.top.console.debug(itemSubscriptions);
setTimeout(function(){
var connecting = document.getElementById('connecting');
connecting.parentNode.removeChild(connecting);
var placeHolder = document.getElementById('placeholder');
for (var i=0, itemId; itemId = itemSubscriptions[i]; i++) {
var item = common.itemFactory.getItem(itemId);
var itemView = new browser.ItemView(item);
placeHolder.appendChild(itemView.getPropertyView('name'))
placeHolder.appendChild(itemView.getPropertyView('age'))
placeHolder.appendChild(document.createElement('br'));
placeHolder.appendChild(itemView.getPropertyView('name'))
placeHolder.appendChild(itemView.getPropertyView('age'))
placeHolder.appendChild(document.createElement('br'));
placeHolder.appendChild(document.createElement('br'));
item.subscribe('PropertySet', bind(gClient, 'onItemPropertySet', item.getId()));
gClient.subscribeToItem(item);
}
})
});
|
feat: Use concatenated string for user roles | package in.ac.amu.zhcet.data.model.base.user;
import in.ac.amu.zhcet.data.model.base.entity.BaseEntity;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
@Entity
@DynamicUpdate
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(exclude = "password")
public class UserAuth extends BaseEntity {
public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
@Id
private String userId;
@NotNull
private String password;
@NotNull
private String roles;
@NotNull
private String name;
@NotNull
private String type;
public UserAuth(String userId, String password, String name, String type, String[] roles) {
setUserId(userId);
setPassword(password);
setName(name);
setType(type);
setRoles(roles);
}
public void setRoles(String[] roles) {
this.roles = String.join(",", roles);
}
public String[] getRoles() {
return roles.split(",");
}
}
| package in.ac.amu.zhcet.data.model.base.user;
import in.ac.amu.zhcet.data.model.base.entity.BaseEntity;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@DynamicUpdate
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(exclude = "password")
public class UserAuth extends BaseEntity {
public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
@Id
private String userId;
@NotNull
private String password;
@NotNull
private String[] roles;
@NotNull
private String name;
@NotNull
private String type;
public UserAuth(String userId, String password, String name, String type, String[] roles) {
setUserId(userId);
setPassword(password);
setName(name);
setType(type);
setRoles(roles);
}
}
|
[tests] Correct the "error" tests configuration. | 'use strict';
var assert = require('assert');
var jsyaml = require('../../lib/js-yaml');
var _functional = require('../support/functional');
var TEST_SCHEMA = require('../support/schema');
var YAMLError = require('../../lib/js-yaml/error');
_functional.generateTests({
description: 'Test errors loading all documents from the string.',
files: ['.loader-error'],
test: function (errorFile) {
assert.throws(
function () {
jsyaml.loadAll(
errorFile.content,
function () {},
{ name: errorFile.path,
schema: TEST_SCHEMA,
strict: true });
},
YAMLError,
'In file "' + errorFile.path + '"');
}
});
_functional.generateTests({
description: 'Test errors loading single documents from the string.',
files: ['.single-loader-error'],
test: function (errorFile) {
assert.throws(
function () {
jsyaml.load(
errorFile.content,
{ name: errorFile.path,
schema: TEST_SCHEMA,
strict: true });
},
YAMLError,
'In file "' + errorFile.path + '"');
}
});
| 'use strict';
var assert = require('assert');
var jsyaml = require('../../lib/js-yaml');
var _functional = require('../support/functional');
var YAMLError = require('../../lib/js-yaml/error');
_functional.generateTests({
description: 'Test errors loading all documents from the string.',
files: ['.loader-error'],
test: function (errorFile) {
assert.throws(
function () {
jsyaml.loadAll(
errorFile.content,
function () {},
{ name: errorFile.path });
},
YAMLError);
}
});
_functional.generateTests({
description: 'Test errors loading single documents from the string.',
files: ['.single-loader-error'],
test: function (errorFile) {
assert.throws(
function () {
jsyaml.load(
errorFile.content,
{ name: errorFile.path });
},
YAMLError);
}
});
|
Edit test method 'test_config_file' to check configuration network interface | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert socket.is_listening
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.is_file
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.contains('port: 27017')
| import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert socket.is_listening
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
|
Make that it works in 90% of the cases. 3:30. | import sublime
import sublime_plugin
import HTMLParser
from commit import Commitment
whatthecommit = 'http://whatthecommit.com/'
randomMessages = Commitment()
class CommitmentToClipboardCommand(sublime_plugin.WindowCommand):
def run(self):
commit = randomMessages.get()
message = HTMLParser.HTMLParser().unescape(commit.get('message', '').replace('\n','').replace('<br/>', '\n'))
message_hash = commit.get('message_hash', '')
if message:
print 'Commitment: ' + '\n' + message + '\n' + 'Permalink: ' + whatthecommit + message_hash
sublime.set_clipboard(message)
class CommitmentToStatusBarCommand(sublime_plugin.WindowCommand):
def run(self):
commit = randomMessages.get()
message = HTMLParser.HTMLParser().unescape(commit.get('message', '').replace('\n','').replace('<br/>', '\n'))
message_hash = commit.get('message_hash', '')
if message:
print 'Commitment: ' + '\n' + message + '\n' + 'Permalink: ' + whatthecommit + message_hash
sublime.status_message(message) | import sublime
import sublime_plugin
from commit import Commitment
whatthecommit = 'http://whatthecommit.com/'
randomMessages = Commitment()
class CommitmentToClipboardCommand(sublime_plugin.WindowCommand):
def run(self):
commit = randomMessages.get()
message = commit.get('message', '')
message_hash = commit.get('message_hash', '')
if message:
print 'Commitment: ' + message + '\n' + 'Permalink: ' + whatthecommit + message_hash
sublime.set_clipboard(message)
class CommitmentToStatusBarCommand(sublime_plugin.WindowCommand):
def run(self):
commit = randomMessages.get()
message = commit.get('message', '')
message_hash = commit.get('message_hash', '')
if message:
print 'Commitment: ' + message + '\n' + 'Permalink: ' + whatthecommit + message_hash
sublime.status_message(message) |
Comment out db for testing | <?php
$config['db']['host'] = "";
$config['db']['user'] = "";
$config['db']['pass'] = "";
$config['db']['name'] = "";
$config['captcha']['pub'] = "";
$config['captcha']['priv'] = "";
$config['twilio']['sid'] = "";
$config['twilio']['token'] = "";
$config['twilio']['number'] = "";
//$pdo = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] . ';charset=utf8', $config['db']['user'], $config['db']['pass']); | <?php
$config['db']['host'] = "";
$config['db']['user'] = "";
$config['db']['pass'] = "";
$config['db']['name'] = "";
$config['captcha']['pub'] = "";
$config['captcha']['priv'] = "";
$config['twilio']['sid'] = "";
$config['twilio']['token'] = "";
$config['twilio']['number'] = "";
$pdo = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] .
';charset=utf8', $config['db']['user'], $config['db']['pass']); |
Remove deprecation warnings for connect/express | var express = require('express');
var path = require('path');
var expressValidator = require('express-validator');
var home = require('./routes/home.js');
var api = require('./routes/api.js');
var port = process.env.PORT || 5000;
var app = express();
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger());
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'controllers')));
app.use(expressValidator());
});
app.get('/', home.index);
app.put('/api/subscriptions', api.createSubscription);
app.get('/api/subscriptions', api.readSubscriptions);
app.del('/api/subscriptions', api.deleteSubscription);
app.get('/api/packages', api.readPackages);
app.listen(port);
| var express = require('express');
var path = require('path');
var expressValidator = require('express-validator');
var home = require('./routes/home.js');
var api = require('./routes/api.js');
var port = process.env.PORT || 5000;
var app = express();
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'controllers')));
app.use(expressValidator());
});
app.get('/', home.index);
app.put('/api/subscriptions', api.createSubscription);
app.get('/api/subscriptions', api.readSubscriptions);
app.del('/api/subscriptions', api.deleteSubscription);
app.get('/api/packages', api.readPackages);
app.listen(port);
|
Test for reading a wave file asserts that the essence is set. | import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1
assert asset.essence != None | import pytest
from adam.adam import *
def test_contains_asset():
storage = AssetStorage()
a = Asset()
storage['key'] = a
assert storage['key'] == a
def test_contains_key():
storage = AssetStorage()
a = Asset()
assert 'key' not in storage
storage['key'] = a
assert 'key' in storage
def test_asset_is_versioned():
storage = AssetStorage()
a = Asset()
updated_a = Asset()
storage['key'] = a
storage['key'] = updated_a
versions = storage.versions_of('key')
assert len(versions) == 2
assert versions[0] == a
assert versions[1] == updated_a
def test_asset_is_deleted():
storage = AssetStorage()
a = Asset()
storage['key'] = a
del storage['key']
assert 'key' not in storage
def test_deleting_unkown_key_raises_exception():
storage = AssetStorage()
with pytest.raises(KeyError):
del storage['key']
def test_create_asset_from_wav():
reader = WavReader()
asset = reader.read('tests/16-bit-mono.wav')
assert asset.mime_type == 'audio/wav'
assert asset.framerate == 48000
assert asset.channels == 1 |
Remove print calls from custom validator
Browsers and server-side CDV seem to have a somewhat
different idea of what 'print' means. Ooops. | wd.cdv.validators.registerValidator("custom", function(validation, rs){
var validationResult = wd.cdv.validationResult({
name: validation.validationName,
type: validation.validationType
});
var result = validation.validationFunction.call(this,rs,[]);
if (typeof result == "object") {
validationResult.setAlert(wd.cdv.alert(result));
} else {
validationResult.setAlert(this.parseAlert(result));
switch(result){
case "OK":
if(validation.successMessage) validationResult.getAlert().setDescription(validation.successMessage);
break;
case "CRITICAL":
case "ERROR":
case "WARNING":
default:
if(validation.failureMessage) validationResult.getAlert().setDescription(validation.failureMessage);
break;
}
}
return validationResult;
});
| wd.cdv.validators.registerValidator("custom", function(validation, rs){
var validationResult = wd.cdv.validationResult({
name: validation.validationName,
type: validation.validationType
});
var result = validation.validationFunction.call(this,rs,[]);
if (typeof result == "object") {
validationResult.setAlert(wd.cdv.alert(result));
} else {
validationResult.setAlert(this.parseAlert(result));
print(JSON.stringify(validation));
print(result);
switch(result){
case "OK":
if(validation.successMessage) validationResult.getAlert().setDescription(validation.successMessage);
break;
case "CRITICAL":
case "ERROR":
case "WARNING":
default:
if(validation.failureMessage) validationResult.getAlert().setDescription(validation.failureMessage);
break;
}
}
return validationResult;
});
|
Remove Code That Doesn't Have a Test | """DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.hostname = hostname
self.api_key = api_key
def create(self, value):
"""Create this record on DigitalOcean with the supplied value."""
self._number = http.create(self, value)
return self.number
def delete(self, record_id=None):
"""Delete this record on DigitalOcean, identified by record_id."""
if record_id is None:
record_id = self.number
http.delete(self, record_id)
def printer(self):
printer(self.number)
@property
def number(self):
return self._number
@number.setter
def number(self, value):
self._number = value
| """DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.hostname = hostname
self.api_key = api_key
def create(self, value):
"""Create this record on DigitalOcean with the supplied value."""
self._number = http.create(self, value)
return self.number
def delete(self, record_id=None):
"""Delete this record on DigitalOcean, identified by record_id."""
if record_id is None:
record_id = self.number
http.delete(self, record_id)
def printer(self):
printer(self.number)
@property
def number(self):
return self._number
@number.setter
def number(self, value):
if self.number is None:
self._number = value
else:
raise ValueError(
'Cannot externally reset a record\'s number identifier.')
|
[+] Add return_url for logout action | <?php
namespace Armd\UserBundle\Security;
use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class LogoutSuccessHandler extends DefaultLogoutSuccessHandler implements ContainerAwareInterface
{
protected $container;
function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
function onLogoutSuccess(Request $request)
{
$response = parent::onLogoutSuccess($request);
$this->clearCookies($response);
$this->addRedirect($request, $response);
return $response;
}
function clearCookies(Response $response)
{
$domain = $this->container->getParameter('domain');
$response->headers->clearCookie('_USER_ID', '/', $domain);
$response->headers->clearCookie('_USER_HASH', '/', $domain);
}
function addRedirect(Request $request, Response $response)
{
$returnUrl = $request->get('return_url');
if (!empty($returnUrl)) {
$response->headers->set('Location', $returnUrl);
}
}
}
| <?php
namespace Armd\UserBundle\Security;
use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class LogoutSuccessHandler extends DefaultLogoutSuccessHandler implements ContainerAwareInterface
{
protected $container;
function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
function onLogoutSuccess(Request $request)
{
$response = parent::onLogoutSuccess($request);
$this->clearCookies($response);
return $response;
}
function clearCookies(Response $response)
{
$domain = $this->container->getParameter('domain');
$response->headers->clearCookie('_USER_ID', '/', $domain);
$response->headers->clearCookie('_USER_HASH', '/', $domain);
}
}
|
Adjust javascript for organisation feedback form | $(document).on("click", ".deletefeedback", function(e){
e.preventDefault();
var feedbackid = $(this).attr('data-feedback-id');
$("#feedback"+feedbackid).remove();
});
var countfeedback = 0;
$("#addfeedbackbtn").click(function(){
countfeedback ++;
var uses = $("#uses").val();
var element = $("#element option:selected").val();
var where = $("#where option:selected").val();
$("#conditions tbody").append('<tr id="feedback' + countfeedback + '"><td>'+organisation_code+' ' + uses + ' ' + element + ' at ' + where + '<input type="hidden" name="feedback" value="' + countfeedback + '" /><input type="hidden" name="uses' + countfeedback + '" value="' + uses + '" /><input type="hidden" name="element' + countfeedback + '" value="' + element + '" /><input type="hidden" name="where' + countfeedback + '" value="' + where + '" /></td><td><a href="" class="deletefeedback" data-feedback-id="' + countfeedback + '"><i class="icon-trash"></i></td></tr>');
$("#addFeedback").modal('hide');
});
| $(document).on("click", ".deletefeedback", function(e){
e.preventDefault();
var feedbackid = $(this).attr('data-feedback-id');
$("#feedback"+feedbackid).remove();
});
var countfeedback = 0;
$("#addfeedbackbtn").click(function(){
countfeedback ++;
var uses = $("#uses option:selected").val();
var element = $("#element option:selected").val();
var where = $("#where option:selected").val();
$("#conditions tbody").append('<tr id="feedback' + countfeedback + '"><td>'+organisation_code+' ' + $("#uses option:selected").val() + ' ' + $("#element option:selected").val() + ' at ' + $("#where option:selected").val() + '<input type="hidden" name="feedback" value="' + countfeedback + '" /><input type="hidden" name="uses' + countfeedback + '" value="' + uses + '" /><input type="hidden" name="element' + countfeedback + '" value="' + element + '" /><input type="hidden" name="where' + countfeedback + '" value="' + where + '" /></td><td><a href="" class="deletefeedback" data-feedback-id="' + countfeedback + '"><i class="icon-trash"></i></td></tr>');
$("#addFeedback").modal('hide');
});
|
Fix module resolution for npm 3+ | var babelPresetEs2015,
commonJsPlugin,
es2015PluginList,
es2015WebpackPluginList;
babelPresetEs2015 = require('babel-preset-es2015');
try {
// npm ^3
commonJsPlugin = require('babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
if (!commonJsPlugin) {
try {
// npm ^2
commonJsPlugin = require('babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
}
if (!commonJsPlugin) {
throw new Error('Cannot resolve "babel-plugin-transform-es2015-modules-commonjs".');
}
es2015PluginList = babelPresetEs2015.plugins;
es2015WebpackPluginList = es2015PluginList.filter(function (es2015Plugin) {
return es2015Plugin !== commonJsPlugin;
});
if (es2015PluginList.length !== es2015WebpackPluginList.length + 1) {
throw new Error('Cannot remove "babel-plugin-transform-es2015-modules-commonjs" from the plugin list.');
}
module.exports = {
plugins: es2015WebpackPluginList
};
| var babelPresetEs2015,
commonJsPlugin,
es2015PluginList,
es2015WebpackPluginList;
babelPresetEs2015 = require('babel-preset-es2015');
try {
// npm ^2
commonJsPlugin = require('babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
if (!commonJsPlugin) {
try {
// npm ^3
commonJsPlugin = require('babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
}
if (!commonJsPlugin) {
throw new Error('Cannot resolve "babel-plugin-transform-es2015-modules-commonjs".');
}
es2015PluginList = babelPresetEs2015.plugins;
es2015WebpackPluginList = es2015PluginList.filter(function (es2015Plugin) {
return es2015Plugin !== commonJsPlugin;
});
if (es2015PluginList.length !== es2015WebpackPluginList.length + 1) {
throw new Error('Cannot remove "babel-plugin-transform-es2015-modules-commonjs" from the plugin list.');
}
module.exports = {
plugins: es2015WebpackPluginList
};
|
Set bamboo generation percent to 0 until water is ready | var biomes = {
"riverLand": {
probability: 0,
tiles: {
"bambooBush": 0,
"rockCluster": 0.2
}
},
"forest": {
probability: 0.5,
tiles: {
"loneTree": 0.25,
"rockCluster": 0.75
}
},
"desert": {
probability: 0.5,
tiles: {
"loneTree": 0.25,
"rockCluster": 0.75
}
}
}
| var biomes = {
"riverLand": {
probability: 0.8,
tiles: {
"bambooBush": 0.8,
"rockCluster": 0.2
}
},
"forest": {
probability: 0.5,
tiles: {
"loneTree": 0.25,
"rockCluster": 0.75
}
},
"desert": {
probability: 0.5,
tiles: {
"loneTree": 0.25,
"rockCluster": 0.75
}
}
}
|
Fix warning when iterating over object | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by 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.
*/
var CommentService = require('./services/comment-service.js');
var findGroupedPlatonThreadUrlElements = require('./utils/find-thread-url-elements.js');
var groupedThreadUrlElements = findGroupedPlatonThreadUrlElements();
var threadUrls = Object.keys(groupedThreadUrlElements);
CommentService.countComments(threadUrls).then(function(commentCounts) {
for (var threadUrl in commentCounts) {
if (commentCounts.hasOwnProperty(threadUrl)) {
groupedThreadUrlElements[threadUrl].forEach(function (element) {
var count = commentCounts[threadUrl];
element.textContent = count + (count === 1 ? ' Comment' : ' Comments');
});
}
}
});
| /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by 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.
*/
var CommentService = require('./services/comment-service.js');
var findGroupedPlatonThreadUrlElements = require('./utils/find-thread-url-elements.js');
var groupedThreadUrlElements = findGroupedPlatonThreadUrlElements();
var threadUrls = Object.keys(groupedThreadUrlElements);
CommentService.countComments(threadUrls).then(function(commentCounts) {
for (var threadUrl in commentCounts) {
groupedThreadUrlElements[threadUrl].forEach(function(element) {
var count = commentCounts[threadUrl];
element.textContent = count + (count === 1 ? ' Comment' : ' Comments');
});
}
});
|
Set property in case it has been set wrong previously | package org.jaxen.javabean;
import junit.framework.TestCase;
import org.jaxen.saxpath.helpers.XPathReaderFactory;
public class DocumentNavigatorTest
extends TestCase
{
protected void setUp() throws Exception
{
System.setProperty( XPathReaderFactory.DRIVER_PROPERTY,
"" );
}
public void testNothing()
throws Exception
{
JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );
Person bob = new Person( "bob", 30 );
bob.addBrother( new Person( "billy", 34 ) );
bob.addBrother( new Person( "seth", 29 ) );
bob.addBrother( new Person( "dave", 32 ) );
bob.addBrother( new Person( "jim", 29 ) );
bob.addBrother( new Person( "larry", 42 ) );
bob.addBrother( new Person( "ted", 22 ) );
System.err.println( xpath.evaluate( bob ) );
}
}
| package org.jaxen.javabean;
import junit.framework.TestCase;
public class DocumentNavigatorTest
extends TestCase
{
public void testNothing()
throws Exception
{
JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );
Person bob = new Person( "bob", 30 );
bob.addBrother( new Person( "billy", 34 ) );
bob.addBrother( new Person( "seth", 29 ) );
bob.addBrother( new Person( "dave", 32 ) );
bob.addBrother( new Person( "jim", 29 ) );
bob.addBrother( new Person( "larry", 42 ) );
bob.addBrother( new Person( "ted", 22 ) );
System.err.println( xpath.evaluate( bob ) );
}
}
|
Change from camelcase to underscores. | import numpy
"""
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.matrix = numpy.zeros((rows, columns))
"""
Attempts to add a piece to a certain column. If the column is
full the move is illegal and false is returned, otherwise true
is returned.
"""
def add_piece(self, column, value):
"Check if column is full."
if self.matrix.item(0,column) != 0:
return False
"Place piece."
for y in range(self.rows):
if y == self.rows - 1: # Reached bottom
self.matrix.itemset((y, column), value)
break
elif self.matrix.item(y + 1, column) == 0: # Next row is also empty
continue
else: # Next row is not empty
self.matrix.itemset((y, column), value)
break
return True
| import numpy
"""
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.boardMatrix = numpy.zeros((rows, columns))
"""
Attempts to add a piece to a certain column. If the column is
full the move is illegal and false is returned, otherwise true
is returned.
"""
def addPiece(self, column, value):
"Check if column is full."
if self.boardMatrix.item(0,column) != 0:
return False
"Place piece."
for y in range(self.rows):
if y == self.rows - 1: # Reached bottom
self.boardMatrix.itemset((y, column), value)
break
elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty
continue
else: # Next row is not empty
self.boardMatrix.itemset((y, column), value)
break
return True
|
Fix default-user to have adequate length for username and password. | var mongoose = require('mongoose'),
User = mongoose.model('User'),
constants = require('../common/constants'),
SHA256 = require('crypto-js/sha256');
User.findOne({username: 'admin'})
.exec(function (err, user) {
'use strict';
if (!user && !err) {
User({
username: 'administrator',
hashPassword: SHA256('administrator'),
cars: [],
level: constants.models.user.defaultLevel,
respect: constants.models.user.defaultRespect,
money: constants.models.user.defaultMoney,
dateRegistered: new Date(),
role: constants.roles.administrator
}).save(function (err) {
if (err) {
console.log('Default user with admin role was not saved!');
}
});
}
}); | var mongoose = require('mongoose'),
User = mongoose.model('User'),
constants = require('../common/constants'),
SHA256 = require('crypto-js/sha256');
User.findOne({username: 'admin'})
.exec(function (err, user) {
'use strict';
if (!user && !err) {
User({
username: 'admin',
hashPassword: SHA256('admin'),
cars: [],
level: constants.models.user.defaultLevel,
respect: constants.models.user.defaultRespect,
money: constants.models.user.defaultMoney,
dateRegistered: new Date(),
role: constants.roles.administrator
}).save(function (err) {
if (err) {
console.log('Default user with admin role was not saved!');
}
});
}
}); |
Fix routing problem when running in PHP web server.
Before: http://localhost/index.php/themes/default/css/global.css
After: http://localhost/themes/default/css/global.css | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>RockMongo</title>
<?php if (php_sapi_name() === 'cli-server'): ?>
<base href="/"/>
<?php endif; ?>
<script language="javascript" src="js/jquery-1.4.2.min.js"></script>
<script language="javascript" src="js/jquery.textarea.js"></script>
<link rel="stylesheet" href="<?php render_theme_path() ?>/css/global.css" type="text/css" media="all"/>
<?php render_page_header(); ?>
<script language="javascript">
$(function () {
$(document).click(window.parent.hideMenus);
if ($("textarea").length > 0) {
$("textarea").tabby();
}
});
</script>
</head>
<body>
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>RockMongo</title>
<script language="javascript" src="js/jquery-1.4.2.min.js"></script>
<script language="javascript" src="js/jquery.textarea.js"></script>
<link rel="stylesheet" href="<?php render_theme_path() ?>/css/global.css" type="text/css" media="all"/>
<?php render_page_header(); ?>
<script language="javascript">
$(function () {
$(document).click(window.parent.hideMenus);
if ($("textarea").length > 0) {
$("textarea").tabby();
}
});
</script>
</head>
<body> |
Add an additional property assayStr
SVN-Revision: 609 | package gov.nih.nci.calab.dto.workflow;
public class AssayBean {
private String assayId;
private String assayName;
private String assayType;
private String assayStr;
public AssayBean(String assayId, String assayName, String assayType) {
super();
// TODO Auto-generated constructor stub
this.assayId = assayId;
this.assayName = assayName;
this.assayType = assayType;
}
public String getAssayId() {
return assayId;
}
public void setAssayId(String assayId) {
this.assayId = assayId;
}
public String getAssayName() {
return assayName;
}
public void setAssayName(String assayName) {
this.assayName = assayName;
}
public String getAssayType() {
return assayType;
}
public void setAssayType(String assayType) {
this.assayType = assayType;
}
public String getAssayStr() {
return this.assayType + " : " + this.assayName;
}
// public void setAssayStr(String assayStr) {
// this.assayStr = assayStr;
// }
}
| package gov.nih.nci.calab.dto.workflow;
public class AssayBean {
private String assayId;
private String assayName;
private String assayType;
public AssayBean(String assayId, String assayName, String assayType) {
super();
// TODO Auto-generated constructor stub
this.assayId = assayId;
this.assayName = assayName;
this.assayType = assayType;
}
public String getAssayId() {
return assayId;
}
public void setAssayId(String assayId) {
this.assayId = assayId;
}
public String getAssayName() {
return assayName;
}
public void setAssayName(String assayName) {
this.assayName = assayName;
}
public String getAssayType() {
return assayType;
}
public void setAssayType(String assayType) {
this.assayType = assayType;
}
}
|
Use config helper & update config key | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on(Config::get('auth.table'))->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
|
Fix to be more forgiving when stringifying
The implicit truthiness string for a node's `value` property
could cause problems when (albeit quite sneakily) setting
a node's `value` to an empty string.
Related bug:
https://github.com/beaugunderson/node-sentence-tools/
pull/4#issuecomment-66350637 | 'use strict';
/**
* Stringify an NLCST node.
*
* @param {NLCSTNode} nlcst
* @return {string}
*/
function nlcstToString(nlcst) {
var values,
length,
children;
if (typeof nlcst.value === 'string') {
return nlcst.value;
}
children = nlcst.children;
length = children.length;
/**
* Shortcut: This is pretty common, and a small performance win.
*/
if (length === 1 && 'value' in children[0]) {
return children[0].value;
}
values = [];
while (length--) {
values[length] = nlcstToString(children[length]);
}
return values.join('');
}
module.exports = nlcstToString;
| 'use strict';
/**
* Stringify an NLCST node.
*
* @param {NLCSTNode} nlcst
* @return {string}
*/
function nlcstToString(nlcst) {
var values,
length,
children;
if (nlcst.value) {
return nlcst.value;
}
children = nlcst.children;
length = children.length;
/**
* Shortcut: This is pretty common, and a small performance win.
*/
if (length === 1 && 'value' in children[0]) {
return children[0].value;
}
values = [];
while (length--) {
values[length] = nlcstToString(children[length]);
}
return values.join('');
}
module.exports = nlcstToString;
|
Declare command function before use | //Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];
//Login to Discord
client.login(config.API.discord);
//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
items.forEach(function(item) {
var file = file.replace(/['"]+/g, '');
command[file] = require(file);
})
})
client.on('ready', function() {
console.log("Successfully connected to Discord!");
client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});
client.on('message', function(message) {
if (!message.content.startsWith(config.MSS.prefix)) return false;
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
if (input[0] === "eval" && message.author.id === "190519304972664832") {
eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
}
});
| //Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
//Login to Discord
client.login(config.API.discord);
//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
items.forEach(function(item) {
var file = file.replace(/['"]+/g, '');
var command[file] = require(file);
})
})
client.on('ready', function() {
console.log("Successfully connected to Discord!");
client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});
client.on('message', function(message) {
if (!message.content.startsWith(config.MSS.prefix)) return false;
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
if (input[0] === "eval" && message.author.id === "190519304972664832") {
eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
}
});
|
Update copyright notice with MIT license | /*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--*/
package com.nasmlanguage;
import com.intellij.lexer.FlexAdapter;
public class NASMLexerAdapter extends FlexAdapter {
public NASMLexerAdapter() {
super(new _NASMLexer());
}
}
| /*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--*/
package com.nasmlanguage;
import com.intellij.lexer.FlexAdapter;
public class NASMLexerAdapter extends FlexAdapter {
public NASMLexerAdapter() {
super(new _NASMLexer());
}
}
|
Add options trailing slashes to the Enrollment API.
This allows the edX REST API Client to perform a sucessful GET against
this API, since Slumber (which our client is based off of) appends the
trailing slash by default. | """
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
EnrollmentView,
EnrollmentListView,
EnrollmentCourseDetailView
)
urlpatterns = patterns(
'enrollment.views',
url(
r'^enrollment/{username},{course_key}/$'.format(
username=settings.USERNAME_PATTERN, course_key=settings.COURSE_ID_PATTERN
),
EnrollmentView.as_view(),
name='courseenrollment'
),
url(
r'^enrollment/{course_key}/$'.format(course_key=settings.COURSE_ID_PATTERN),
EnrollmentView.as_view(),
name='courseenrollment'
),
url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'),
url(
r'^course/{course_key}/$'.format(course_key=settings.COURSE_ID_PATTERN),
EnrollmentCourseDetailView.as_view(),
name='courseenrollmentdetails'
),
)
| """
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
EnrollmentView,
EnrollmentListView,
EnrollmentCourseDetailView
)
urlpatterns = patterns(
'enrollment.views',
url(
r'^enrollment/{username},{course_key}$'.format(
username=settings.USERNAME_PATTERN, course_key=settings.COURSE_ID_PATTERN
),
EnrollmentView.as_view(),
name='courseenrollment'
),
url(
r'^enrollment/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN),
EnrollmentView.as_view(),
name='courseenrollment'
),
url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'),
url(
r'^course/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN),
EnrollmentCourseDetailView.as_view(),
name='courseenrollmentdetails'
),
)
|
Use raw_input instead of the unmodified words | #coding:utf-8
import urllib
import urllib2
import re
from random import choice
ipList=['120.76.115.134:80','222.83.14.145:3128','119.188.94.145:80']
thisIp=choice(ipList)
input = raw_input("Please input your key words:")
keyWord=urllib.quote(input)
url='http://search.sina.com.cn/iframe/suggest/index.php?q='+keyWord
headers={
'Get':url,
'Host':'search.sina.com.cn',
'Referer':'http://search.sina.com.cn/',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
}
proxy_support = urllib2.ProxyHandler({'http': 'http://'+thisIp})
opener=urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
req=urllib2.Request(url)
for key in headers:
req.add_header(key,headers[key])
html=urllib2.urlopen(req).read()
file=open('C:\Users\Ryan\Desktop\lianXC.txt','w')
file.write(html)
| #coding:utf-8
import urllib
import urllib2
import re
from random import choice
ipList=['120.76.115.134:80','222.83.14.145:3128','119.188.94.145:80']
thisIp=choice(ipList)
keyWord=urllib.quote('科学')
url='http://search.sina.com.cn/iframe/suggest/index.php?q='+keyWord
headers={
'Get':url,
'Host':'search.sina.com.cn',
'Referer':'http://search.sina.com.cn/',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
}
proxy_support = urllib2.ProxyHandler({'http': 'http://'+thisIp})
opener=urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
req=urllib2.Request(url)
for key in headers:
req.add_header(key,headers[key])
html=urllib2.urlopen(req).read()
file=open('C:\Users\Ryan\Desktop\lianXC.txt','w')
file.write(html)
|
Fix login response not containing the token | <?php namespace Flarum\Forum\Actions;
use Flarum\Api\Client;
use Flarum\Forum\Events\UserLoggedIn;
use Flarum\Core\Repositories\UserRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
class LoginAction extends BaseAction
{
use WritesRememberCookie;
protected $users;
protected $apiClient;
public function __construct(UserRepositoryInterface $users, Client $apiClient)
{
$this->users = $users;
$this->apiClient = $apiClient;
}
public function handle(Request $request, $routeParams = [])
{
$params = array_only($request->getAttributes(), ['identification', 'password']);
$data = $this->apiClient->send('Flarum\Api\Actions\TokenAction', $params);
event(new UserLoggedIn($this->users->findOrFail($data->userId), $data->token));
// TODO: The client needs to pass through exceptions
$response = $this->success();
$response->getBody()->write(json_encode($data));
return $this->withRememberCookie(
$response,
$data->token
);
}
}
| <?php namespace Flarum\Forum\Actions;
use Flarum\Api\Client;
use Flarum\Forum\Events\UserLoggedIn;
use Flarum\Core\Repositories\UserRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
class LoginAction extends BaseAction
{
use WritesRememberCookie;
protected $users;
protected $apiClient;
public function __construct(UserRepositoryInterface $users, Client $apiClient)
{
$this->users = $users;
$this->apiClient = $apiClient;
}
public function handle(Request $request, $routeParams = [])
{
$params = array_only($request->getAttributes(), ['identification', 'password']);
$data = $this->apiClient->send('Flarum\Api\Actions\TokenAction', $params);
event(new UserLoggedIn($this->users->findOrFail($data->userId), $data->token));
// TODO: The client needs to pass through exceptions
return $this->withRememberCookie(
$this->success(),
$data->token
);
}
}
|
Test with headless Chrome by default | /*
Copyright 2017 The BioBricks Foundation
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.
*/
var spawn = require('child_process').spawn
var path = require('path')
var CHROMEDRIVER = path.join(
__dirname, '..', 'node_modules', '.bin', 'chromedriver'
)
var chromedriver = spawn(CHROMEDRIVER, ['--url-base=/wd/hub'])
var webdriver = module.exports = require('webdriverio')
.remote({
host: 'localhost',
port: 9515,
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: process.env.DISABLE_HEADLESS
? undefined
: {args: ['headless', '--disable-gpu']}
}
})
.init()
.timeouts('script', 1000)
.timeouts('implicit', 1000)
require('tape').onFinish(cleanup)
process
.on('SIGTERM', cleanup)
.on('SIGQUIT', cleanup)
.on('SIGINT', cleanup)
.on('uncaughtException', cleanup)
function cleanup () {
webdriver.end()
chromedriver.kill('SIGKILL')
}
| /*
Copyright 2017 The BioBricks Foundation
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.
*/
var spawn = require('child_process').spawn
var path = require('path')
var CHROMEDRIVER = path.join(
__dirname, '..', 'node_modules', '.bin', 'chromedriver'
)
var chromedriver = spawn(CHROMEDRIVER, ['--url-base=/wd/hub'])
var webdriver = module.exports = require('webdriverio')
.remote({
host: 'localhost',
port: 9515,
desiredCapabilities: {
browserName: 'chrome'
}
})
.init()
.timeouts('script', 1000)
.timeouts('implicit', 1000)
require('tape').onFinish(cleanup)
process
.on('SIGTERM', cleanup)
.on('SIGQUIT', cleanup)
.on('SIGINT', cleanup)
.on('uncaughtException', cleanup)
function cleanup () {
webdriver.end()
chromedriver.kill('SIGKILL')
}
|
Correct the trove categorization to say License = BSD. | from setuptools import setup
import tamarin
DESCRIPTION = "A Django app for monitoring AWS usage in Django's admin."
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
version_str = '%d.%d' % (tamarin.VERSION[0], tamarin.VERSION[1])
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Framework :: Django',
]
setup(
name='tamarin',
version=version_str,
packages=[
'tamarin',
'tamarin.management', 'tamarin.management.commands',
'tamarin.migrations',
],
author='Gregory Taylor',
author_email='gtaylor@duointeractive.com',
url='https://github.com/duointeractive/tamarin/',
license='BSD',
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
install_requires=['boto', 'pyparsing'],
)
| from setuptools import setup
import tamarin
DESCRIPTION = "A Django app for monitoring AWS usage in Django's admin."
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
version_str = '%d.%d' % (tamarin.VERSION[0], tamarin.VERSION[1])
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Framework :: Django',
]
setup(
name='tamarin',
version=version_str,
packages=[
'tamarin',
'tamarin.management', 'tamarin.management.commands',
'tamarin.migrations',
],
author='Gregory Taylor',
author_email='gtaylor@duointeractive.com',
url='https://github.com/duointeractive/tamarin/',
license='MIT',
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
install_requires=['boto', 'pyparsing'],
)
|
Hide stripes from screen readers | var stripy = function (element, stripes) {
element.style.position = "relative";
element.style.display = "block";
var text = element.innerHTML;
var newstripe = function (size, name) {
var stripe = document.createElement("span");
stripe.setAttribute("data-stripe", name);
stripe.setAttribute("aria-hidden", "true");
stripe.style.position = "absolute";
stripe.style.height = size + "%";
stripe.style.overflow = "hidden";
stripe.innerHTML = text;
return stripe;
};
var percent = 100 / stripes;
var current = 0;
var i = 0;
while (current < 100) {
current += percent;
current = Math.floor(current);
element.insertBefore(newstripe(current, i), element.firstChild);
i += 1;
};
}; | var stripy = function (element, stripes) {
element.style.position = "relative";
element.style.display = "block";
var text = element.innerHTML;
var newstripe = function (size, name) {
var stripe = document.createElement("span");
stripe.setAttribute("data-stripe", name);
stripe.style.position = "absolute";
stripe.style.height = size + "%";
stripe.style.overflow = "hidden";
stripe.innerHTML = text;
return stripe;
};
var percent = 100 / stripes;
var current = 0;
var i = 0;
while (current < 100) {
current += percent;
current = Math.floor(current);
element.insertBefore(newstripe(current, i), element.firstChild);
i += 1;
};
}; |
Change default DataDog metric prefix in node app to node.express | var FS = require('fs');
var Path = require('path');
var Winston = require('winston');
global.Config = require('nconf');
global.Log = new Winston.Logger();
Log.add(Winston.transports.Console, {
colorize: true,
timestamp: true
});
Config.file(Path.resolve(__dirname, '../config.json'));
Config.defaults({
github: {
owner: 'snipe',
repo: 'nofuckstogive.today',
branch: 'gh-pages',
index: 'images/fucks',
api: 'api.github.com',
raw: 'raw.githubusercontent.com'
},
service: {
listen: 9001
},
datadog: {
enable: false,
stat: 'node.express',
path: true,
method: true,
protocol: true,
response_code: true
}
});
Log.info('Starting FAAS');
| var FS = require('fs');
var Path = require('path');
var Winston = require('winston');
global.Config = require('nconf');
global.Log = new Winston.Logger();
Log.add(Winston.transports.Console, {
colorize: true,
timestamp: true
});
Config.file(Path.resolve(__dirname, '../config.json'));
Config.defaults({
github: {
owner: 'snipe',
repo: 'nofuckstogive.today',
branch: 'gh-pages',
index: 'images/fucks',
api: 'api.github.com',
raw: 'raw.githubusercontent.com'
},
service: {
listen: 9001
},
datadog: {
enable: false,
stat: 'node.faas',
path: true,
method: true,
protocol: true,
response_code: true
}
});
Log.info('Starting FAAS');
|
Include credentials when entity models are fetched | import fetch from 'isomorphic-fetch'
export const REQUEST_ENTITY_MODELS = 'REQUEST_ENTITY_MODELS'
export const RECEIVE_ENTITY_MODELS = 'RECEIVE_ENTITY_MODELS'
function requestEntityModels() {
return {
type: REQUEST_ENTITY_MODELS
}
}
function receiveEntityModels(json) {
return {
type: RECEIVE_ENTITY_MODELS,
models: json,
receivedAt: Date.now()
}
}
export function fetchEntityModels() {
return (dispatch, getState) => {
if (getState().entityModels.length > 0) {
return null
}
dispatch(requestEntityModels())
return fetch(`http://localhost:8080/nice2/rest/entities`, {
credentials: 'include'
})
.then(response => response.json())
.then(json => dispatch(receiveEntityModels(json)))
}
}
const ACTION_HANDLERS = {
[RECEIVE_ENTITY_MODELS]: (entityModels, { models }) =>
Object.keys(models.entities).map(modelName => ({
name: modelName,
label: models.entities[modelName].metaData.label
}))
}
const initialState = []
export default function entityModelsReducer(state = initialState, action: Action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
| import fetch from 'isomorphic-fetch'
export const REQUEST_ENTITY_MODELS = 'REQUEST_ENTITY_MODELS'
export const RECEIVE_ENTITY_MODELS = 'RECEIVE_ENTITY_MODELS'
function requestEntityModels() {
return {
type: REQUEST_ENTITY_MODELS
}
}
function receiveEntityModels(json) {
return {
type: RECEIVE_ENTITY_MODELS,
models: json,
receivedAt: Date.now()
}
}
export function fetchEntityModels() {
return (dispatch, getState) => {
if (getState().entityModels.length > 0) {
return null
}
dispatch(requestEntityModels())
return fetch(`http://localhost:8080/nice2/rest/entities`)
.then(response => response.json())
.then(json => dispatch(receiveEntityModels(json)))
}
}
const ACTION_HANDLERS = {
[RECEIVE_ENTITY_MODELS]: (entityModels, { models }) =>
Object.keys(models.entities).map(modelName => ({
name: modelName,
label: models.entities[modelName].metaData.label
}))
}
const initialState = []
export default function entityModelsReducer(state = initialState, action: Action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
Test passing multiple arguments to Y f | package vm
import "testing"
func TestY(t *testing.T) {
for _, n := range []float64{0, 1, 2, 3, 4, 5, 6, 100} {
n1 := lazyFactorial(NumberThunk(n))
n2 := strictFactorial(n)
t.Logf("%d: %f == %f?\n", int(n), n1, n2)
if n1 != n2 {
t.Fail()
}
}
for _, ts := range [][]*Thunk{
{NumberThunk(7)},
{NumberThunk(13), StringThunk("foobarbaz")},
{NumberThunk(42), NilThunk(), NilThunk()},
} {
t.Log(lazyFactorial(ts...))
}
}
func strictFactorial(n float64) float64 {
if n == 0 {
return 1
}
return n * strictFactorial(n-1)
}
func lazyFactorial(ts ...*Thunk) float64 {
return float64(Y(Normal(NewLazyFunction(lazyFactorialImpl))).(Callable).Call(ts...).(Number))
}
func lazyFactorialImpl(ts ...*Thunk) Object {
// fmt.Println(len(ts))
return If(
App(Normal(Equal), ts[1], NumberThunk(0)),
NumberThunk(1),
App(Normal(Mult),
ts[1],
App(ts[0], append([]*Thunk{App(Normal(Sub), ts[1], NumberThunk(1))}, ts[2:]...)...)))
}
| package vm
import "testing"
func TestY(t *testing.T) {
for _, n := range []float64{0, 1, 2, 3, 4, 5, 6, 100} {
n1 := float64(Y(Normal(NewLazyFunction(lazyFactorial))).(Callable).Call(NumberThunk(n)).(Number))
n2 := strictFactorial(n)
t.Logf("%d: %f == %f?\n", int(n), n1, n2)
if n1 != n2 {
t.Fail()
}
}
}
func strictFactorial(n float64) float64 {
if n == 0 {
return 1
}
return n * strictFactorial(n-1)
}
func lazyFactorial(ts ...*Thunk) Object {
return If(
App(Normal(Equal), ts[1], NumberThunk(0)),
NumberThunk(1),
App(Normal(Mult),
ts[1],
App(ts[0], App(Normal(Sub), ts[1], NumberThunk(1)))))
}
|
Add waypoint list and landmark names | import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
| import flask
app = flask.Flask(__name__)
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'route': [
{
'description': 'This is a description of this place.',
'photos': ['photo1.jpg', 'photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
Increase time-out to 2 minutes | package org.embulk.output.sftp.utils;
import java.io.Closeable;
import java.util.concurrent.TimeUnit;
public class TimeoutCloser implements Closeable
{
private Closeable wrapped;
public TimeoutCloser(Closeable wrapped)
{
this.wrapped = wrapped;
}
@Override
public void close()
{
new TimedCallable<Void>()
{
@Override
public Void call() throws Exception
{
if (wrapped != null) {
wrapped.close();
}
return null;
}
}.callNonInterruptible(120, TimeUnit.SECONDS);
}
}
| package org.embulk.output.sftp.utils;
import java.io.Closeable;
import java.util.concurrent.TimeUnit;
public class TimeoutCloser implements Closeable
{
private Closeable wrapped;
public TimeoutCloser(Closeable wrapped)
{
this.wrapped = wrapped;
}
@Override
public void close()
{
new TimedCallable<Void>()
{
@Override
public Void call() throws Exception
{
if (wrapped != null) {
wrapped.close();
}
return null;
}
}.callNonInterruptible(60, TimeUnit.SECONDS);
}
}
|
Include citation data in search targets | 'use strict';
module.controller('searchView', [
'$scope', 'volumes', 'pageService', function ($scope, volumes, page) {
page.display.title = page.constants.message('page.title.search');
//
var updateData = function (data) {
angular.forEach(data, function (volume) {
volume.more = '';
angular.forEach(volume.access, function (access) {
if (access.individual >= page.permission.ADMIN) {
volume.more += ' ' + access.party.name;
if ('email' in access.party)
volume.more += ' ' + access.party.email;
if ('affiliation' in access.party)
volume.more += ' ' + access.party.affiliation;
}
});
if (volume.citation) {
angular.forEach(volume.citation, function (v) {
volume.more += ' ' + v;
});
}
});
$scope.volumes = data;
};
updateData(volumes);
//
page.events.listen($scope, 'searchForm-init', function (form) {
$scope.searchForm = $scope.searchForm || form;
});
}
]);
| 'use strict';
module.controller('searchView', [
'$scope', 'volumes', 'pageService', function ($scope, volumes, page) {
page.display.title = page.constants.message('page.title.search');
//
var updateData = function (data) {
angular.forEach(data, function (volume) {
volume.more = '';
angular.forEach(volume.access, function (access) {
if (access.individual >= page.permission.ADMIN) {
volume.more += ' ' + access.party.name;
if ('email' in access.party)
volume.more += ' ' + access.party.email;
if ('affiliation' in access.party)
volume.more += ' ' + access.party.affiliation;
}
});
});
$scope.volumes = data;
};
updateData(volumes);
//
page.events.listen($scope, 'searchForm-init', function (form) {
$scope.searchForm = $scope.searchForm || form;
});
}
]);
|
Fix header content-type for lang file | <?php
namespace Code16\Sharp\Http;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
class LangController extends Controller
{
/**
* Echoes out the localization messages as a JS file,
* to be used by the front code (Vue.js).
*/
public function index()
{
$lang = app()->getLocale();
$version = sharp_version();
$strings = Cache::rememberForever("sharp.lang.$lang.$version.js", function() {
$strings = [];
foreach(["action_bar", "form", "modals", "entity_list"] as $filename) {
$strings += collect(trans("sharp-front::$filename"))
->mapWithKeys(function ($value, $key) use ($filename) {
return ["$filename.$key" => $value];
})->all();
}
return $strings;
});
header('Content-Type: application/javascript');
return 'window.i18n = ' . json_encode($strings) . ';';
}
} | <?php
namespace Code16\Sharp\Http;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
class LangController extends Controller
{
/**
* Echoes out the localization messages as a JS file,
* to be used by the front code (Vue.js).
*/
public function index()
{
$lang = app()->getLocale();
$version = sharp_version();
$strings = Cache::rememberForever("sharp.lang.$lang.$version.js", function() {
$strings = [];
foreach(["action_bar", "form", "modals", "entity_list"] as $filename) {
$strings += collect(trans("sharp-front::$filename"))
->mapWithKeys(function ($value, $key) use ($filename) {
return ["$filename.$key" => $value];
})->all();
}
return $strings;
});
header('Content-Type: text/javascript');
return 'window.i18n = ' . json_encode($strings) . ';';
}
} |
Upgrade to yii2 version 2.0.16
see https://github.com/yiisoft/yii2/blob/2.0.16/framework/UPGRADE.md#upgrade-from-yii-207 | <?php
/**
* @link http://foundationize.com
* @package foundationize/yii2-foundation
* @version dev
*/
namespace foundationize\foundation;
use Yii;
use yii\helpers\Html;
class FnActiveForm extends \yii\widgets\ActiveForm {
public $fieldClass = 'foundationize\foundation\FnActiveField';
public $layout = 'default';
/**
* Override default settings for form
*/
//public $errorCssClass = 'form-error';
/**
* @inheritdoc
*/
public function init() {
if (!in_array($this->layout, ['default', 'inline'])) {
throw new InvalidConfigException('Invalid layout type: ' . $this->layout);
}
if ($this->layout !== 'default') {
Html::addCssClass($this->options, 'form-' . $this->layout);
}
parent::init();
}
/**
* @inheritdoc
*/
public function run() {
$view = $this->getView();
ActiveFormAsset::register($view);
return parent::run();
}
}
| <?php
/**
* @link http://foundationize.com
* @package foundationize/yii2-foundation
* @version dev
*/
namespace foundationize\foundation;
use Yii;
use yii\helpers\Html;
class FnActiveForm extends \yii\widgets\ActiveForm {
public $fieldClass = 'foundationize\foundation\FnActiveField';
public $layout = 'default';
/**
* Override default settings for form
*/
//public $errorCssClass = 'form-error';
/**
* @inheritdoc
*/
public function init() {
if (!in_array($this->layout, ['default', 'inline'])) {
throw new InvalidConfigException('Invalid layout type: ' . $this->layout);
}
if ($this->layout !== 'default') {
Html::addCssClass($this->options, 'form-' . $this->layout);
}
parent::init();
}
/**
* @inheritdoc
*/
public function run() {
parent::run();
$view = $this->getView();
ActiveFormAsset::register($view);
}
}
|
Fix permission grouping bug resulting in incorrect permission checking | <?php
declare(strict_types=1);
namespace muqsit\playervaults;
use Ds\Set;
use pocketmine\Player;
use pocketmine\utils\Config;
final class PermissionManager{
/** @var Set<string>[] */
private $grouping = [];
public function __construct(Config $config){
if($config->get("enabled", false)){
foreach($config->get("permissions") as $permission => $vaults){
$this->registerGroup($permission, $vaults);
}
}
}
public function registerGroup(string $permission, int $vaults) : void{
if(!isset($this->grouping[$vaults])){
$this->grouping[$vaults] = new Set();
krsort($this->grouping);
}
$this->grouping[$vaults]->add($permission);
}
public function hasPermission(Player $player, int $vault) : bool{
if($player->hasPermission("playervaults.vault.{$vault}")){
return true;
}
foreach($this->grouping as $max_vaults => $permissions){
if($max_vaults < $vault){
break;
}
foreach($permissions as $permission){
if($player->hasPermission($permission)){
return true;
}
}
}
return false;
}
} | <?php
declare(strict_types=1);
namespace muqsit\playervaults;
use Ds\Set;
use pocketmine\Player;
use pocketmine\utils\Config;
final class PermissionManager{
/** @var Set<string>[] */
private $grouping = [];
public function __construct(Config $config){
if($config->get("enabled", false)){
foreach($config->get("permissions") as $permission => $vaults){
$this->registerGroup($permission, $vaults);
}
}
}
public function registerGroup(string $permission, int $vaults) : void{
if(!isset($this->grouping[$vaults])){
$this->grouping[$vaults] = new Set();
ksort($this->grouping);
}
$this->grouping[$vaults]->add($permission);
}
public function hasPermission(Player $player, int $vault) : bool{
if($player->hasPermission("playervaults.vault.{$vault}")){
return true;
}
foreach($this->grouping as $max_vaults => $permissions){
if($max_vaults < $vault){
break;
}
foreach($permissions as $permission){
if($player->hasPermission($permission)){
return true;
}
}
}
return false;
}
} |
Document dependency on CakePHP Migration plugin | <?php
namespace OrcaServices\Heartbeat\Heartbeat\Sensor;
use Cake\Core\Plugin;
use Migrations\Migrations;
use OrcaServices\Heartbeat\Heartbeat\Sensor;
/**
* DB Up to Date Sensor
*
* This sensor depends on the CakePHP Migrations plugin
*
* @link https://github.com/cakephp/migrations/
*/
class DBUpToDate extends Sensor
{
/**
* Migration status indicating the migration was executed successfully
*/
const MIGRATION_STATUS_UP = 'up';
/**
* @inheritdoc
*/
protected function _getStatus()
{
if (!Plugin::loaded('Migrations')) {
Plugin::load('Migrations');
}
$dbMigrated = true;
try {
$migrations = new Migrations();
$status = $migrations->status();
$lastStatus = array_pop($status);
if ($lastStatus['status'] !== self::MIGRATION_STATUS_UP) {
$dbMigrated = false;
}
} catch (\Exception $e) {
$dbMigrated = false;
}
return $dbMigrated;
}
}
| <?php
namespace OrcaServices\Heartbeat\Heartbeat\Sensor;
use Cake\Core\Plugin;
use Migrations\Migrations;
use OrcaServices\Heartbeat\Heartbeat\Sensor;
/**
* DB Up to Date Sensor
*/
class DBUpToDate extends Sensor
{
/**
* Migration status indicating the migration was executed successfully
*/
const MIGRATION_STATUS_UP = 'up';
/**
* @inheritdoc
*/
protected function _getStatus()
{
if (!Plugin::loaded('Migrations')) {
Plugin::load('Migrations');
}
$dbMigrated = true;
try {
$migrations = new Migrations();
$status = $migrations->status();
$lastStatus = array_pop($status);
if ($lastStatus['status'] !== self::MIGRATION_STATUS_UP) {
$dbMigrated = false;
}
} catch (\Exception $e) {
$dbMigrated = false;
}
return $dbMigrated;
}
}
|
Drop RSSCloud queue items if the notice has a bogus profile, rather than attempting to rerun it due to the initial erroring-out. That's not a recoverable error | <?php
/*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2008, 2009, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
class RSSCloudQueueHandler extends QueueHandler
{
function transport()
{
return 'rsscloud';
}
function handle($notice)
{
try {
$profile = $notice->getProfile();
} catch (Exception $e) {
common_log(LOG_ERR, "Dropping RSSCloud item for notice with bogus profile: " . $e->getMessage());
return true;
}
$notifier = new RSSCloudNotifier();
return $notifier->notify($profile);
}
}
| <?php
/*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2008, 2009, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
class RSSCloudQueueHandler extends QueueHandler
{
function transport()
{
return 'rsscloud';
}
function handle($notice)
{
$profile = $notice->getProfile();
$notifier = new RSSCloudNotifier();
return $notifier->notify($profile);
}
}
|
Drop time-left from job stats. | package main
import (
"fmt"
)
func inspectJob(id uint64) (err error) {
body, err := conn.Peek(id)
stats, _ := conn.StatsJob(id)
if err != nil {
return fmt.Errorf("Unknown job %v", id)
}
printJob(id, body, stats)
return
}
func nextJobs(state string) {
for _, t := range ctubes {
fmt.Printf("Next %s job in %s:\n", state, t.Name)
if id, body, err := peekState(t, state); err == nil {
stats, _ := conn.StatsJob(id)
printJob(id, body, stats)
fmt.Println()
}
}
}
func printJob(id uint64, body []byte, stats map[string]string) {
fmt.Printf("%25s: %v\n", "id", id)
fmt.Printf("%25s:\n---------------------\n%s\n---------------------\n", "body", body)
var include = []string{
"tube",
"age",
"reserves",
"kicks",
"delay",
"releases",
"pri",
"ttr",
"timeouts",
"buries",
}
printStats(stats, include)
}
| package main
import (
"fmt"
)
func inspectJob(id uint64) (err error) {
body, err := conn.Peek(id)
stats, _ := conn.StatsJob(id)
if err != nil {
return fmt.Errorf("Unknown job %v", id)
}
printJob(id, body, stats)
return
}
func nextJobs(state string) {
for _, t := range ctubes {
fmt.Printf("Next %s job in %s:\n", state, t.Name)
if id, body, err := peekState(t, state); err == nil {
stats, _ := conn.StatsJob(id)
printJob(id, body, stats)
fmt.Println()
}
}
}
func printJob(id uint64, body []byte, stats map[string]string) {
fmt.Printf("%25s: %v\n", "id", id)
fmt.Printf("%25s:\n---------------------\n%s\n---------------------\n", "body", body)
var include = []string{
"tube",
"age",
"reserves",
"kicks",
"delay",
"releases",
"pri",
"ttr",
"time-left",
"timeouts",
"buries",
}
printStats(stats, include)
}
|
Use `logrus` instead of `log` in import | package middleware
import (
"time"
"github.com/sirupsen/logrus"
"gopkg.in/gin-gonic/gin.v1"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
requestID, _ := c.Get("request_id")
logger := logrus.WithField("request_id", requestID)
c.Set("logger", logger)
start := time.Now()
c.Next()
end := time.Now()
method := c.Request.Method
path := c.Request.URL.Path
latency := end.Sub(start)
logger.WithFields(logrus.Fields{
"method": method,
"path": path,
"status": c.Writer.Status(),
"client_ip": c.ClientIP(),
"latency": latency,
"bytes": c.Writer.Size(),
}).Infof("%s %s", method, path)
}
}
| package middleware
import (
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/gin-gonic/gin.v1"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
requestID, _ := c.Get("request_id")
logger := log.WithField("request_id", requestID)
c.Set("logger", logger)
start := time.Now()
c.Next()
end := time.Now()
method := c.Request.Method
path := c.Request.URL.Path
latency := end.Sub(start)
logger.WithFields(log.Fields{
"method": method,
"path": path,
"status": c.Writer.Status(),
"client_ip": c.ClientIP(),
"latency": latency,
"bytes": c.Writer.Size(),
}).Infof("%s %s", method, path)
}
}
|
Modify the name of package | import os
from setuptools import find_packages, setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def requirements(fname):
return [line.strip()
for line in open(os.path.join(os.path.dirname(__file__), fname))]
setup(
name='slacklog',
version='0.2.0',
author='Tatsuya NAKAMURA',
author_email='nkmrtty.com@gmail.com',
description='A tool for logging messages on your Slack term.',
license='MIT',
url='https://github.com/nkmrtty/slacklog/',
packages=find_packages(),
keywords=['slack', 'logging', 'api'],
install_requires=['slackclient']
)
| import os
from setuptools import find_packages, setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def requirements(fname):
return [line.strip()
for line in open(os.path.join(os.path.dirname(__file__), fname))]
setup(
name='slacklogger',
version='0.2.0',
author='Tatsuya NAKAMURA',
author_email='nkmrtty.com@gmail.com',
description='A tool for logging messages on your Slack term.',
license='MIT',
url='https://github.com/nkmrtty/SlackLogger/',
packages=find_packages(),
keywords=['slack', 'logging', 'api'],
install_requires=['slackclient']
)
|
Replace spacing option with delimiter | 'use strict';
var fio = require('imacros-fio');
var vsprintf = require('format').vsprintf;
var formatDate = require('isolocaldateformat');
function FileTransport ( options ){
options = options || {};
// Transport must set groupsEnabled and groupsDisabled to provide transport
// level support for overriding what groups to log
// (NOTE - the user does not need to pass in groupsEnabled, but the
// transport must set these properties)
this.groupsEnabled = options.groupsEnabled;
this.groupsDisabled = options.groupsDisabled;
// Transport specific settings
// ------------------------------
this.logFileName = options.logFileName;
this.delimiter = options.delimiter === undefined ? '\t' : options.delimiter;
return this;
}
FileTransport.prototype.name = 'FileTransport';
FileTransport.prototype.log = function FileTransportLog( loggedObject ){
// Do something with loggedObject
//window.console.log(loggedObject);
var delim = this.delimiter;
var time = formatDate(new Date(loggedObject.unixTimestamp * 1000));
var group = loggedObject.group;
var message = time + delim + group;
if (loggedObject.originalArgs.length > 0)
message += delim + vsprintf(loggedObject.message, loggedObject.originalArgs);
else {
message += delim + loggedObject.message;
}
fio.append(this.logFileName, message + '\n');
return this;
};
module.exports = FileTransport;
| 'use strict';
var fio = require('imacros-fio');
var vsprintf = require('format').vsprintf;
var formatDate = require('isolocaldateformat');
function FileTransport ( options ){
options = options || {};
// Transport must set groupsEnabled and groupsDisabled to provide transport
// level support for overriding what groups to log
// (NOTE - the user does not need to pass in groupsEnabled, but the
// transport must set these properties)
this.groupsEnabled = options.groupsEnabled;
this.groupsDisabled = options.groupsDisabled;
// Transport specific settings
// ------------------------------
this.logFileName = options.logFileName;
this.spacing = options.spacing === undefined ? '\t' : options.spacing;
return this;
}
FileTransport.prototype.name = 'FileTransport';
FileTransport.prototype.log = function FileTransportLog( loggedObject ){
// Do something with loggedObject
//window.console.log(loggedObject);
var spacing = this.spacing;
var time = formatDate(new Date(loggedObject.unixTimestamp * 1000));
var group = loggedObject.group;
var message = time + spacing + group;
if (loggedObject.originalArgs.length > 0)
message += spacing + vsprintf(loggedObject.message, loggedObject.originalArgs);
else {
message += spacing + loggedObject.message;
}
fio.append(this.logFileName, message + '\n');
return this;
};
module.exports = FileTransport;
|
Set version to 0.5.2 to publish on Pypi | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend client library
This module is a Python library used the REST API of the Alignak backend
"""
# Application version and manifest
VERSION = (0, 5, 2)
__application__ = u"Alignak Backend client"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend client library"
__releasenotes__ = u"""Alignak backend client library"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-client"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend client library
This module is a Python library used the REST API of the Alignak backend
"""
# Application version and manifest
VERSION = (0, 5, 1)
__application__ = u"Alignak Backend client"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend client library"
__releasenotes__ = u"""Alignak backend client library"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-client"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
Remove now-deleted font reference from Page component | import React from 'react'
import GoogleAnalyticsScript from './scripts/google-analytics'
export default Page
function Page({
children,
title = 'JavaScript Air',
description = 'The live JavaScript podcast all about JavaScript and the web platform. Available on YouTube, iTunes, and an RSS audio feed',
} = {}) {
/* eslint max-len:0 */
return (
<html>
<head lang="en">
<title>{title}</title>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="google-site-verification" content="85n8ZBk_3hSeShlRmsVJXgDolakFG4UsMJgpy3mQyPs" />
<meta name="theme-color" content="#155674" />
<meta name="author" content="Kent C. Dodds" />
<meta name="description" content={description} />
<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
<link rel="stylesheet" href="/styles.dist.css" />
</head>
<body>
{children}
<GoogleAnalyticsScript />
</body>
</html>
)
}
| import React from 'react'
import GoogleAnalyticsScript from './scripts/google-analytics'
export default Page
function Page({
children,
title = 'JavaScript Air',
description = 'The live JavaScript podcast all about JavaScript and the web platform. Available on YouTube, iTunes, and an RSS audio feed',
} = {}) {
/* eslint max-len:0 */
return (
<html>
<head lang="en">
<title>{title}</title>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="google-site-verification" content="85n8ZBk_3hSeShlRmsVJXgDolakFG4UsMJgpy3mQyPs" />
<meta name="theme-color" content="#155674" />
<meta name="author" content="Kent C. Dodds" />
<meta name="description" content={description} />
<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
<link rel="stylesheet" href="/styles.dist.css" />
<link rel="stylesheet" href="/resources/font/font.css" />
</head>
<body>
{children}
<GoogleAnalyticsScript />
</body>
</html>
)
}
|
Change project image class names | import React from 'react';
import BuildingWithPoetic from './BuildingWithPoetic';
import ProjectInfoList from './ProjectInfoList';
const poeticUrl = 'http://www.poeticsystems.com';
class ProjectItem extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
const { project } = this.props;
return (
<div className="project-item">
<a href={project.url || poeticUrl} target="_blank" className="project-img-container">
<div className="project-img-overlay"></div>
<img className="project-img" src={project.image} />
</a>
<div className="project-info">
<h1 className="project-name">{project.name}</h1>
<p className="project-description">{project.description}</p>
<ProjectInfoList subtitle="Languages" list={project.languages} />
<ProjectInfoList subtitle="Tools" list={project.tools} />
<a href={project.url || poeticUrl} target="_blank" className="project-btn button red">
{project.url ? 'View' : <BuildingWithPoetic />}
</a>
</div>
</div>
);
}
}
ProjectItem.propTypes = {
project: React.PropTypes.object.isRequired,
};
export default ProjectItem;
| import React from 'react';
import BuildingWithPoetic from './BuildingWithPoetic';
import ProjectInfoList from './ProjectInfoList';
const poeticUrl = 'http://www.poeticsystems.com';
class ProjectItem extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
const { project } = this.props;
return (
<div className="project-item">
<a href={project.url || poeticUrl} target="_blank" className="project-img-wrapper">
<div className="project-overlay"></div>
<img className="project-img" src={project.image} />
</a>
<div className="project-info">
<h1 className="project-name">{project.name}</h1>
<p className="project-description">{project.description}</p>
<ProjectInfoList subtitle="Languages" list={project.languages} />
<ProjectInfoList subtitle="Tools" list={project.tools} />
<a href={project.url || poeticUrl} target="_blank" className="project-btn button red">
{project.url ? 'View' : <BuildingWithPoetic />}
</a>
</div>
</div>
);
}
}
ProjectItem.propTypes = {
project: React.PropTypes.object.isRequired,
};
export default ProjectItem;
|
Check if the bot is sending the commands, and if so wait a little (twitch limitation) | BOT.client.addListener('message' + BOT.settings.channel, function (from, message) {
BOT.logMessage('[' + BOT.settings.channel + '] ' + from + ": " + message);
if (message.charAt(0) == '!') {
var parts = message.split(' ');
var command = parts[0].substr(1, parts[0].length);
var cmd = BOT.getCommand(command);
if (cmd) {
BOT.logInfo('executing command: ' + command);
if (BOT.settings.name.toLowerCase() == from.toLowerCase()) {
setTimeout(function () {
cmd(from, parts.splice(1));
}, 1200);
} else {
cmd(from, parts.splice(1));
}
}
}
});
BOT.client.addListener('error', function (message) {
BOT.logInfo('error: ' + message);
});
BOT.client.addListener('registered', function (e) {
BOT.logInfo('Now Connected to ' + e.server);
});
BOT.client.addListener('join', function (channel) {
BOT.logInfo('Joined ' + channel);
}); | BOT.client.addListener('message' + BOT.settings.channel, function (from, message) {
BOT.logMessage('[' + BOT.settings.channel + '] ' + from + ": " + message);
if (message.charAt(0) == '!') {
var parts = message.split(' ');
var command = parts[0].substr(1, parts[0].length);
var cmd = BOT.getCommand(command);
if (cmd) {
BOT.logInfo('executing command: ' + command);
cmd(from, parts.splice(1));
}
}
});
BOT.client.addListener('error', function (message) {
BOT.logInfo('error: ' + message);
});
BOT.client.addListener('registered', function (e) {
BOT.logInfo('Now Connected to ' + e.server);
});
BOT.client.addListener('join', function (channel) {
BOT.logInfo('Joined ' + channel);
}); |
Fix a bug in combineClassNames
There was a bug in the implementation of combineClassNames
which resulted in undefined values to be merge in the combined
className string. | import moment from 'moment';
/**
* Concatenates class names given as an array of strings or
* undefined values into a string compatible with "className" property.
* @param {Array<String>} classNames Array of values to concatenate
* @return {String} className compatible string
*/
function combineClassNames(...classNames) {
return classNames.reduce((acc, name) => {
if (name === '' || name === undefined) {
return acc;
}
return `${acc} ${name}`;
}, '').trim();
}
/**
* Returns a current year;
* @return {Number} Current year
*/
function currentYear() {
return new Date().getFullYear();
}
/**
* Returns a function that cycles through
* a collection indefinitely.
* @param {Any} collection
* @return {Function}
*/
function cycle(collection) {
let index = 0;
return function () {
const result = collection[index];
if ((index + 1) === collection.length) {
index = 0;
} else {
index += 1;
}
return result;
};
}
function toHumanReadableDate(timestamp) {
return moment(timestamp).fromNow();
}
export { combineClassNames, currentYear, cycle, toHumanReadableDate };
| import moment from 'moment';
/**
* Concatenates class names given as an array of strings or
* undefined values into a string compatible with "className" property.
* @param {Array<String>} classNames Array of values to concatenate
* @return {String} className compatible string
*/
function combineClassNames(...classNames) {
return classNames.reduce((name, acc) => {
if (name && name !== '') {
return `${acc} ${name}`;
}
return acc;
}, '');
}
/**
* Returns a current year;
* @return {Number} Current year
*/
function currentYear() {
return new Date().getFullYear();
}
/**
* Returns a function that cycles through
* a collection indefinitely.
* @param {Any} collection
* @return {Function}
*/
function cycle(collection) {
let index = 0;
return function () {
const result = collection[index];
if ((index + 1) === collection.length) {
index = 0;
} else {
index += 1;
}
return result;
};
}
function toHumanReadableDate(timestamp) {
return moment(timestamp).fromNow();
}
export { combineClassNames, currentYear, cycle, toHumanReadableDate };
|
Test for bigWig aggregation modes | import clodius.tiles.bigwig as hgbi
import os.path as op
def test_bigwig_tiles():
filename = op.join(
'data',
'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig'
)
meanval = hgbi.tiles(filename, ['x.0.0'])
minval = hgbi.tiles(filename, ['x.0.0.min'])
maxval = hgbi.tiles(filename, ['x.0.0.max'])
assert meanval[0][1]['max_value'] > minval[0][1]['max_value']
assert maxval[0][1]['max_value'] > meanval[0][1]['max_value']
def test_tileset_info():
filename = op.join(
'data',
'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig'
)
tileset_info = hgbi.tileset_info(filename)
assert len(tileset_info['aggregation_modes']) == 4
assert tileset_info['aggregation_modes']['mean']
assert tileset_info['aggregation_modes']['min']
assert tileset_info['aggregation_modes']['max']
assert tileset_info['aggregation_modes']['std']
| import clodius.tiles.bigwig as hgbi
import os.path as op
def test_bigwig_tiles():
filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig')
meanval = hgbi.tiles(filename, ['x.0.0'])
minval = hgbi.tiles(filename, ['x.0.0.min'])
maxval = hgbi.tiles(filename, ['x.0.0.max'])
assert meanval[0][1]['max_value'] > minval[0][1]['max_value']
assert maxval[0][1]['max_value'] > meanval[0][1]['max_value']
def test_tileset_info():
filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig')
tileset_info = hgbi.tileset_info(filename)
# print('tileset_info', tileset_info)
|
Update the version for manifest update | from setuptools import setup
PACKAGE_VERSION = '1.0.1'
deps = []
setup(name='wptserve',
version=PACKAGE_VERSION,
description="Python webserver intended for in web browser testing",
long_description=open("README.md").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=["Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers"],
keywords='',
author='James Graham',
author_email='james@hoppipolla.co.uk',
url='http://wptserve.readthedocs.org/',
license='BSD',
packages=['wptserve'],
include_package_data=True,
zip_safe=False,
install_requires=deps
)
| from setuptools import setup
PACKAGE_VERSION = '1.0'
deps = []
setup(name='wptserve',
version=PACKAGE_VERSION,
description="Python webserver intended for in web browser testing",
long_description=open("README.md").read(),
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=["Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers"],
keywords='',
author='James Graham',
author_email='james@hoppipolla.co.uk',
url='http://wptserve.readthedocs.org/',
license='BSD',
packages=['wptserve'],
include_package_data=True,
zip_safe=False,
install_requires=deps
)
|
Add isOwner EntityPlayer signature method to the interface. | /*
* Aeronica's mxTune MOD
* Copyright {2016} Paul Boese a.k.a. Aeronica
*
* 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 net.aeronica.mods.mxtune.world;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.IWorldNameable;
import net.minecraft.world.LockCode;
public interface IModLockableContainer extends IWorldNameable
{
boolean isLocked();
void setLockCode(LockCode code);
LockCode getLockCode();
boolean isOwner(OwnerUUID ownerUUID);
boolean isOwner(EntityPlayer entityPlayer);
void setOwner(OwnerUUID ownerUUID);
OwnerUUID getOwner();
}
| /*
* Aeronica's mxTune MOD
* Copyright {2016} Paul Boese a.k.a. Aeronica
*
* 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 net.aeronica.mods.mxtune.world;
import net.minecraft.world.IWorldNameable;
import net.minecraft.world.LockCode;
public interface IModLockableContainer extends IWorldNameable
{
boolean isLocked();
void setLockCode(LockCode code);
LockCode getLockCode();
boolean isOwner(OwnerUUID ownerUUID);
void setOwner(OwnerUUID ownerUUID);
OwnerUUID getOwner();
}
|
Use real path to WebTorrent.exe | var electron = require('electron')
var app = electron.app
module.exports = function () {
if (process.platform === 'win32') {
registerProtocolHandler('magnet', 'URL:BitTorrent Magnet URL', app.getPath('exe'))
}
}
function registerProtocolHandler (protocol, name, command) {
var Registry = require('winreg')
var protocolKey = new Registry({
hive: Registry.HKCU, // HKEY_CURRENT_USER
key: '\\Software\\Classes\\' + protocol
})
protocolKey.set('', Registry.REG_SZ, name, callback)
protocolKey.set('URL Protocol', Registry.REG_SZ, '', callback)
var commandKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\' + protocol + '\\shell\\open\\command'
})
commandKey.set('', Registry.REG_SZ, '"' + command + '" "%1"', callback)
function callback (err) {
if (err) console.error(err.message || err)
}
}
| module.exports = function () {
if (process.platform === 'win32') {
registerProtocolHandler('magnet', 'URL:BitTorrent Magnet URL', 'WebTorrent.exe')
}
}
function registerProtocolHandler (protocol, name, command) {
var Registry = require('winreg')
var protocolKey = new Registry({
hive: Registry.HKCU, // HKEY_CURRENT_USER
key: '\\Software\\Classes\\' + protocol
})
protocolKey.set('', Registry.REG_SZ, name, callback)
protocolKey.set('URL Protocol', Registry.REG_SZ, '', callback)
var commandKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Classes\\' + protocol + '\\shell\\open\\command'
})
commandKey.set('', Registry.REG_SZ, '"' + command + '" "%1"', callback)
function callback (err) {
if (err) console.error(err.message || err)
}
}
|
Add option inn page test | <?php
require 'classes/Tmdb/Tmdb.php';
require 'classes/Tmdb/Movie.php';
require 'classes/Tmdb/TVShow.php';
$api_key = '62dfe9839b8937e595e325a4144702ad';
$VfacTmdb = new Vfac\Tmdb\Tmdb($api_key);
$results = [];
//$results = $VfacTmdb->searchMovie('star wars', array('language' => 'fr-FR'));
$results[] = $VfacTmdb->getMovieDetails(11, array('language' => 'fr-FR')); // star wars
foreach ($results as $movie)
{
echo <<<RES
{$movie->getId()}<br />
{$movie->getTitle()}<br />
{$movie->getOriginalTitle()}<br />
{$movie->getOverview()}<br />
{$movie->getNote()}<br />
{$movie->getReleaseDate()}<br />
{$movie->getPoster()}<br />
{$movie->getBackdrop()}<br />
{$movie->getGenres()}<br />
<hr />
RES;
echo $movie->raw;
}
| <?php
require 'classes/Tmdb/Tmdb.php';
require 'classes/Tmdb/Movie.php';
require 'classes/Tmdb/TVShow.php';
$api_key = '62dfe9839b8937e595e325a4144702ad';
$VfacTmdb = new Vfac\Tmdb\Tmdb($api_key);
$VfacTmdb->setLanguage('fr-FR');
$results = [];
//$results = $VfacTmdb->searchMovie('star wars');
$results[] = $VfacTmdb->getMovieDetails(11); // star wars
foreach ($results as $movie)
{
echo <<<RES
{$movie->getId()}<br />
{$movie->getTitle()}<br />
{$movie->getOriginalTitle()}<br />
{$movie->getOverview()}<br />
{$movie->getNote()}<br />
{$movie->getReleaseDate()}<br />
{$movie->getPoster()}<br />
{$movie->getBackdrop()}<br />
{$movie->getGenres()}<br />
<hr />
RES;
echo $movie->raw;
}
|
Load the correct config for new Symfony environment | <?php
use Sylius\Bundle\CoreBundle\Application\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use SitemapPlugin\SitemapPlugin;
final class AppKernel extends Kernel
{
/**
* {@inheritdoc}
*/
public function registerBundles()
{
return array_merge(parent::registerBundles(), [
new \Sylius\Bundle\AdminBundle\SyliusAdminBundle(),
new \Sylius\Bundle\ShopBundle\SyliusShopBundle(),
new \FOS\OAuthServerBundle\FOSOAuthServerBundle(), // Required by SyliusApiBundle
new \Sylius\Bundle\AdminApiBundle\SyliusAdminApiBundle(),
new SitemapPlugin(),
]);
}
/**
* {@inheritdoc}
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
if ($this->getEnvironment() === 'test_relative') {
$loader->load($this->getRootDir() . '/config/config_test_relative.yml');
return;
}
$loader->load($this->getRootDir() . '/config/config.yml');
}
}
| <?php
use Sylius\Bundle\CoreBundle\Application\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use SitemapPlugin\SitemapPlugin;
final class AppKernel extends Kernel
{
/**
* {@inheritdoc}
*/
public function registerBundles()
{
return array_merge(parent::registerBundles(), [
new \Sylius\Bundle\AdminBundle\SyliusAdminBundle(),
new \Sylius\Bundle\ShopBundle\SyliusShopBundle(),
new \FOS\OAuthServerBundle\FOSOAuthServerBundle(), // Required by SyliusApiBundle
new \Sylius\Bundle\AdminApiBundle\SyliusAdminApiBundle(),
new SitemapPlugin(),
]);
}
/**
* {@inheritdoc}
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
if ($this->getEnvironment() === 'test_relative') {
$loader->load($this->getRootDir() . '/config/config_relative.yml');
return;
}
$loader->load($this->getRootDir() . '/config/config.yml');
}
}
|
Add under development warning message | import React, { Component } from 'react';
import HeadMetaTags from '../../components/headMetaTags';
class DiseasePage extends Component {
render() {
const title = this.props.params.diseaseId;
return (
<div className='container'>
<HeadMetaTags title={title} />
<div className='alert alert-warning'>
<i className='fa fa-warning' /> Page under active development
</div>
<h1>
{this.props.params.diseaseId}
<hr />
</h1>
<a href={'http://www.disease-ontology.org/?id=' + this.props.params.diseaseId}>
{this.props.params.diseaseId}
</a>
</div>
);
}
}
DiseasePage.propTypes = {
params: React.PropTypes.object,
};
export default DiseasePage;
| import React, { Component } from 'react';
import HeadMetaTags from '../../components/headMetaTags';
class DiseasePage extends Component {
render() {
const title = this.props.params.diseaseId;
return (
<div className='container'>
<HeadMetaTags title={title} />
<h1>
{this.props.params.diseaseId}
<hr />
</h1>
<a href={'http://www.disease-ontology.org/?id=' + this.props.params.diseaseId}>
{this.props.params.diseaseId}
</a>
</div>
);
}
}
DiseasePage.propTypes = {
params: React.PropTypes.object,
};
export default DiseasePage;
|
Remove unneeded links from about menu | <?php
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package WordPress
* @subpackage Ally
*/
?>
<? get_header(); ?>
<!-- Content -->
<div class="content-container about">
<div class="row">
<div class="two mobile-one columns">
<ul class="side-nav" id="about-menu" data-spy="affix" data-offset-top="205">
<li><a href="#mission">Mission</a></li>
<li><a href="#staff">Staff</a></li>
<li><a href="#board">Board</a></li>
</ul>
</div>
<div class="ten mobile-three columns" id="about-container">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
</div>
</div>
</div>
<?php get_footer(); ?> | <?php
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package WordPress
* @subpackage Ally
*/
?>
<? get_header(); ?>
<!-- Content -->
<div class="content-container about">
<div class="row">
<div class="two mobile-one columns">
<ul class="side-nav" id="about-menu" data-spy="affix" data-offset-top="205">
<li><a href="#mission">Mission</a></li>
<li><a href="#board">Board</a></li>
<li><a href="#staff">Staff</a></li>
<li><a href="#jobs">Jobs</a></li>
<li><a href="#inthenews">In The News</a></li>
<li><a href="#press">Press Releases</a></li>
</ul>
</div>
<div class="ten mobile-three columns" id="about-container">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
</div>
</div>
</div>
<?php get_footer(); ?> |
Add node env location to script header. | #!/usr/bin/env node
const
fs = require('fs');
/* Remove all white space from str. */
function minifyString(str) {
return str.replace(/\s/g, '');
};
/* Insert .min extension to FileName. */
function addMinExtension(FileName) {
var fileExtIndex = FileName.indexOf('.')
, filePrefix = FileName.slice(0, fileExtIndex)
, fileExten = FileName.slice(fileExtIndex, FileName.length)
, minFileName = filePrefix + '.min' + fileExten;
return minFileName;
};
/* Removes white space from file and writes minified data to a new file. */
(function main() {
/* Read the file into a string */
var filePath = process.argv[2]
, fileContent = fs.readFileSync(filePath, 'utf8')
, minFileContent = minifyString(fileContent)
, minFileName = addMinExtension(filePath);
var minifiedFile = fs.writeFile(minFileName, minFileContent, function(err) {
if (err) { throw err; };
console.log('-- ' + filePath + ' minified to ' + minFileName + ' --');
});
})();
| const
fs = require('fs');
/* Remove all white space from str. */
function minifyString(str) {
return str.replace(/\s/g, '');
};
/* Insert .min extension to FileName. */
function addMinExtension(FileName) {
var fileExtIndex = FileName.indexOf('.')
, filePrefix = FileName.slice(0, fileExtIndex)
, fileExten = FileName.slice(fileExtIndex, FileName.length)
, minFileName = filePrefix + '.min' + fileExten;
return minFileName;
};
/* Removes white space from file and
writes new minified file. */
(function main() {
/* Read the file into a string */
var filePath = process.argv[2]
, fileContent = fs.readFileSync(filePath, 'utf8')
, minFileContent = minifyString(fileContent)
, minFileName = addMinExtension(filePath);
var minifiedFile = fs.writeFile(minFileName, minFileContent, function(err) {
if (err) { throw err; };
console.log('-- ' + filePath + ' minified to ' + minFileName + ' --');
});
})();
|
[ogm/hiking] Move to explicit generator to avoid warning | package org.hibernate.ogm.hiking.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OrderColumn;
import javax.validation.constraints.NotNull;
@Entity
public class Hike {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
public long id;
@NotNull
public String start;
@NotNull
public String destination;
@ManyToOne
public Person organizer;
@ElementCollection
@OrderColumn(name="order")
public List<Section> sections = new ArrayList<>();
Hike() {
}
public Hike(String start, String destination) {
this.start = start;
this.destination = destination;
}
}
| package org.hibernate.ogm.hiking.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OrderColumn;
import javax.validation.constraints.NotNull;
@Entity
public class Hike {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long id;
@NotNull
public String start;
@NotNull
public String destination;
@ManyToOne
public Person organizer;
@ElementCollection
@OrderColumn(name="order")
public List<Section> sections = new ArrayList<>();
Hike() {
}
public Hike(String start, String destination) {
this.start = start;
this.destination = destination;
}
}
|
[Feature] Add Login, Registration, Bucketlists endpoints. | """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResource, \
BucketListApi, UserLogin, UserRegister
app = flask_app
api = Api(app=app, prefix='/api/v1.0')
manager = Manager(app)
migrate = Migrate(app, db)
# add resources
api.add_resource(TestResource, '/')
api.add_resource(BucketListApi, '/bucketlists/')
api.add_resource(UserLogin, '/auth/login/')
api.add_resource(UserRegister, '/auth/register/')
def make_shell_context():
"""Add app, database and models to the shell."""
return dict(app=app, db=db, User=User, BucketList=BucketList,
BucketListItem=BucketListItem)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def run_tests():
"""Run tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
| """This module runs the api server."""
import os
from app import flask_app, db
from app.models import User, BucketList, BucketListItem
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.restful import Resource, Api
from app.api_v1.resources import TestResource, BucketListApi
app = flask_app
api = Api(app=app, prefix='/api/v1.0')
manager = Manager(app)
migrate = Migrate(app, db)
# add resources
api.add_resource(TestResource, '/')
api.add_resource(BucketListApi, '/user/<user_id>/bucketlists/')
def make_shell_context():
"""Add app, database and models to the shell."""
return dict(app=app, db=db, User=User, BucketList=BucketList,
BucketListItem=BucketListItem)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def run_tests():
"""Run tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
|
Replace T with void in create method. | /*
* Copyright 2016, Frederik Boster
*
* 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 de.syquel.bushytail.controller;
import org.apache.olingo.server.api.uri.UriParameter;
import java.util.List;
/**
* Interface for all ODataControllers. Provides CRUD Operations.
*
* @author Clemens Bartz
* @author Frederik Boster
* @since 1.0
*
* @param <T> Entity which is handled by the controller.
*/
public interface IBushyTailController<T> {
T read(List<UriParameter> keyPredicates);
void create(T entity);
}
| /*
* Copyright 2016, Frederik Boster
*
* 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 de.syquel.bushytail.controller;
import org.apache.olingo.server.api.uri.UriParameter;
import java.util.List;
/**
* Interface for all ODataControllers. Provides CRUD Operations.
*
* @author Clemens Bartz
* @author Frederik Boster
* @since 1.0
*
* @param <T> Entity which is handled by the controller.
*/
public interface IBushyTailController<T> {
T read(List<UriParameter> keyPredicates);
T create(T entity);
}
|
Check that the .doc and .pdf files exist before we blindly set the asset path to the file. | <?php
use Illuminate\Filesystem\Filesystem;
class Document {
private static function getFiles ($path, $type, $extension = null)
{
$result = array();
foreach ( glob($path . '/' . $type . "/*.pdf") as $file )
{
$filename = pathinfo($file, PATHINFO_FILENAME);
array_push($result, array(
'title' => $filename,
'doc' => file_exists($path . '/' . $type . '/' . $filename . '.doc') ? '/assets/documents/' . $type . '/' . $filename . '.doc' : '',
'pdf' => file_exists($path . '/' . $type . '/' . $filename . '.pdf') ? '/assets/documents/' . $type . '/' . $filename . '.pdf' : ''
));
}
return $result;
}
/**
* Get all the forms that are in pdf|doc format.
*
* @return array
*/
public static function getForms ()
{
return Document::getFiles(dirname(__FILE__) . "/../../irexinc.org/assets/documents", "forms");
}
public static function getMinutes ()
{
$result = Document::getFiles(dirname(__FILE__) . "/../../irexinc.org/assets/documents", "minutes");
foreach ($result as $index => $file)
{
$title = explode(' ', $file['title']);
$result[$index]['title'] = strftime('%B %e, %Y', strtotime(end($title)));
}
return $result;
}
} | <?php
use Illuminate\Filesystem\Filesystem;
class Document {
private static function getFiles ($path, $type, $extension = null)
{
$result = array();
foreach ( glob($path . '/' . $type . "/*.pdf") as $file )
{
$filename = pathinfo($file, PATHINFO_FILENAME);
array_push($result, array(
'title' => $filename,
'doc' => '/assets/documents/' . $type . '/' . $filename . '.doc',
'pdf' => '/assets/documents/' . $type . '/' . $filename . '.pdf'
));
}
return $result;
}
/**
* Get all the forms that are in pdf|doc format.
*
* @return array
*/
public static function getForms ()
{
return Document::getFiles(dirname(__FILE__) . "/../../irexinc.org/assets/documents", "forms");
}
public static function getMinutes ()
{
$result = Document::getFiles(dirname(__FILE__) . "/../../irexinc.org/assets/documents", "minutes");
foreach ($result as $index => $file)
{
$title = explode(' ', $file['title']);
$result[$index]['title'] = strftime('%B %e, %Y', strtotime(end($title)));
}
return $result;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.