text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use threads to allow simultaneous serving of site and building of assets | """Task functions for use with Invoke."""
from threading import Thread
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def serve(context, host='127.0.0.1', port='5000'):
steps = [
'open http://{host}:{port}/',
'FLASK_APP=typesetter/typesetter.py FLASK_DEBUG=1 flask run --host={host} --port={port}',
]
steps = [step.format(host=host, port=port) for step in steps]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def static(context):
cmd = '$(npm bin)/gulp'
context.run(cmd)
@task
def stream(context, host=None):
tasks = [static, serve]
threads = [Thread(target=task, args=(context,), daemon=True) for task in tasks]
[t.start() for t in threads]
[t.join() for t in threads]
| """Task functions for use with Invoke."""
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def run(context, host='127.0.0.1', port='5000'):
steps = [
'open http://{host}:{port}/',
'FLASK_APP=typesetter/typesetter.py FLASK_DEBUG=1 flask run --host={host} --port={port}',
]
steps = [step.format(host=host, port=port) for step in steps]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def static(context):
cmd = '$(npm bin)/gulp'
context.run(cmd)
|
Set <controller> name scoped by modules 'namespace' | 'use strict';
var _ = require('lodash');
var path = require('path');
var convert = require(path.resolve(__dirname, './convert.js'));
var context = {
getDefaults: getDefaults
};
function getDefaults(name, module) {
var folderName = convert.moduleToFolder(module);
return _.clone({
module: module,
camelName: _.camelCase(name),
controller: _getController(name, module),
directive: _.camelCase(name),
directiveUrl: folderName + _.kebabCase(name) + '.directive.html',
kebabName: _.kebabCase(name),
moduleClass: _.kebabCase(module),
route: _.camelCase(name) + 'Route',
service: _.camelCase(name) + 'Service',
state: module.replace('app.modules.', ''),
templateUrl: folderName + _.kebabCase(name) + '.html'
});
}
function _getController(name, module) {
module = module.replace(/app\..*?\./, '');
return _.upperFirst(_.camelCase(module)) + 'Controller';
}
module.exports = context;
| 'use strict';
var _ = require('lodash');
var path = require('path');
var convert = require(path.resolve(__dirname, './convert.js'));
var context = {
getDefaults: getDefaults
};
function getDefaults(name, module) {
var folderName = convert.moduleToFolder(module);
return _.clone({
module: module,
camelName: _.camelCase(name),
controller: _.upperFirst(_.camelCase(name)) + 'Controller',
directive: _.camelCase(name),
directiveUrl: folderName + _.kebabCase(name) + '.directive.html',
kebabName: _.kebabCase(name),
moduleClass: _.kebabCase(module),
route: _.camelCase(name) + 'Route',
service: _.camelCase(name) + 'Service',
state: module.replace('app.modules.', ''),
templateUrl: folderName + _.kebabCase(name) + '.html'
});
}
module.exports = context;
|
Add import for variables file, set a const API_KEY as the data from variables file. | import React, { Component } from 'react';
import ReactDom from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
import file from './variables.js';
// const API_KEY = 'PLACE_YOUR_API_KEY_HERE';
const API_KEY = file.data;
class App extends Component {
constructor (props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => {
console.log(videos);
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render () {
return (
<div>
<SearchBar />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
videos={this.state.videos}
onVideoSelect={selectedVideo => this.setState({selectedVideo})}
/>
</div>
);
}
}
ReactDom.render(<App />, document.querySelector('.container')); | import React, { Component } from 'react';
import ReactDom from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
// const API_KEY = 'PLACE_YOUR_API_KEY_HERE';
class App extends Component {
constructor (props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => {
console.log(videos);
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render () {
return (
<div>
<SearchBar />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
videos={this.state.videos}
onVideoSelect={selectedVideo => this.setState({selectedVideo})}
/>
</div>
);
}
}
ReactDom.render(<App />, document.querySelector('.container')); |
Update ‘content-h1’ class name on social impact page | <?php
/*
Template name: Social Impact
*/
$si_galleries = get_posts([
'post_type'=>'si-gallery',
'sort_column'=>'menu_order',
'sort_order'=>'asc',
'numberposts'=>-1,
]);
$content = apply_filters('the_content',$post->post_content);
$contact = apply_filters('the_content',get_post_meta( $post->ID, '_cmb2_contact', true ));
?>
<div class="page-block description -bg-cream-dark -bottom-underlap">
<h2 class="content-h1">Hair Cares</h2>
<div class="user-content">
<?= $content ?>
</div>
<div class="contact user-content">
<?= $contact ?>
</div>
</div>
<?php
$posts = $si_galleries;
include(locate_template('templates/page-gallery.php'));
?> | <?php
/*
Template name: Social Impact
*/
$si_galleries = get_posts([
'post_type'=>'si-gallery',
'sort_column'=>'menu_order',
'sort_order'=>'asc',
'numberposts'=>-1,
]);
$content = apply_filters('the_content',$post->post_content);
$contact = apply_filters('the_content',get_post_meta( $post->ID, '_cmb2_contact', true ));
?>
<div class="page-block description -bg-cream-dark -bottom-underlap">
<h2 class="user-content-h1">Hair Cares</h2>
<div class="user-content">
<?= $content ?>
</div>
<div class="contact user-content">
<?= $contact ?>
</div>
</div>
<?php
$posts = $si_galleries;
include(locate_template('templates/page-gallery.php'));
?> |
Use correct icon pack name | /* eslint-env node */
'use strict'
const {setSvgConfiguration} = require('ember-frost-core/utils/frost-icon-svg')
module.exports = {
name: 'ember-frost-navigation',
included: function () {
this.app = this._findHost.call(this) // eslint-disable-line no-useless-call
// Set ember-cli-svgstore options so that consuming applications don't have to
setSvgConfiguration.call(this, 'frost-nav')
this._super.included.apply(this, arguments)
},
/* eslint-disable complexity */
init: function () {
this.options = this.options || {}
this.options.babel = this.options.babel || {}
this.options.babel.optional = this.options.babel.optional || []
if (this.options.babel.optional.indexOf('es7.decorators') === -1) {
this.options.babel.optional.push('es7.decorators')
}
// eslint-disable-next-line no-unused-expressions
this._super.init && this._super.init.apply(this, arguments)
}
/* eslint-enable complexity */
}
| /* eslint-env node */
'use strict'
const {setSvgConfiguration} = require('ember-frost-core/utils/frost-icon-svg')
module.exports = {
name: 'ember-frost-navigation',
included: function () {
this.app = this._findHost.call(this) // eslint-disable-line no-useless-call
// Set ember-cli-svgstore options so that consuming applications don't have to
setSvgConfiguration.call(this, 'frost-navigation')
this._super.included.apply(this, arguments)
},
/* eslint-disable complexity */
init: function () {
this.options = this.options || {}
this.options.babel = this.options.babel || {}
this.options.babel.optional = this.options.babel.optional || []
if (this.options.babel.optional.indexOf('es7.decorators') === -1) {
this.options.babel.optional.push('es7.decorators')
}
// eslint-disable-next-line no-unused-expressions
this._super.init && this._super.init.apply(this, arguments)
}
/* eslint-enable complexity */
}
|
Remove unused methods from signature | /*
* Copyright (C) 2013 Brett Wooldridge
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zaxxer.hikari.proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;
import com.zaxxer.hikari.util.ConcurrentBag.IBagManagable;
/**
*
* @author Brett Wooldridge
*/
public interface IHikariConnectionProxy extends Connection, IBagManagable
{
void unclose();
void realClose() throws SQLException;
void untrackStatement(Object statement);
void checkException(SQLException sqle);
boolean isBrokenConnection();
long getCreationTime();
long getLastAccess();
/* Leak Detection API */
void captureStack(long leakThreshold, Timer houseKeepingTimer);
}
| /*
* Copyright (C) 2013 Brett Wooldridge
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zaxxer.hikari.proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;
import com.zaxxer.hikari.util.ConcurrentBag.IBagManagable;
/**
*
* @author Brett Wooldridge
*/
public interface IHikariConnectionProxy extends Connection, IBagManagable
{
void unclose();
void realClose() throws SQLException;
void untrackStatement(Object statement);
void checkException(SQLException sqle);
boolean isBrokenConnection();
boolean isTransactionIsolationDirty();
boolean isAutoCommitDirty();
long getCreationTime();
long getLastAccess();
/* Leak Detection API */
void captureStack(long leakThreshold, Timer houseKeepingTimer);
}
|
Improve handling of scanning of shrinking files in subd: return zero hash. | package scanner
import (
"github.com/Symantec/Dominator/lib/filesystem/scanner"
"github.com/Symantec/Dominator/lib/objectcache"
)
func scanFileSystem(rootDirectoryName string, cacheDirectoryName string,
configuration *Configuration, oldFS *FileSystem) (*FileSystem, error) {
var fileSystem FileSystem
fileSystem.configuration = configuration
fileSystem.rootDirectoryName = rootDirectoryName
fileSystem.cacheDirectoryName = cacheDirectoryName
fs, err := scanner.ScanFileSystem(rootDirectoryName,
configuration.FsScanContext, configuration.ScanFilter,
checkScanDisableRequest, scanner.GetSimpleHasher(true),
&oldFS.FileSystem)
if err != nil {
return nil, err
}
fileSystem.FileSystem = *fs
if err = fileSystem.scanObjectCache(); err != nil {
return nil, err
}
return &fileSystem, nil
}
func (fs *FileSystem) scanObjectCache() error {
if fs.cacheDirectoryName == "" {
return nil
}
var err error
fs.ObjectCache, err = objectcache.ScanObjectCache(fs.cacheDirectoryName)
return err
}
| package scanner
import (
"github.com/Symantec/Dominator/lib/filesystem/scanner"
"github.com/Symantec/Dominator/lib/objectcache"
)
func scanFileSystem(rootDirectoryName string, cacheDirectoryName string,
configuration *Configuration, oldFS *FileSystem) (*FileSystem, error) {
var fileSystem FileSystem
fileSystem.configuration = configuration
fileSystem.rootDirectoryName = rootDirectoryName
fileSystem.cacheDirectoryName = cacheDirectoryName
fs, err := scanner.ScanFileSystem(rootDirectoryName,
configuration.FsScanContext, configuration.ScanFilter,
checkScanDisableRequest, nil, &oldFS.FileSystem)
if err != nil {
return nil, err
}
fileSystem.FileSystem = *fs
if err = fileSystem.scanObjectCache(); err != nil {
return nil, err
}
return &fileSystem, nil
}
func (fs *FileSystem) scanObjectCache() error {
if fs.cacheDirectoryName == "" {
return nil
}
var err error
fs.ObjectCache, err = objectcache.ScanObjectCache(fs.cacheDirectoryName)
return err
}
|
Update Simple Modal Component Documentation and Styling | /*!
Copyright (C) 2017 Google Inc.
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/
(function (can, GGRC) {
'use strict';
var tpl = can.view(GGRC.mustache_path +
'/components/simple-modal/simple-modal.mustache');
/**
* Simple Modal Component is a general abstraction to visualize
* modal and pop-ups with overlay.
* Simple Modal can be initialized in any part of the HTML.
* Simple Modal provides only logic less basic markup. All business logic should be placed on the level of inner components.
* To simplify styling additional helper CSS classes were created: 'simple-modal__footer', 'simple-modal__body' and 'simple-modal__header'
*/
can.Component.extend({
tag: 'simple-modal',
template: tpl,
viewModel: {
extraCssClass: '@',
instance: null,
modalTitle: '',
state: {
open: false
},
hide: function () {
this.attr('state.open', false);
},
show: function () {
this.attr('state.open', true);
}
}
});
})(window.can, window.GGRC);
| /*!
Copyright (C) 2017 Google Inc.
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/
(function (can, GGRC) {
'use strict';
var tpl = can.view(GGRC.mustache_path +
'/components/simple-modal/simple-modal.mustache');
var baseCls = 'simple-modal';
can.Component.extend({
tag: 'simple-modal',
template: tpl,
viewModel: {
extraCssClass: '@',
instance: null,
modalTitle: '',
state: {
open: false
},
hide: function () {
this.attr('state.open', false);
},
show: function () {
this.attr('state.open', true);
}
}
});
})(window.can, window.GGRC);
|
Remove commented code in NotEnoughPermutationEx | package com.hida.model;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* An exception used to display how many permutations actually remain and the requested amount
* that caused an error.
* @author lruffin
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason =
"Requested amount exceeds possible number "
+ "of permutations")
public class NotEnoughPermutationsException extends RuntimeException {
private long RemainingPermutations;
private long RequestedAmount;
public NotEnoughPermutationsException(long remaining, long requested) {
this.RemainingPermutations = remaining;
this.RequestedAmount = requested;
}
/**
* Creates a new instance of <code>TooManyPermutationsException</code>
* without detail message.
*/
public NotEnoughPermutationsException() {
}
@Override
public String getMessage() {
return String.format("%d ids were requested but only %d can be created using given format",
RequestedAmount, RemainingPermutations);
}
}
| package com.hida.model;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* An exception used to display how many permutations actually remain and the requested amount
* that caused an error.
* @author lruffin
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason =
"Requested amount exceeds possible number "
+ "of permutations")
public class NotEnoughPermutationsException extends RuntimeException {
private long RemainingPermutations;
private long RequestedAmount;
public NotEnoughPermutationsException(long remaining, long requested) {
this.RemainingPermutations = remaining;
this.RequestedAmount = requested;
}
/**
* Creates a new instance of <code>TooManyPermutationsException</code>
* without detail message.
*/
public NotEnoughPermutationsException() {
}
@Override
public String getMessage() {
//Logger.error(RequestedAmount+" ids were requested but only "+RemainingPermutations+" can be created using given format");
return String.format("%d ids were requested but only %d can be created using given format",
RequestedAmount, RemainingPermutations);
}
}
|
Move all input filtering to emit episodes for now | 'use strict';
var path = require('path');
var async = require('async');
var _ = require('lodash');
var parse = require('../lib/torrent-parser');
var glob = require('../plugins/input/glob');
var customCommand = require('../plugins/input/customCommand');
module.exports = function(program, config, done) {
async.waterfall([
function (next) {
if (config.input.globs) {
glob(config.input.globs, next);
} else if (config.input.customCommand) {
customCommand(program, config.input.customCommand).exec(next);
} else {
program.log.error('no input specified');
}
},
function (filePaths, next) {
// TODO extract to input filters
var allowedExt = ['.avi', '.mp4', '.mpg', '.mkv'];
var regex = /(Extras|Sample|E00)/;
program.log.debug('%s files found', filePaths.length);
var filtered = _.filter(filePaths, function (filePath) {
return -1 !== _.indexOf(allowedExt, path.extname(filePath)) && !regex.test(filePath);
});
program.log.debug('%s files remained after filter', filtered.length);
next(null, filtered)
},
function (filePaths, next) {
async.map(filePaths, parse.bind(null, program, config), next);
}
], done);
}
| 'use strict';
var path = require('path');
var async = require('async');
var _ = require('lodash');
var parse = require('../lib/torrent-parser');
var glob = require('../plugins/input/glob');
var customCommand = require('../plugins/input/customCommand');
module.exports = function(program, config, done) {
async.waterfall([
function (next) {
if (config.input.globs) {
glob(config.input.globs, next);
} else if (config.input.customCommand) {
customCommand(program, config.input.customCommand).exec(next);
} else {
program.log.error('no input specified');
}
},
function (filePaths, next) {
// TODO extract to input filters
var filtered = _.filter(filePaths, function (filePath) {
return -1 !== _.indexOf(['.avi', '.mp4', '.mpg', '.mkv'], path.extname(filePath));
});
next(null, filtered)
},
function (filePaths, next) {
async.map(filePaths, parse.bind(null, program, config), next);
}
], done);
}
|
Add min task to watch | module.exports = function (grunt) {
grunt.initConfig({
meta: {
banner: '// ' + grunt.file.read('src/loStorage.js').split("\n")[0]
},
min: {
dist: {
src: ['<banner>', 'src/loStorage.js'],
dest: 'src/loStorage.min.js'
}
},
jasmine: {
all: ['spec/index.html']
},
watch: {
test: {
files: ['src/loStorage.js', 'spec/*'],
tasks: 'test'
},
min: {
files: ['src/loStorage.js'],
tasks: 'min'
}
}
});
grunt.loadNpmTasks('grunt-jasmine-task');
grunt.registerTask('test', 'jasmine');
grunt.registerTask('release', 'test min');
grunt.registerTask('default', 'release');
}; | module.exports = function (grunt) {
grunt.initConfig({
meta: {
banner: '// ' + grunt.file.read('src/loStorage.js').split("\n")[0]
},
min: {
dist: {
src: ['<banner>', 'src/loStorage.js'],
dest: 'src/loStorage.min.js'
}
},
jasmine: {
all: ['spec/index.html']
},
watch: {
test: {
files: ['src/loStorage.js', 'spec/*'],
tasks: 'test'
}
}
});
grunt.loadNpmTasks('grunt-jasmine-task');
grunt.registerTask('test', 'jasmine');
grunt.registerTask('release', 'test min');
grunt.registerTask('default', 'release');
}; |
Fix test suite gettext handler. | <?php
// This is global bootstrap for autoloading
$autoloader = require __DIR__.'/../vendor/autoload.php';
$autoloader->addClassMap([
'Functional\CestAbstract' => __DIR__ . '/Functional/CestAbstract.php',
]);
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$autoloader, 'loadClass']);
$GLOBALS['autoloader'] = $autoloader;
if (!function_exists('__')) {
\Gettext\TranslatorFunctions::register(new \Gettext\Translator());
}
// Clear output directory
function rrmdir($dir)
{
if (is_dir($dir)) {
$objects = array_diff(scandir($dir, SCANDIR_SORT_NONE) ?: [], ['.', '..', '.gitignore']);
foreach ($objects as $object) {
if (is_dir($dir . '/' . $object)) {
rrmdir($dir . '/' . $object);
} else {
unlink($dir . '/' . $object);
}
}
reset($objects);
@rmdir($dir);
}
}
rrmdir(__DIR__ . '/_output');
| <?php
// This is global bootstrap for autoloading
$autoloader = require __DIR__.'/../vendor/autoload.php';
$autoloader->addClassMap([
'Functional\CestAbstract' => __DIR__ . '/Functional/CestAbstract.php',
]);
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$autoloader, 'loadClass']);
$GLOBALS['autoloader'] = $autoloader;
if (!function_exists('__')) {
$translator = new \Gettext\Translator();
$translator->register();
}
// Clear output directory
function rrmdir($dir)
{
if (is_dir($dir)) {
$objects = array_diff(scandir($dir, SCANDIR_SORT_NONE) ?: [], ['.', '..', '.gitignore']);
foreach ($objects as $object) {
if (is_dir($dir . '/' . $object)) {
rrmdir($dir . '/' . $object);
} else {
unlink($dir . '/' . $object);
}
}
reset($objects);
@rmdir($dir);
}
}
rrmdir(__DIR__ . '/_output');
|
Add route handler for PUT /api/nodes/:nodeID | var Node = require('./nodeModel.js'),
handleError = require('../../util.js').handleError,
handleQuery = require('../queryHandler.js');
module.exports = {
createNode : function (req, res, next) {
var newNode = req.body;
// Support /nodes and /roadmaps/roadmapID/nodes
newNode.parentRoadmap = newNode.parentRoadmap || req.params.roadmapID;
Node(newNode).save()
.then(function(dbResults){
res.status(201).json(dbResults);
})
.catch(handleError(next));
},
getNodeByID : function (req, res, next) {
var _id = req.params.nodeID;
Node.findById(_id)
.then(function(dbResults){
res.json(dbResults);
})
.catch(handleError(next));
},
updateNode : function (req, res, next) {
var _id = req.params.nodeID;
var updateCommand = req.body;
Node.findByIdAndUpdate(_id, updateCommand)
.then(function(dbResults){
res.json(dbResults);
})
.catch(handleError(next));
},
deleteNode : function (req, res, next) {
}
}; | var Node = require('./nodeModel.js'),
handleError = require('../../util.js').handleError,
handleQuery = require('../queryHandler.js');
module.exports = {
createNode : function (req, res, next) {
var newNode = req.body;
// Support /nodes and /roadmaps/roadmapID/nodes
newNode.parentRoadmap = newNode.parentRoadmap || req.params.roadmapID;
Node(newNode).save()
.then(function(dbResults){
res.status(201).json(dbResults);
})
.catch(handleError(next));
},
getNodeByID : function (req, res, next) {
var _id = req.params.nodeID;
Node.findById(_id)
.then(function(dbResults){
res.json(dbResults);
})
.catch(handleError(next));
},
updateNode : function (req, res, next) {
},
deleteNode : function (req, res, next) {
}
}; |
Make file spinner same size as all others on site | var $ = require('jquery');
var m = require('mithril');
function Panel(title, header, inner, args, selected) {
panel = m.component(Panel, title, header, inner, args);
panel.title = title;
panel.selected = selected || false;
return panel;
}
Panel.controller = function(title, header, inner, args) {
var self = this;
self.title = title;
self.header = header === null ? null : header || title;
self.inner = m.component.apply(self, [inner].concat(args || []));
};
Panel.view = function(ctrl) {
return m('#' + ctrl.title.toLowerCase() + 'Panel.panel.panel-default', [
!ctrl.header ? '' :
m('.panel-heading', $.isFunction(ctrl.header) ? ctrl.header() : ctrl.header),
m('', ctrl.inner)
]);
};
var Spinner = m.component({
controller: function(){},
view: function() {
return m('.spinner-loading-wrapper', [
m('.logo-spin.logo-lg'),
m('p.m-t-sm.fg-load-message', ' Loading... ')
]);
}
});
module.exports = {
Panel: Panel,
Spinner: Spinner,
};
| var $ = require('jquery');
var m = require('mithril');
function Panel(title, header, inner, args, selected) {
panel = m.component(Panel, title, header, inner, args);
panel.title = title;
panel.selected = selected || false;
return panel;
}
Panel.controller = function(title, header, inner, args) {
var self = this;
self.title = title;
self.header = header === null ? null : header || title;
self.inner = m.component.apply(self, [inner].concat(args || []));
};
Panel.view = function(ctrl) {
return m('#' + ctrl.title.toLowerCase() + 'Panel.panel.panel-default', [
!ctrl.header ? '' :
m('.panel-heading', $.isFunction(ctrl.header) ? ctrl.header() : ctrl.header),
m('', ctrl.inner)
]);
};
var Spinner = m.component({
controller: function(){},
view: function() {
return m('.spinner-loading-wrapper', [
m('.logo-spin.logo-xl'),
m('p.m-t-sm.fg-load-message', ' Loading... ')
]);
}
});
module.exports = {
Panel: Panel,
Spinner: Spinner,
};
|
Revert "Handle exception straight away"
This reverts commit 0cac4b793b3eb7c122f1f6550f2e62ba29e02795. | package uk.co.prenderj.trail.util;
import android.os.AsyncTask;
public abstract class CheckedAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
private Exception thrown;
public abstract Result call(Params... params) throws Exception;
public abstract void finish(Result result) throws Exception;
@Override
protected Result doInBackground(Params... params) {
try {
return call(params);
} catch (Exception e) {
thrown = e;
return null;
}
}
@Override
protected void onPostExecute(Result result) {
if (thrown != null) {
onException(thrown);
}
try {
finish(result);
} catch (Exception e) {
onException(e);
}
}
public void onException(Exception thrown) {
cancel(true);
}
}
| package uk.co.prenderj.trail.util;
import android.os.AsyncTask;
public abstract class CheckedAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
public abstract Result call(Params... params) throws Exception;
public abstract void finish(Result result) throws Exception;
@Override
protected Result doInBackground(Params... params) {
try {
return call(params);
} catch (Exception e) {
onException(e);
return null;
}
}
@Override
protected void onPostExecute(Result result) {
try {
finish(result);
} catch (Exception e) {
onException(e);
}
}
public void onException(Exception thrown) {
cancel(true);
}
}
|
Make reddit url a constant | import json
import pprint
import requests
SAMPLE_REDDIT_URL = 'http://www.reddit.com/r/cscareerquestions/top.json'
def sample_valid_reddit_response():
r = requests.get(SAMPLE_REDDIT_URL)
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response()
return response_json
def save_sample():
response_json = sample_valid_reddit_response()
del response_json['data']['children']
with open('sample_response.json', 'w+') as f:
json.dump(response_json, f, indent=5)
def get_next_reddit_response():
response = {}
with open('sample_response.json', 'r') as f:
response = json.load(f)
after = response['data']['after']
print(after)
if '__main__' == __name__:
get_next_reddit_response()
| import json
import pprint
import requests
def sample_valid_reddit_response():
r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response()
return response_json
def save_sample():
response_json = sample_valid_reddit_response()
del response_json['data']['children']
with open('sample_response.json', 'w+') as f:
json.dump(response_json, f, indent=5)
def get_next_reddit_response():
response = {}
with open('sample_response.json', 'r') as f:
response = json.load(f)
after = response['data']['after']
print(after)
if '__main__' == __name__:
get_next_reddit_response()
|
Fix firefox launching from Karma | module.exports = config => {
config.set({
frameworks: ['jasmine'],
files: ['*.js'],
preprocessors: {
'*.js': ['webpack'],
},
browsers: [process.env.BROWSER || 'chrome'],
plugins: [
'karma-chrome-launcher',
'karma-webpack',
'karma-jasmine',
],
webpack: {
devtool: 'inline-source-map',
},
customLaunchers: {
chrome: {
base: 'Chrome',
flags: ['--use-fake-device-for-media-stream',
'--use-fake-ui-for-media-stream', '--disable-popup-blocking'],
},
firefox: {
base: 'Firefox',
prefs: {
'media.navigator.permission.disabled': true,
'media.navigator.streams.fake': true,
},
},
},
webpackMiddleware: {
noInfo: true,
},
});
};
| module.exports = config => {
config.set({
frameworks: ['jasmine'],
files: ['*.js'],
preprocessors: {
'*.js': ['webpack'],
},
browsers: ['Chrome_fakeDevices'],
plugins: [
'karma-chrome-launcher',
'karma-webpack',
'karma-jasmine',
],
webpack: {
devtool: 'inline-source-map',
},
customLaunchers: {
Chrome_fakeDevices: {
base: 'Chrome',
flags: ['--use-fake-device-for-media-stream',
'--use-fake-ui-for-media-stream', '--disable-popup-blocking'],
},
},
webpackMiddleware: {
noInfo: true,
},
});
};
|
BUGFIX: Reformat code, fix cache bug | <?php
/**
* Defines the StaffFolder page type
*/
class StaffFolder extends Page implements RenderableAsPortlet {
static $db = array(
);
static $has_one = array(
'MainImage' => 'Image'
);
static $allowed_children = array( 'Staff' );
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab( 'Root.Content.Image', new ImageField( 'MainImage' ) );
return $fields;
}
public function getPortletTitle() {
return $this->Title;
}
// FIXME - make this more efficient
public function getPortletImage() {
if ( $this->MainImageID ) {
return DataObject::get_by_id( 'Image', $this->MainImageID );
} else {
return null;
}
}
public function getPortletCaption() {
return '';
}
}
class StaffFolder_Controller extends Page_Controller {
public function StaffFolderCacheKey() {
$start = isset( $_GET['start'] ) ? (int)( Convert::raw2sql( $_GET['start'] ) ) : 0;
return implode( '_', array(
'StaffFolders',
$this->Locale,
$this->Aggregate( 'Staff' )->Max( 'LastEdited' ),
'_',
$this->ID,
'_',
$this->Aggregate( 'StaffFolder' )->Max( 'LastEdited' ),
'_',
$start
) );
}
}
?>
| <?php
/**
* Defines the StaffFolder page type
*/
class StaffFolder extends Page {
static $db = array(
);
static $has_one = array(
);
static $allowed_children = array('Staff');
}
class StaffFolder_Controller extends Page_Controller {
public function StaffFolderCacheKey() {
$start = isset( $_GET['start'] ) ? (int)( Convert::raw2sql( $_GET['start'] ) ) : 0;
return implode( '_', array(
'StaffFolders',
$this->Locale,
$this->Aggregate( 'Staff' )->Max( 'LastEdited' ),
$this->Aggregate( 'StaffFolder' )->Max( 'LastEdited' ),
'_',
$start
) );
}
}
?>
|
Use utils._iter_but_not_str_or_map in Writer log creation. | from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
__slots__ = ('v', 'log')
def __init__(self, v, log):
self.v = v
if _iter_but_not_str_or_map(log):
print("convert iter to list log...")
self.log = [l for l in log]
else:
print("convert str/map/other to list log...")
self.log = [log]
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log)
| from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
def __init__(self, v, log):
self.v = v
if not isinstance(log, list):
self.log = [log]
else:
self.log = log
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log)
|
Use global instead of window | /**
* Create a blob builder even when vendor prefixes exist
*/
var BlobBuilder = global.BlobBuilder
|| global.WebKitBlobBuilder
|| global.MSBlobBuilder
|| global.MozBlobBuilder;
/**
* Check if Blob constructor is supported
*/
var blobSupported = (function() {
try {
var b = new Blob(['hi']);
return b.size == 2;
} catch(e) {
return false;
}
})();
/**
* Check if BlobBuilder is supported
*/
var blobBuilderSupported = BlobBuilder
&& BlobBuilder.prototype.append
&& BlobBuilder.prototype.getBlob;
function BlobBuilderConstructor(ary, options) {
options = options || {};
var bb = new BlobBuilder();
for (var i = 0; i < ary.length; i++) {
bb.append(ary[i]);
}
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};
module.exports = (function() {
if (blobSupported) {
return global.Blob;
} else if (blobBuilderSupported) {
return BlobBuilderConstructor;
} else {
return undefined;
}
})();
| /**
* Create a blob builder even when vendor prefixes exist
*/
var BlobBuilder = window.BlobBuilder
|| window.WebKitBlobBuilder
|| window.MSBlobBuilder
|| window.MozBlobBuilder;
/**
* Check if Blob constructor is supported
*/
var blobSupported = (function() {
try {
var b = new Blob(['hi']);
return b.size == 2;
} catch(e) {
return false;
}
})();
/**
* Check if BlobBuilder is supported
*/
var blobBuilderSupported = BlobBuilder
&& BlobBuilder.prototype.append
&& BlobBuilder.prototype.getBlob;
function BlobBuilderConstructor(ary, options) {
options = options || {};
var bb = new BlobBuilder();
for (var i = 0; i < ary.length; i++) {
bb.append(ary[i]);
}
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};
module.exports = (function() {
if (blobSupported) {
return window.Blob;
} else if (blobBuilderSupported) {
return BlobBuilderConstructor;
} else {
return undefined;
}
})();
|
Split out bytesToHexString as a static method. | package com.msgilligan.bitcoinj.json.conversion;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.bitcoinj.core.Transaction;
import java.io.IOException;
import java.util.Formatter;
/**
*
*/
public class TransactionHexSerializer extends JsonSerializer<Transaction> {
@Override
public void serialize(Transaction value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeString(bytesToHexString(value.bitcoinSerialize()));
}
// From: http://bitcoin.stackexchange.com/questions/8475/how-to-get-hex-string-from-transaction-in-bitcoinj
public static String bytesToHexString(byte[] bytes) {
final StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
for (byte b : bytes) {
formatter.format("%02x", b);
}
formatter.close();
return sb.toString();
}
}
| package com.msgilligan.bitcoinj.json.conversion;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.bitcoinj.core.Transaction;
import java.io.IOException;
import java.util.Formatter;
/**
*
*/
public class TransactionHexSerializer extends JsonSerializer<Transaction> {
@Override
public void serialize(Transaction value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
// From: http://bitcoin.stackexchange.com/questions/8475/how-to-get-hex-string-from-transaction-in-bitcoinj
final StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
byte[] bytes = value.bitcoinSerialize();
for (byte b : bytes) {
formatter.format("%02x", b);
}
formatter.close();
gen.writeString(sb.toString());
}
}
|
Use the UFOs not the OTFs
Oops, the OTF are not interpolation compatible due to overlap removal, I
should have use the UFOs all along. Now the script passes without
errors, still need to verify the output. | from psautohint import autohint
from psautohint import psautohint
baseDir = "tests/data/source-code-pro"
masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
glyphList = None
fonts = []
for master in masters:
print("Hinting %s" % master)
options = autohint.ACOptions()
options.quiet = True
path = "%s/%s/font.ufo" % (baseDir, master)
font = autohint.openUFOFile(path, "font.ufo", False, options)
font.useProcessedLayer = False
names = font.getGlyphList()
info = font.getFontInfo(font.getPSName(), path, False, False, [], [])
info = info.getFontInfo()
if glyphList is None:
glyphList = names
else:
assert glyphList == names
glyphs = []
for name in glyphList:
glyph = font.convertToBez(name, False, True)[0]
if not glyph:
glyph = "%%%s\n" % name
glyphs.append(glyph)
fonts.append(psautohint.autohint(info, glyphs, False, False, False))
glyphs = []
for i in range(len(glyphList)):
glyphs.append([f[i] for f in fonts])
print("MM Hinting")
glyphs = psautohint.autohintmm(info, glyphs, masters, True)
| from psautohint import autohint
from psautohint import psautohint
baseDir = "tests/data/source-code-pro"
masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
glyphList = None
fonts = []
for master in masters:
print("Hinting %s" % master)
path = "%s/%s/font.otf" % (baseDir, master)
font = autohint.openOpenTypeFile(path, "font.otf", None)
names = font.getGlyphList()
info = font.getFontInfo(font.getPSName(), path, False, False, [], [])
info = info.getFontInfo()
if glyphList is None:
glyphList = names
else:
assert glyphList == names
glyphs = []
for name in names:
glyph = font.convertToBez(name, False)
glyphs.append(glyph[0])
fonts.append(psautohint.autohint(info, glyphs, False, False, False))
glyphs = []
for i in range(len(glyphList)):
glyphs.append([f[i] for f in fonts])
print("MM Hinting")
glyphs = psautohint.autohintmm(info, glyphs, masters, True)
|
Use a faster source map implementation | const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./client/src/index.js'],
devtool: 'eval-source-map',
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js',
},
resolve: {
root: path.resolve('./client/src'),
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader'],
},
{
test: /\.css$/,
loader: 'style-loader!css-loader?sourceMap',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html',
}),
]
};
| const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./client/src/index.js'],
devtool: 'source-map',
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js',
},
resolve: {
root: path.resolve('./client/src'),
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader'],
},
{
test: /\.css$/,
loader: 'style-loader!css-loader?sourceMap',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html',
}),
]
};
|
Add test case to 014 | """
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if strs is None or strs == "":
return ""
lcp = list(strs[0])
for i, string in enumerate(strs):
if list(string[0:len(lcp)]) == lcp:
continue
else:
while len(lcp) > 0 and list(string[0:len(lcp)]) != lcp:
lcp.pop()
if lcp == 0:
return ""
return "".join(lcp)
a = Solution()
print(a.longestCommonPrefix(["apps","apple","append"]) == "app")
| """
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return ""
lcp=list(strs[0])
for i,string in enumerate(strs):
if list(string[0:len(lcp)])==lcp:
continue
else:
while len(lcp)>0 and list(string[0:len(lcp)])!=lcp:
lcp.pop()
if lcp==0:
return ""
return "".join(lcp)
|
Change from array to dictionary for general insight calculators |
from functools import reduce
from ..models import User, Text, Insight, Comment, GeneralInsight
class general_insight_calculator:
name = None
calc = lambda *_: None
def __init__(self, name, calc):
self.name = name
self.calc = calc
def do_calc(self):
return self.calc()
def calc_and_save(self):
entry, created = GeneralInsight.objects.get_or_create(pk=self.name, defaults={'value':''})
entry.value = self.do_calc()
entry.save()
# Dictionary of general insight name to general insight calculator
general_insights = { }
def add_general_insight(name, func):
global general_insights
general_insights[name] = general_insight_calculator(name, func)
def calc_and_save_general_insights():
for insight in general_insights:
insight.calc_and_save()
########################################################################
# Insight calculation implementations
########################################################################
def _calc_total_words():
ret = 0
for text in Text.objects.all():
ret += len(text.content.split())
return ret
add_general_insight('Total Words', _calc_total_words)
|
from functools import reduce
from ..models import User, Text, Insight, Comment, GeneralInsight
class general_insight_calculator:
name = None
calc = lambda *_: None
def __init__(self, name, calc):
self.name = name
self.calc = calc
def do_calc(self):
return self.calc()
def calc_and_save(self):
entry, created = GeneralInsight.objects.get_or_create(pk=self.name, defaults={'value':''})
entry.value = self.do_calc()
entry.save()
general_insights = [ ]
def add_general_insight(name, func):
global general_insights
general_insights.append(general_insight_calculator(name, func))
def calc_and_save_general_insights():
for insight in general_insights:
insight.calc_and_save()
########################################################################
# Insight calculation implementations
########################################################################
def _calc_total_words():
ret = 0
for text in Text.objects.all():
ret += len(text.content.split())
return ret
add_general_insight('Total Words', _calc_total_words)
|
Reduce flakiness in auto-run test | import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';
import sinon from 'sinon';
const { run } = Ember;
const SELECTORS = {
passingComponent: '[data-test-selector="violations-page__passing-component"]'
};
let application;
let sandbox;
module('Acceptance | auto-run', {
beforeEach: function() {
application = startApp();
sandbox = sinon.sandbox.create();
},
afterEach: function() {
sandbox.restore();
Ember.run(application, 'destroy');
}
});
test('should run the function when visiting a new route', function(assert) {
const callbackStub = sandbox.stub(run.backburner.options.render, 'after');
visit('/');
andThen(() => {
assert.ok(callbackStub.calledOnce);
assert.equal(currentPath(), 'violations');
});
});
test('should run the function whenever a render occurs', function(assert) {
const callbackStub = sandbox.stub(run.backburner.options.render, 'after');
let callCount = 0;
visit('/');
andThen(() => {
callCount = callbackStub.callCount;
assert.ok(callCount > 0, 'afterRender called at least once for initial visit');
assert.equal(currentPath(), 'violations');
});
click(SELECTORS.passingComponent);
andThen(() => {
assert.ok(callbackStub.callCount > callCount, 'afterRender called more than before');
});
});
| import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';
import sinon from 'sinon';
const { run } = Ember;
const SELECTORS = {
passingComponent: '[data-test-selector="violations-page__passing-component"]'
};
let application;
let sandbox;
module('Acceptance | auto-run', {
beforeEach: function() {
application = startApp();
sandbox = sinon.sandbox.create();
},
afterEach: function() {
sandbox.restore();
Ember.run(application, 'destroy');
}
});
test('should run the function when visiting a new route', function(assert) {
const callbackStub = sandbox.stub(run.backburner.options.render, 'after');
visit('/');
andThen(() => {
assert.ok(callbackStub.calledOnce);
assert.equal(currentPath(), 'violations');
});
});
test('should run the function whenever a render occurs', function(assert) {
const callbackStub = sandbox.stub(run.backburner.options.render, 'after');
visit('/').then(() => {
assert.ok(callbackStub.calledOnce);
assert.equal(currentPath(), 'violations');
click(`${SELECTORS.passingComponent}`);
andThen(() => {
assert.ok(callbackStub.calledTwice);
});
});
});
|
Increment version number to 1.0.0 | from setuptools import setup, find_packages
setup(
name = 'django-news-sitemaps',
version = '1.0.0',
description = 'Generates sitemaps compatible with the Google News schema',
author = 'TWT Web Devs',
author_email = 'webdev@washingtontimes.com',
url = 'http://github.com/washingtontimes/django-news-sitemaps/',
include_package_data = True,
packages = find_packages(),
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Operating System :: OS Independent',
]
)
| from setuptools import setup, find_packages
setup(
name = 'django-news-sitemaps',
version = '0.1.7',
description = 'Generates sitemaps compatible with the Google News schema',
author = 'TWT Web Devs',
author_email = 'webdev@washingtontimes.com',
url = 'http://github.com/washingtontimes/django-news-sitemaps/',
include_package_data = True,
packages = find_packages(),
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Operating System :: OS Independent',
]
)
|
Use MONGOHQ_URL for database connection in prod | 'use strict';
module.exports = {
app: {
name: 'MEAN - A Modern Stack - Production'
},
facebook: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: 'CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: 'API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
}
};
| 'use strict';
module.exports = {
db: 'mongodb://localhost/mean',
app: {
name: 'MEAN - A Modern Stack - Production'
},
facebook: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: 'CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: 'API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
}
};
|
Rename core config "id" to "mirId" | /*
* Copyright (c) 2017. Vitus Lehner. UrbanLife+. Universität der Bundeswehr München.
*/
package org.sociotech.urbanlifeplus.microinforadiator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author vituslehner 03.07.17
*/
@Configuration
public class CoreConfiguration {
@Bean("reactorEventBus")
public EventBus reactorEventBus() {
return new EventBus("reactorEventBus");
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Value("${ULP_MIR_ID}")
private String mirId;
public String getMirId() {
return mirId;
}
@Value("${ULP_RECURSION_DEPTH:3}")
private int recursionDepth;
public int getRecursionDepth() {
return recursionDepth;
}
}
| /*
* Copyright (c) 2017. Vitus Lehner. UrbanLife+. Universität der Bundeswehr München.
*/
package org.sociotech.urbanlifeplus.microinforadiator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author vituslehner 03.07.17
*/
@Configuration
public class CoreConfiguration {
@Bean("reactorEventBus")
public EventBus reactorEventBus() {
return new EventBus("reactorEventBus");
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Value("${ULP_MIR_ID}")
private String id;
public String getId() {
return id;
}
@Value("${ULP_RECURSION_DEPTH:3}")
private int recursionDepth;
public int getRecursionDepth() {
return recursionDepth;
}
}
|
Update navigation to use Orchestra\Decorator::navbar()
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | @section('melody::primary_menu')
<ul class="nav">
<li class="{{ URI::is('*/manages/melody.themes/frontend*') ? 'active' : '' }}">
{{ HTML::link(handles('orchestra::manages/melody.themes/frontend'), 'Frontend') }}
</li>
<li class="{{ URI::is('*/manages/melody.themes/backend*') ? 'active' : '' }}">
{{ HTML::link(handles('orchestra::manages/melody.themes/backend'), 'Backend') }}
</li>
</ul>
@endsection
<?php
$navbar = new Orchestra\Fluent(array(
'id' => 'melody',
'title' => 'Theme Manager',
'url' => handles('orchestra::manages/melody.themes'),
'primary_menu' => Laravel\Section::yield('melody::primary_menu'),
)); ?>
{{ Orchestra\Decorator::navbar($navbar) }} | <div class="navbar">
<div class="navbar-inner">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target="#cellonav">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
{{ HTML::link(handles('orchestra::manages/melody.themes'), 'Themes Manager', array('class' => 'brand')) }}
<div id="cellonav" class="collapse nav-collapse">
<ul class="nav">
<li class="{{ URI::is('*/manages/melody.themes/frontend*') ? 'active' : '' }}">
{{ HTML::link(handles('orchestra::manages/melody.themes/frontend'), 'Frontend') }}
</li>
<li class="{{ URI::is('*/manages/melody.themes/backend*') ? 'active' : '' }}">
{{ HTML::link(handles('orchestra::manages/melody.themes/backend'), 'Backend') }}
</li>
</ul>
</div>
</div>
</div> |
Change to connect to Stratisd on the system bus
Stratisd is changing to use the system bus, so naturally we need to
also change in order to continue working.
Signed-off-by: Andy Grover <b7d524d2f5cc5aebadb6b92b08d3ab26911cde33@redhat.com> | # Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Miscellaneous helpful methods.
"""
import dbus
from ._constants import SERVICE
class Bus(object):
"""
Our bus.
"""
# pylint: disable=too-few-public-methods
_BUS = None
@staticmethod
def get_bus(): # pragma: no cover
"""
Get our bus.
"""
if Bus._BUS is None:
Bus._BUS = dbus.SystemBus()
return Bus._BUS
def get_object(object_path): # pragma: no cover
"""
Get an object from an object path.
:param str object_path: an object path with a valid format
:returns: the proxy object corresponding to the object path
:rtype: ProxyObject
"""
return Bus.get_bus().get_object(SERVICE, object_path, introspect=False)
| # Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Miscellaneous helpful methods.
"""
import dbus
from ._constants import SERVICE
class Bus(object):
"""
Our bus.
"""
# pylint: disable=too-few-public-methods
_BUS = None
@staticmethod
def get_bus(): # pragma: no cover
"""
Get our bus.
"""
if Bus._BUS is None:
Bus._BUS = dbus.SessionBus()
return Bus._BUS
def get_object(object_path): # pragma: no cover
"""
Get an object from an object path.
:param str object_path: an object path with a valid format
:returns: the proxy object corresponding to the object path
:rtype: ProxyObject
"""
return Bus.get_bus().get_object(SERVICE, object_path, introspect=False)
|
Update code to match current generation format | import javax.annotation.Generated;
import javax.annotation.Nonnull;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.Observable;
@Generated( "org.realityforge.arez.processor.ArezProcessor" )
public final class Arez_BasicObservableModel
extends BasicObservableModel
{
private static volatile long $$arez$$_nextId;
private final long $$arez$$_id;
@Nonnull
private final ArezContext $$arez$$_context;
@Nonnull
private final Observable $$arez$$_time;
public Arez_BasicObservableModel( @Nonnull final ArezContext $$arez$$_context )
{
super();
this.$$arez$$_id = $$arez$$_nextId++;
this.$$arez$$_context = $$arez$$_context;
this.$$arez$$_time =
$$arez$$_context.createObservable( this.$$arez$$_context.areNamesEnabled() ? $$arez$$_id() + "time" : null );
}
private String $$arez$$_id()
{
return "BasicObservableModel." + $$arez$$_id + ".";
}
@Override
public long getTime()
{
this.$$arez$$_time.reportObserved();
return super.getTime();
}
@Override
public void setTime( final long time )
{
if ( time != super.getTime() )
{
super.setTime( time );
this.$$arez$$_time.reportObserved();
}
}
}
| import javax.annotation.Generated;
import javax.annotation.Nonnull;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.Observable;
@Generated( "org.realityforge.arez.processor.ArezProcessor" )
public final class Arez_BasicObservableModel
extends BasicObservableModel
{
@Nonnull
private final ArezContext $$arez$$_context;
@Nonnull
private final Observable $$arez$$_time;
public Arez_BasicObservableModel( @Nonnull final ArezContext $$arez$$_context )
{
super();
this.$$arez$$_context = $$arez$$_context;
this.$$arez$$_time =
$$arez$$_context.createObservable( this.$$arez$$_context.areNamesEnabled() ? "BasicObservableModel.time" : null );
}
@Override
public long getTime()
{
this.$$arez$$_time.reportObserved();
return super.getTime();
}
@Override
public void setTime( final long time )
{
if ( time != super.getTime() )
{
super.setTime( time );
this.$$arez$$_time.reportObserved();
}
}
}
|
Correct routing if URI is not
when index.php is not routed on / of the website you could get errors like:
hipay.WARNING: No route found for "GET /some/place/on/the/server/index.php" [] [] | <?php
/**
* Main entry point
*
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>, updated by Flavius Bindea - BFB Consulting
* @copyright 2015 Smile, BFB Consulting
*/
require_once __DIR__ . '/../app/bootstrap.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app->post('/{anyplace}', function (Request $request) use ($app, $notificationHandler) {
$notificationHandler->handleHipayNotification(rawurldecode($request->request->get('xml')));
return new Response(null, 204);
})->assert("anyplace", ".*");
$app->error(function (Exception $e) use ($app, $notificationHandler) {
$notificationHandler->handleException($e);
return new Response($e->getMessage());
});
$app->get('/{anyplace}', function () {
return 'Hello World';
})->assert("anyplace", ".*");
$app->run();
| <?php
/**
* Main entry point
*
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
require_once __DIR__ . '/../app/bootstrap.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app->post('/', function (Request $request) use ($app, $notificationHandler) {
$notificationHandler->handleHipayNotification(rawurldecode($request->request->get('xml')));
return new Response(null, 204);
});
$app->error(function (Exception $e) use ($app, $notificationHandler) {
$notificationHandler->handleException($e);
return new Response($e->getMessage());
});
$app->get('/', function () {
return 'Hello World';
});
$app->run();
|
Tweak express-dynamic-fields example to use global builder dynamic fields + newEvent | var libhoney = require('libhoney').default;
var process = require('process');
module.exports = function(options) {
var honey = new libhoney(options);
return function(req, res, next) {
// Attach dynamic fields to the global event builder in libhoney.
// Dynamic fields calculate their values at the time the event is created
// (the event.sendNow call below)
honey.addDynamicField('rss_after', () => process.memoryUsage().rss);
honey.addDynamicField('heapTotal_after', () => process.memoryUsage().heapTotal);
honey.addDynamicField('heapUsed_after', () => process.memoryUsage().heapUsed);
var event = honey.newEvent();
event.add({
app: req.app,
baseUrl: req.baseUrl,
fresh: req.fresh,
hostname: req.hostname,
ip: req.ip,
method: req.method,
originalUrl: req.originalUrl,
params: req.params,
path: req.path,
protocol: req.protocol,
query: req.query,
route: req.route,
secure: req.secure,
xhr: req.xhr,
// these fields capture values for memory usage at the time they're added
// to the newEvent
rss_before: process.memoryUsage().rss,
heapTotal_before: process.memoryUsage().heapTotal,
heapUsed_before: process.memoryUsage().heapUsed
});
next();
builder.sendNow();
};
};
| var libhoney = require('libhoney').default;
var process = require('process');
module.exports = function(options) {
var honey = new libhoney(options);
return function(req, res, next) {
var builder = honey.newBuilder({
app: req.app,
baseUrl: req.baseUrl,
fresh: req.fresh,
hostname: req.hostname,
ip: req.ip,
method: req.method,
originalUrl: req.originalUrl,
params: req.params,
path: req.path,
protocol: req.protocol,
query: req.query,
route: req.route,
secure: req.secure,
xhr: req.xhr,
// fields here give the values at the time newBuilder is called
rss_before: process.memoryUsage().rss,
heapTotal_before: process.memoryUsage().heapTotal,
heapUsed_before: process.memoryUsage().heapUsed
}, {
// dynamic fields generate values at the time the event is created
// (the buidler.sendNow call below.)
rss_after: () => process.memoryUsage().rss,
heapTotal_after: () => process.memoryUsage().heapTotal,
heapUsed_after: () => process.memoryUsage().heapUsed
});
next();
builder.sendNow();
};
};
|
Switch the main file to use getters to defer loading the JS version unless requested | /*
* Copyright 2015 The Closure Compiler 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.
*/
/**
* @fileoverview Nodejs plugins and build tools for Google Closure Compiler
*
* @author Chad Killingsworth (chadkillingsworth@gmail.com)
*/
'use strict';
// defer loading modules. The jscomp file is rather large. Don't load it unless it's actually referenced.
class Main {
static get grunt() {
return require('./lib/grunt');
}
static get gulp() {
return require('./lib/gulp');
}
static get compiler() {
return require('./lib/node/closure-compiler');
}
static get jsCompiler() {
return require('./lib/node/closure-compiler-js');
}
}
module.exports = Main;
| /*
* Copyright 2015 The Closure Compiler 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.
*/
/**
* @fileoverview Nodejs plugins and build tools for Google Closure Compiler
*
* @author Chad Killingsworth (chadkillingsworth@gmail.com)
*/
'use strict';
const grunt_plugin = require('./lib/grunt');
const gulp_plugin = require('./lib/gulp');
const Compiler = require('./lib/node/closure-compiler');
const CompilerJS = require('./lib/node/closure-compiler-js');
module.exports = {
grunt: grunt_plugin,
compiler: Compiler,
jsCompiler: CompilerJS,
gulp: gulp_plugin
};
|
Add missing debugbar alias and serviceProvider | <?php
namespace App\Containers\Debugger\Providers;
use App\Containers\Debugger\Tasks\QueryDebuggerTask;
use App\Ship\Parents\Providers\MainProvider;
use Barryvdh\Debugbar\Facade as Debugbar;
use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider;
use Jenssegers\Agent\AgentServiceProvider;
use Jenssegers\Agent\Facades\Agent;
/**
* Class MainServiceProvider.
*
* The Main Service Provider of this container, it will be automatically registered in the framework.
*
* @author Mahmoud Zalt <mahmoud@zalt.me>
*/
class MainServiceProvider extends MainProvider
{
/**
* Container Service Providers.
*/
public array $serviceProviders = [
AgentServiceProvider::class,
MiddlewareServiceProvider::class,
DebugbarServiceProvider::class
];
/**
* Container Aliases
*/
public array $aliases = [
'Agent' => Agent::class,
'Debugbar' => Debugbar::class,
];
/**
* Register anything in the container.
*/
public function register(): void
{
parent::register();
(new QueryDebuggerTask)->run();
}
}
| <?php
namespace App\Containers\Debugger\Providers;
use App\Containers\Debugger\Tasks\QueryDebuggerTask;
use App\Ship\Parents\Providers\MainProvider;
use Jenssegers\Agent\AgentServiceProvider;
use Jenssegers\Agent\Facades\Agent;
/**
* Class MainServiceProvider.
*
* The Main Service Provider of this container, it will be automatically registered in the framework.
*
* @author Mahmoud Zalt <mahmoud@zalt.me>
*/
class MainServiceProvider extends MainProvider
{
/**
* Container Service Providers.
*/
public array $serviceProviders = [
AgentServiceProvider::class,
MiddlewareServiceProvider::class,
];
/**
* Container Aliases
*/
public array $aliases = [
'Agent' => Agent::class,
];
/**
* Register anything in the container.
*/
public function register(): void
{
parent::register();
(new QueryDebuggerTask)->run();
}
}
|
Use `import` for ES6 modules | import AnnotationApi from './annotation';
let ScssCommentParser = require('scss-comment-parser');
export default class Parser {
constructor (config) {
this.annotations = new AnnotationApi();
this.scssParser = new ScssCommentParser(this.annotations.list, config);
this.scssParser.commentParser.on('warning', (warning) => {
config.logger.warn(warning);
});
}
parse(...args) {
return this.scssParser.parse(args);
}
/**
* Invoke the `resolve` function of an annotation if present.
* Called with all found annotations except with type "unkown".
*/
postProcess(data) {
Object.keys(this.annotations.list).forEach(key => {
let annotation = this.annotations.list[key];
if (annotation.resolve) {
annotation.resolve(data);
}
});
return data;
}
}
| let AnnotationApi = require('./annotation');
let ScssCommentParser = require('scss-comment-parser');
export default class Parser {
constructor (config) {
this.annotations = new AnnotationApi();
this.scssParser = new ScssCommentParser(this.annotations.list, config);
this.scssParser.commentParser.on('warning', (warning) => {
config.logger.warn(warning);
});
}
parse(...args) {
return this.scssParser.parse(args);
}
/**
* Invoke the `resolve` function of an annotation if present.
* Called with all found annotations except with type "unkown".
*/
postProcess(data) {
Object.keys(this.annotations.list).forEach(key => {
let annotation = this.annotations.list[key];
if (annotation.resolve) {
annotation.resolve(data);
}
});
return data;
}
}
|
Fix order and display of areas. | <?php
namespace Kula\HEd\Bundle\GradingBundle\Field;
use Kula\Core\Component\Field\Field;
class AreaName extends Field {
public function select($schema, $param) {
$menu = array();
$result = $this->db()->db_select('STUD_DEGREE_AREA', 'area')
->fields('area', array('AREA_ID', 'AREA_NAME'))
->join('CORE_LOOKUP_VALUES', 'area_types', "area_types.CODE = area.AREA_TYPE AND area_types.LOOKUP_TABLE_ID = (SELECT LOOKUP_TABLE_ID FROM CORE_LOOKUP_TABLES WHERE LOOKUP_TABLE_NAME = 'HEd.Grading.Degree.AreaTypes')")
->fields('area_types', array('DESCRIPTION' => 'area_type'))
->orderBy('DESCRIPTION', 'ASC', 'area_types')
->orderBy('AREA_NAME', 'ASC', 'area')
->execute();
while ($row = $result->fetch()) {
$menu[$row['AREA_ID']] = $row['area_type'].' - '.$row['AREA_NAME'];
}
return $menu;
}
} | <?php
namespace Kula\HEd\Bundle\GradingBundle\Field;
use Kula\Core\Component\Field\Field;
class AreaName extends Field {
public function select($schema, $param) {
$menu = array();
$result = $this->db()->db_select('STUD_DEGREE_AREA', 'area')
->fields('area', array('AREA_ID', 'AREA_NAME'))
->join('CORE_LOOKUP_VALUES', 'area_types', "area_types.CODE = area.AREA_TYPE AND area_types.LOOKUP_TABLE_ID = (SELECT LOOKUP_TABLE_ID FROM CORE_LOOKUP_TABLES WHERE LOOKUP_TABLE_NAME = 'HEd.Grading.Degree.AreaTypes')")
->fields('area_types', array('DESCRIPTION' => 'area_type'))
->orderBy('DESCRIPTION', 'ASC')
->orderBy('AREA_NAME', 'ASC')
->execute();
while ($row = $result->fetch()) {
$menu[$row['AREA_ID']] = $row['AREA_NAME'].' - '.$row['area_type'];
}
return $menu;
}
} |
Add a method to EndpointController to get back the Renderable representation of its data. | /**
* The default controller for your page structure.
*/
var turnpike = require('turnpike');
var util = require('util');
var _ = turnpike.imports.underscore;
/**
* Controller that composes page elements and prepares a complete HTML document for delivery.
*
* @param connection
* @constructor
*/
function Page(connection) {
turnpike.classes.base.controller.PageComposerController.call(this, connection);
this.prepare = function(next) {
this.mode = 'main';
this.data = {
'body': this.connection.response(),
'title': this.connection.controller.title + ' | ' + turnpike.config.sitename
};
process.nextTick(next);
};
}
util.inherits(Page, turnpike.classes.base.controller.PageComposerController);
module.exports = Page;
| /**
* The default controller for your page structure.
*/
var turnpike = require('turnpike');
var util = require('util');
var _ = turnpike.imports.underscore;
/**
* Controller that composes page elements and prepares a complete HTML document for delivery.
*
* @param connection
* @constructor
*/
function Page(connection) {
turnpike.classes.base.controller.PageComposerController.call(this, connection);
this.view = turnpike.application.views.Page;
this.prepare = function(next) {
this.mode = 'main';
this.data = {
'body': this.connection.response(),
'title': this.connection.controller.title + ' | ' + turnpike.config.sitename
};
process.nextTick(next);
};
}
util.inherits(Page, turnpike.classes.base.controller.PageComposerController);
module.exports = Page;
|
Handle filepaths in an OS independent manner.
--CAR | from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
class MyEventHandler(FileSystemEventHandler):
def __init__(self, filePath, callback):
super(MyEventHandler, self).__init__()
self.filePath = filePath
self.callback = callback
def on_modified(self, event):
if os.path.normpath(event.src_path) == self.filePath:
self.callback()
class LibraryFileWatcher(object):
def __init__(self, filePath, callback):
super(LibraryFileWatcher, self).__init__()
self.filePath = os.path.normpath(filePath)
self.callback = callback
self.eventHandler = MyEventHandler(self.filePath, callback)
self.resume()
def __del__(self):
self.observer.stop()
self.observer.join()
def pause(self):
self.observer.stop()
def resume(self):
self.observer = Observer()
self.watch = self.observer.schedule(self.eventHandler, path=os.path.dirname(self.filePath))
self.observer.start() | from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
class MyEventHandler(FileSystemEventHandler):
def __init__(self, filePath, callback):
super(MyEventHandler, self).__init__()
self.filePath = filePath
self.callback = callback
def on_modified(self, event):
if event.src_path == self.filePath:
self.callback()
class LibraryFileWatcher(object):
def __init__(self, filePath, callback):
super(LibraryFileWatcher, self).__init__()
self.filePath = filePath
self.callback = callback
self.eventHandler = MyEventHandler(filePath, callback)
self.resume()
def __del__(self):
self.observer.stop()
self.observer.join()
def pause(self):
self.observer.stop()
def resume(self):
self.observer = Observer()
self.watch = self.observer.schedule(self.eventHandler, path=os.path.dirname(self.filePath))
self.observer.start() |
Change to plugin interface: unload() is no longer part of the protocol, and any unloading a plugin needs to do can just be done by registering an atexit handler.
git-svn-id: b6fd099cd3d97ba56ca68c4d1ea7aaa6a131ba03@17 8b7adc99-b347-0410-ae0a-d9e86c8d69b5 | # TODO: Add documentation for this module.
import logging
import enso.config
def install( eventManager ):
eventManager.registerResponder( _init, "init" )
def _init():
for moduleName in enso.config.PLUGINS:
try:
# Import the module; most of this code was taken from the
# Python Library Reference documentation for __import__().
module = __import__( moduleName, {}, {}, [], 0 )
components = moduleName.split( "." )
for component in components[1:]:
module = getattr( module, component )
module.load()
except:
logging.warn( "Error while loading plugin '%s'." % moduleName )
raise
logging.info( "Loaded plugin '%s'." % moduleName )
| # TODO: Add documentation for this module.
import logging
import atexit
import enso.config
_plugins = []
def install( eventManager ):
eventManager.registerResponder( _init, "init" )
atexit.register( _shutdown )
def _init():
for moduleName in enso.config.PLUGINS:
try:
# Import the module; most of this code was taken from the
# Python Library Reference documentation for __import__().
module = __import__( moduleName, {}, {}, [], 0 )
components = moduleName.split( "." )
for component in components[1:]:
module = getattr( module, component )
module.load()
_plugins.append( (module, moduleName) )
except:
logging.warn( "Error while loading plugin '%s'." % moduleName )
raise
logging.info( "Loaded plugin '%s'." % moduleName )
def _shutdown():
for module, moduleName in _plugins:
try:
module.unload()
except:
logging.warn( "Error while unloading plugin '%s'." % moduleName )
raise
logging.info( "Unloaded plugin '%s'." % moduleName )
_plugins[:] = []
|
Test 1 of Serene Grace | exports.BattleAbilities = {
"serenegrace": {
inherit: true
onModifyMovePriority: -101,
onModifyMove: function(move) {
if (move.secondaries) {
this.debug('doubling secondary chance');
for (var i=0; i<move.secondaries.length; i++) {
if move.secondaries[i].chance >= 50 {
move.secondaries[i].chance = 100;
}
}
}
}
},
"skilllink": {
inherit: true
onModifyMove: function(move) {
if (move.multihit && move.multihit.length) {
if (move.multihit[1] === 3 && move.id !== "triplekick") {
move.multihit = 5;
}
}
}
}
};
| exports.BattleAbilities = {
"serenegrace": {
inherit: true
onModifyMove: function(move) {
if (move.secondaries) {
this.debug('doubling secondary chance');
for (var i=0; i<move.secondaries.length; i++) {
if move.secondaries[i].chance >= 50 {
move.secondaries[i].chance = 100;
}
}
}
}
},
"skilllink": {
inherit: true
onModifyMove: function(move) {
if (move.multihit && move.multihit.length) {
if (move.multihit[1] === 3 && move.id !== "triplekick") {
move.multihit = 5;
}
}
}
}
};
|
Add a more useful representation of Shipper objects | import re
class Shipper(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('shippers.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
return bool(re.match(self.barcode_pattern, self.barcode))
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Shipper):
shipper = 'Unknown'
@property
def matches_barcode(self):
return False
| import re
class Shipper(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
return bool(re.match(self.barcode_pattern, self.barcode))
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Shipper):
shipper = 'Unknown'
@property
def matches_barcode(self):
return False
|
[add] Add a description to an event | from django.db import models
from django.conf import settings
# Create your models here.
#Events :
# Des users peuvent participer à un event
# Les gens peuvnet être "intéressés"
# Utiliser https://github.com/thoas/django-sequere ?
# API hackeragenda
class Event(models.Model):
STATUS_CHOICES = (
("i", "in preparation"),
("r", "ready"),
("p", "planned"),
("j", "just an idea"),
)
place = models.CharField(max_length=300)
start = models.DateTimeField()
stop = models.DateTimeField()
title = models.CharField(max_length=300)
status = models.CharField(max_length=1, choices=STATUS_CHOICES)
organizer = models.ForeignKey(settings.AUTH_USER_MODEL)
description = models.TextField()
| from django.db import models
from django.conf import settings
# Create your models here.
#Events :
# Des users peuvent participer à un event
# Les gens peuvnet être "intéressés"
# Utiliser https://github.com/thoas/django-sequere ?
# API hackeragenda
class Event(models.Model):
STATUS_CHOICES = (
("i", "in preparation"),
("r", "ready"),
("p", "planned"),
("j", "just an idea"),
)
place = models.CharField(max_length=300)
start = models.DateTimeField()
stop = models.DateTimeField()
title = models.CharField(max_length=300)
status = models.CharField(max_length=1, choices=STATUS_CHOICES)
organizer = models.ForeignKey(settings.AUTH_USER_MODEL)
|
Fix Multiplication operation in new SQL executor | /* Generated By:JJTree: Do not edit this line. OMultExpression.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.orientechnologies.orient.core.sql.parser;
import java.util.Set;
public
class OMultExpression extends OMathExpression {
public OMultExpression(int id) {
super(id);
}
public OMultExpression(OrientSql p, int id) {
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public boolean needsAliases(Set<String> aliases) {
return super.needsAliases(aliases);
}
}
/* JavaCC - OriginalChecksum=f75b8be48dca1e0cafae0cacadc608c8 (do not edit this line) */
| /* Generated By:JJTree: Do not edit this line. OMultExpression.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.orientechnologies.orient.core.sql.parser;
import java.util.Set;
public
class OMultExpression extends OMathExpression {
public OMultExpression(int id) {
super(id);
}
public OMultExpression(OrientSql p, int id) {
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public boolean needsAliases(Set<String> aliases) {
throw new UnsupportedOperationException();
}
}
/* JavaCC - OriginalChecksum=f75b8be48dca1e0cafae0cacadc608c8 (do not edit this line) */
|
Use a sensible tile extension - use the same as OsmAnd | package org.andnav.osm.tileprovider.constants;
import java.io.File;
import android.os.Environment;
/**
*
* This class contains constants used by the service.
*
* @author Neil Boyd
*
*/
public interface OpenStreetMapTileProviderConstants {
// ===========================================================
// Final Fields
// ===========================================================
public static final boolean DEBUGMODE = false;
/** Base path for osmdroid files. Zip files are in this folder. */
public static final File OSMDROID_PATH = new File(Environment.getExternalStorageDirectory(), "osmdroid");
/** Base path for tiles. */
public static final File TILE_PATH_BASE = new File(OSMDROID_PATH, "tiles");
/** add an extension to files on sdcard so that gallery doesn't index them */
public static final String TILE_PATH_EXTENSION = ".tile";
public static final int NUMBER_OF_TILE_DOWNLOAD_THREADS = 8;
public static final int NUMBER_OF_TILE_FILESYSTEM_THREADS = 8;
public static final int TILE_DOWNLOAD_MAXIMUM_QUEUE_SIZE = 40;
public static final int TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE = 40;
/** 30 days */
public static final long TILE_EXPIRY_TIME_MILLISECONDS = 1000L * 60 * 60 * 24 * 30;
// ===========================================================
// Methods
// ===========================================================
}
| package org.andnav.osm.tileprovider.constants;
import java.io.File;
import android.os.Environment;
/**
*
* This class contains constants used by the service.
*
* @author Neil Boyd
*
*/
public interface OpenStreetMapTileProviderConstants {
// ===========================================================
// Final Fields
// ===========================================================
public static final boolean DEBUGMODE = false;
/** Base path for osmdroid files. Zip files are in this folder. */
public static final File OSMDROID_PATH = new File(Environment.getExternalStorageDirectory(), "osmdroid");
/** Base path for tiles. */
public static final File TILE_PATH_BASE = new File(OSMDROID_PATH, "tiles");
/** add an extension to files on sdcard so that gallery doesn't index them */
public static final String TILE_PATH_EXTENSION = ".x";
public static final int NUMBER_OF_TILE_DOWNLOAD_THREADS = 8;
public static final int NUMBER_OF_TILE_FILESYSTEM_THREADS = 8;
public static final int TILE_DOWNLOAD_MAXIMUM_QUEUE_SIZE = 40;
public static final int TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE = 40;
/** 30 days */
public static final long TILE_EXPIRY_TIME_MILLISECONDS = 1000L * 60 * 60 * 24 * 30;
// ===========================================================
// Methods
// ===========================================================
}
|
Test for uploading files to /media/ folder in S3 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models import PointField
from .storage import user_store
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
location = PointField(
null=True,
blank=True,
help_text='User Location, only read in production user admin panel'
)
picture = models.ImageField(
null=True,
blank=True,
help_text='Profile Picture',
storage=user_store
)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db.models import PointField
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
location = PointField(
null=True,
blank=True,
help_text='User Location, only read in production user admin panel'
)
picture = models.ImageField(
null=True,
blank=True,
help_text='Profile Picture'
)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
|
Set default title to single dash character temporarily | <?php
namespace Ojs\JournalBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Ojs\CoreBundle\Entity\DisplayTrait;
use Prezent\Doctrine\Translatable\Annotation as Prezent;
use Prezent\Doctrine\Translatable\Entity\AbstractTranslation;
class SectionTranslation extends AbstractTranslation
{
use DisplayTrait;
/**
* @Prezent\Translatable(targetEntity="Ojs\JournalBundle\Entity\Section")
*/
protected $translatable;
/**
* @var string
*/
private $title = '-';
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
*/
public function setTitle($title)
{
if ($title !== null) {
$this->title = $title;
}
}
}
| <?php
namespace Ojs\JournalBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Ojs\CoreBundle\Entity\DisplayTrait;
use Prezent\Doctrine\Translatable\Annotation as Prezent;
use Prezent\Doctrine\Translatable\Entity\AbstractTranslation;
class SectionTranslation extends AbstractTranslation
{
use DisplayTrait;
/**
* @Prezent\Translatable(targetEntity="Ojs\JournalBundle\Entity\Section")
*/
protected $translatable;
/**
* @var string
*/
private $title;
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
}
|
Fix system tests when running on GCE
The new project ID logic for Cloud SDK invokes Cloud SDK directly. Cloud SDK helpfully falls back to the GCE project ID if the project ID is unset in the configuration. This breaks one of our previous expectations. | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import google.auth
EXPECT_PROJECT_ID = os.environ.get('EXPECT_PROJECT_ID')
def test_application_default_credentials(verify_refresh):
credentials, project_id = google.auth.default()
if EXPECT_PROJECT_ID is not None:
assert project_id is not None
verify_refresh(credentials)
| # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import google.auth
EXPECT_PROJECT_ID = os.environ.get('EXPECT_PROJECT_ID')
def test_application_default_credentials(verify_refresh):
credentials, project_id = google.auth.default()
if EXPECT_PROJECT_ID is not None:
assert project_id is not None
else:
assert project_id is None
verify_refresh(credentials)
|
Fix wrong @Value for spark context configuration. | package org.talend.dataprep.dataset.configuration;
import java.util.UUID;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnProperty("dataset.spark.master")
public class Spark {
@Value("${dataset.spark.master}")
private String sparkMasterUrl;
@Bean
public SparkContext getSparkContext() {
SparkConf conf = new SparkConf();
conf.set("spark.ui.enabled", "false"); //$NON-NLS-1$ //$NON-NLS-2$
return new SparkContext(sparkMasterUrl, UUID.randomUUID().toString(), conf);
}
}
| package org.talend.dataprep.dataset.configuration;
import java.util.UUID;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnProperty("dataset.spark.master")
public class Spark {
@Value("dataset.spark.master")
private String sparkMasterUrl;
@Bean
public SparkContext getSparkContext() {
SparkConf conf = new SparkConf();
conf.set("spark.ui.enabled", "false"); //$NON-NLS-1$ //$NON-NLS-2$
return new SparkContext(sparkMasterUrl, UUID.randomUUID().toString(), conf);
}
}
|
Revert "CW + AW | 225 | add instance path when building app"
This reverts commit 9aa8d2ec4f49dfe8261893de70887052cf134bd5. | # Copyright (c) 2015 ThoughtWorks
#
# See the file LICENSE for copying permission.
import flask
from openahjo_activity_streams import convert
import requests
import logging
import json
OPENAHJO_URL = 'http://dev.hel.fi/paatokset/v1/agenda_item/?order_by=-last_modified_time'
def create_app(remote_url=OPENAHJO_URL, converter=convert.to_activity_stream):
logging.basicConfig(level=logging.INFO)
application = flask.Flask(__name__)
application.config['REMOTE_URL'] = remote_url
application.config['CONVERTER'] = converter
@application.route('/')
def show_something():
openahjo_data = requests.get(application.config['REMOTE_URL'])
converted_data = application.config['CONVERTER'](openahjo_data.json())
return application.response_class(json.dumps(converted_data), mimetype='application/activity+json')
return application
application = create_app()
if __name__ == '__main__':
application.run()
| # Copyright (c) 2015 ThoughtWorks
#
# See the file LICENSE for copying permission.
import os
import flask
from openahjo_activity_streams import convert
import requests
import logging
import json
OPENAHJO_URL = 'http://dev.hel.fi/paatokset/v1/agenda_item/?order_by=-last_modified_time'
def create_app(remote_url=OPENAHJO_URL, converter=convert.to_activity_stream):
logging.basicConfig(level=logging.INFO)
application = flask.Flask(__name__, instance_path=os.environ['INSTANCE_PATH'])
application.config['REMOTE_URL'] = remote_url
application.config['CONVERTER'] = converter
@application.route('/')
def show_something():
openahjo_data = requests.get(application.config['REMOTE_URL'])
converted_data = application.config['CONVERTER'](openahjo_data.json())
return application.response_class(json.dumps(converted_data), mimetype='application/activity+json')
return application
application = create_app()
if __name__ == '__main__':
application.run()
|
Remove the executable property to allow override.
This problem was discussed here : SublimeLinter/SublimeLinter#455
If the `executable` property is defined, the plugin require the host system to have a global `phpcs` binary. If I haven't that binary installed (eg. I use composer to install inside my project folder) and I use the `*.sublime-project` file to configure my linter, the phpcs linter is never executed.
```
{
"folders":
[
{
"path": "."
}
],
"SublimeLinter": {
"linters": {
"phpcs": {
"standard": "${folder}/phpcs.xml",
"cmd": "${folder}/vendor/bin/phpcs"
}
}
}
}
```
With that update suggested by @kaste the global binary is returned only if the configuration doesn't defined a specific one. | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = ['phpcs']
command.append('--report=checkstyle')
return command
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
executable = 'phpcs'
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = [self.executable_path]
command.append('--report=checkstyle')
return command
|
Remove hard-code callback url from the requestBuilder, build via urlBuilder instead. | <?php
namespace Omise\Payment\Gateway\Request;
use Magento\Framework\UrlInterface;
use Magento\Payment\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Request\BuilderInterface;
use Omise\Payment\Observer\OffsiteInternetbankingDataAssignObserver;
class PaymentOffsiteBuilder implements BuilderInterface
{
/**
* @var string
*/
const OFFSITE = 'offsite';
/**
* @var string
*/
const RETURN_URI = 'return_uri';
/**
* @var \Magento\Framework\UrlInterface
*/
protected $url;
public function __construct(UrlInterface $url)
{
$this->url = $url;
}
/**
* @param array $buildSubject
*
* @return array
*/
public function build(array $buildSubject)
{
$payment = SubjectReader::readPayment($buildSubject);
$method = $payment->getPayment();
return [
self::OFFSITE => $method->getAdditionalInformation(OffsiteInternetbankingDataAssignObserver::OFFSITE),
self::RETURN_URI => $this->url->getUrl('omise/callback/internetbanking', ['_secure' => true])
];
}
}
| <?php
namespace Omise\Payment\Gateway\Request;
use Magento\Payment\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Request\BuilderInterface;
use Omise\Payment\Observer\OffsiteInternetbankingDataAssignObserver;
class PaymentOffsiteBuilder implements BuilderInterface
{
/**
* @var string
*/
const OFFSITE = 'offsite';
/**
* @var string
*/
const RETURN_URI = 'return_uri';
/**
* @param array $buildSubject
*
* @return array
*/
public function build(array $buildSubject)
{
$payment = SubjectReader::readPayment($buildSubject);
$method = $payment->getPayment();
return [
self::OFFSITE => $method->getAdditionalInformation(OffsiteInternetbankingDataAssignObserver::OFFSITE),
self::RETURN_URI => 'http://127.0.0.1' // TODO: Remove this dump-data
];
}
}
|
Change the comment from timestamp plugin to addCreatedAndModified plugin | var vows = require('vows')
, assert = require('assert')
, mongoose = require('mongoose')
, timestamp = require('../lib/addCreatedAndModified')
, util = require('util')
// DB setup
mongoose.connect('mongodb://localhost/mongoose_troop')
// Setting up test schema
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
var BlogPost = new Schema({
author : String
, title : String
, body : String
})
// Registering the addCreatedAndModified plugin with mongoose
// Note: Must be defined before creating schema object
mongoose.plugin(timestamp,{debug: true})
var Blog = mongoose.model('BlogPost',BlogPost)
vows.describe('Add create and modified').addBatch({
'when this plugin registered by default':{
topic: function(){
var blog = new Blog()
blog.author = "butu5"
blog.title = "Mongoose troops!!! timestamp plugin "
blog.save(this.callback)
},
'it should create created and modified attribute': function(topic){
assert.equal(util.isDate(topic.created),true)
assert.equal(util.isDate(topic.modified),true)
}
}
}).run()
| var vows = require('vows')
, assert = require('assert')
, mongoose = require('mongoose')
, timestamp = require('../lib/addCreatedAndModified')
, util = require('util')
// DB setup
mongoose.connect('mongodb://localhost/mongoose_troop')
// Setting up test schema
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
var BlogPost = new Schema({
author : String
, title : String
, body : String
})
// Registering the timestamp plugin with mongoose
// Note: Must be defined before creating schema object
mongoose.plugin(timestamp,{debug: true})
var Blog = mongoose.model('BlogPost',BlogPost)
vows.describe('Add create and modified').addBatch({
'when this plugin registered by default':{
topic: function(){
var blog = new Blog()
blog.author = "butu5"
blog.title = "Mongoose troops!!! timestamp plugin "
blog.save(this.callback)
},
'it should create created and modified attribute': function(topic){
assert.equal(util.isDate(topic.created),true)
assert.equal(util.isDate(topic.modified),true)
}
}
}).run()
|
Make Ignores try to find '.mnignore'
If it doesn't find it, that's okay, and no action is required. | import os
from fnmatch import fnmatchcase
import click
from morenines.util import find_file
class Ignores(object):
@classmethod
def read(cls, path):
if not path:
path = find_file('.mnignore')
ignores = cls()
if path:
with click.open_file(path, 'r') as stream:
ignores.patterns = [line.strip() for line in stream]
return ignores
def __init__(self):
self.patterns = []
def match(self, path):
filename = os.path.basename(path)
if any(fnmatchcase(filename, pattern) for pattern in self.patterns):
return True
else:
return False
| import os
from fnmatch import fnmatchcase
import click
class Ignores(object):
@classmethod
def read(cls, path):
ignores = cls()
if path:
with click.open_file(path, 'r') as stream:
ignores.patterns = [line.strip() for line in stream]
return ignores
def __init__(self):
self.patterns = []
def match(self, path):
filename = os.path.basename(path)
if any(fnmatchcase(filename, pattern) for pattern in self.patterns):
return True
else:
return False
|
Use a type assertion on the io.Reader to make it an os.File, and to access so to its FD | // Copyright 2010 The "go-linoise" Authors
//
// Use of this source code is governed by the Simplified BSD License
// that can be found in the LICENSE file.
//
// This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License
// for more details.
package linoise
import (
"fmt"
"os"
"testing"
"github.com/kless/go-term/term"
)
func Test(t *testing.T) {
term.MakeRaw(Input.(*os.File).Fd())
defer term.RestoreTermios()
hist, err := NewHistory("/tmp/go-history")
if err != nil {
t.Error(err)
}
hist.Load()
ln := NewLine(hist, "matrix> ")
if err = ln.Run(); err != nil {
fmt.Println(err)
} else {
hist.Save()
}
}
| // Copyright 2010 The "go-linoise" Authors
//
// Use of this source code is governed by the Simplified BSD License
// that can be found in the LICENSE file.
//
// This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License
// for more details.
package linoise
import (
"os"
"testing"
"fmt"
"github.com/kless/go-term/term"
)
var stdin = 0
func Test(t *testing.T) {
term.MakeRaw(stdin)
defer term.RestoreTermios()
hist, err := NewHistory("/tmp/go-history")
if err != nil {
t.Error(err)
}
hist.Load()
ln := NewLine(os.Stdin, os.Stdout, hist, "matrix> ")
if err = ln.Run(); err != nil {
fmt.Println(err)
} else {
hist.Save()
}
}
|
Increase length of logged request responses in `HTTPException` | <?php
namespace wcf\util\exception;
use wcf\system\exception\IExtraInformationException;
use wcf\system\exception\SystemException;
use wcf\util\HTTPRequest;
use wcf\util\StringUtil;
/**
* Denotes failure to perform a HTTP request.
*
* @author Tim Duesterhus
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Util\Exception
* @since 3.0
*/
class HTTPException extends SystemException implements IExtraInformationException {
/**
* The HTTP request that lead to this Exception.
*
* @param HTTPRequest
*/
protected $http = null;
/**
* @inheritDoc
*/
public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) {
parent::__construct($message, $code, '', $previous);
$this->http = $http;
}
/**
* @inheritDoc
*/
public function getExtraInformation() {
$reply = $this->http->getReply();
$body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 512, StringUtil::HELLIP, true);
return [
['Body', $body],
['Status Code', $reply['statusCode']]
];
}
}
| <?php
namespace wcf\util\exception;
use wcf\system\exception\IExtraInformationException;
use wcf\system\exception\SystemException;
use wcf\util\HTTPRequest;
use wcf\util\StringUtil;
/**
* Denotes failure to perform a HTTP request.
*
* @author Tim Duesterhus
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Util\Exception
* @since 3.0
*/
class HTTPException extends SystemException implements IExtraInformationException {
/**
* The HTTP request that lead to this Exception.
*
* @param HTTPRequest
*/
protected $http = null;
/**
* @inheritDoc
*/
public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) {
parent::__construct($message, $code, '', $previous);
$this->http = $http;
}
/**
* @inheritDoc
*/
public function getExtraInformation() {
$reply = $this->http->getReply();
$body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 80, StringUtil::HELLIP, true);
return [
['Body', $body],
['Status Code', $reply['statusCode']]
];
}
}
|
Make preview URLs include trailing slash when slug is given
- the trailing slash isn't shown usually
- slash added when a slug is given to be more correct | /*
Example usage:
{{gh-url-preview prefix="tag" slug=theSlugValue tagName="p" classNames="description"}}
*/
var urlPreview = Ember.Component.extend({
classNames: 'ghost-url-preview',
prefix: null,
slug: null,
theUrl: null,
generateUrl: function () {
// Get the blog URL and strip the scheme
var blogUrl = this.get('config').blogUrl,
noSchemeBlogUrl = blogUrl.substr(blogUrl.indexOf('://') + 3), // Remove `http[s]://`
// Get the prefix and slug values
prefix = this.get('prefix') ? this.get('prefix') + '/' : '',
slug = this.get('slug') ? this.get('slug') : '',
// Join parts of the URL together with slashes
theUrl = noSchemeBlogUrl + '/' + prefix + (slug ? slug + '/' : '');
this.set('the-url', theUrl);
}.on('didInsertElement').observes('slug')
});
export default urlPreview;
| /*
Example usage:
{{gh-url-preview prefix="tag" slug=theSlugValue tagName="p" classNames="description"}}
*/
var urlPreview = Ember.Component.extend({
classNames: 'ghost-url-preview',
prefix: null,
slug: null,
theUrl: null,
generateUrl: function () {
// Get the blog URL and strip the scheme
var blogUrl = this.get('config').blogUrl,
noSchemeBlogUrl = blogUrl.substr(blogUrl.indexOf('://') + 3), // Remove `http[s]://`
// Get the prefix and slug values
prefix = this.get('prefix') ? this.get('prefix') + '/' : '',
slug = this.get('slug') ? this.get('slug') : '',
// Join parts of the URL together with slashes
theUrl = noSchemeBlogUrl + '/' + prefix + slug;
this.set('the-url', theUrl);
}.on('didInsertElement').observes('slug')
});
export default urlPreview;
|
Add strings in weak quotes | """celery.backends"""
from functools import partial
from django.conf import settings
import sys
DEFAULT_BACKEND = "database"
CELERY_BACKEND = getattr(settings, "CELERY_BACKEND", DEFAULT_BACKEND)
def get_backend_cls(backend):
"""Get backend class by name.
If the name does not include "``.``" (is not fully qualified),
``"celery.backends."`` will be prepended to the name. e.g.
``"database"`` becomes ``"celery.backends.database"``.
"""
if backend.find(".") == -1:
backend = "celery.backends.%s" % backend
__import__(backend)
backend_module = sys.modules[backend]
return getattr(backend_module, 'Backend')
"""
.. function:: get_default_backend_cls()
Get the backend class specified in :settings:`CELERY_BACKEND`.
"""
get_default_backend_cls = partial(get_backend_cls, CELERY_BACKEND)
"""
.. class:: DefaultBackend
The backend class specified in :setting:`CELERY_BACKEND`.
"""
DefaultBackend = get_default_backend_cls()
"""
.. data:: default_backend
An instance of :class:`DefaultBackend`.
"""
default_backend = DefaultBackend()
| """celery.backends"""
from functools import partial
from django.conf import settings
import sys
DEFAULT_BACKEND = "database"
CELERY_BACKEND = getattr(settings, "CELERY_BACKEND", DEFAULT_BACKEND)
def get_backend_cls(backend):
"""Get backend class by name.
If the name does not include "``.``" (is not fully qualified),
``celery.backends.`` will be prepended to the name. e.g.
``database`` becomes ``celery.backends.database``.
"""
if backend.find(".") == -1:
backend = "celery.backends.%s" % backend
__import__(backend)
backend_module = sys.modules[backend]
return getattr(backend_module, 'Backend')
"""
.. function:: get_default_backend_cls()
Get the backend class specified in :settings:`CELERY_BACKEND`.
"""
get_default_backend_cls = partial(get_backend_cls, CELERY_BACKEND)
"""
.. class:: DefaultBackend
The backend class specified in :setting:`CELERY_BACKEND`.
"""
DefaultBackend = get_default_backend_cls()
"""
.. data:: default_backend
An instance of :class:`DefaultBackend`.
"""
default_backend = DefaultBackend()
|
Remove listener on component unmount | import React from 'react';
import LoadingSpinner from './LoadingSpinner';
class IFrame extends React.Component {
constructor() {
super();
this.state = {
loaded: false,
height: 400
};
}
componentDidMount() {
this.refs.iframe.addEventListener('load', () => this.onLoad());
}
componentWillUnmount() {
this.refs.iframe.removeEventListener('load', () => this.onLoad());
}
onLoad() {
const height = this.refs.iframe.contentDocument.body.scrollHeight;
this.setState({ loaded: true, height });
}
render() {
let loading;
if (!this.state.loaded) loading = <LoadingSpinner />;
return (
<div className="c-iframe" style={{ height: this.state.height }}>
{loading}
<iframe ref="iframe" src={this.props.src}></iframe>
</div>
);
}
}
IFrame.propTypes = {
/**
* The source url to load iframe
*/
src: React.PropTypes.string.isRequired,
};
export default IFrame;
| import React from 'react';
import LoadingSpinner from './LoadingSpinner';
class IFrame extends React.Component {
constructor() {
super();
this.state = {
loaded: false,
height: 400
};
}
componentDidMount() {
this.refs.iframe.addEventListener('load', () => this.onLoad());
}
onLoad() {
const height = this.refs.iframe.contentDocument.body.scrollHeight;
this.setState({ loaded: true, height });
}
render() {
let loading;
if (!this.state.loaded) loading = <LoadingSpinner />;
return (
<div className="c-iframe" style={{ height: this.state.height }}>
{loading}
<iframe ref="iframe" src={this.props.src}></iframe>
</div>
);
}
}
IFrame.propTypes = {
/**
* The source url to load iframe
*/
src: React.PropTypes.string.isRequired,
};
export default IFrame;
|
Update to use Turbolinks events | $(document).on('ready turbolinks:load', function() {
$("#create_filter").on("click", function(ev) {
var checkboxes = $("input[type=checkbox]");
var bits = new Array(checkboxes.length);
$.each(checkboxes, function(index, item) {
var $item = $(item);
var arrayIndex = $item.data("index");
if ($item.is(":checked")) {
bits[arrayIndex] = 1;
}
else {
bits[arrayIndex] = 0;
}
});
var unsafeFilter = "";
while (bits.length) {
var nextByte = bits.splice(0, 8).join("");
var charCode = parseInt(nextByte.toString(), 2);
unsafeFilter += String.fromCharCode(charCode);
console.log(nextByte, charCode, unsafeFilter);
}
var filter = encodeURIComponent(unsafeFilter);
prompt("Calculated, URL-encoded filter:", filter);
});
});
| $(document).ready(function() {
$("#create_filter").on("click", function(ev) {
var checkboxes = $("input[type=checkbox]");
var bits = new Array(checkboxes.length);
$.each(checkboxes, function(index, item) {
var $item = $(item);
var arrayIndex = $item.data("index");
if ($item.is(":checked")) {
bits[arrayIndex] = 1;
}
else {
bits[arrayIndex] = 0;
}
});
var unsafeFilter = "";
while (bits.length) {
var nextByte = bits.splice(0, 8).join("");
var charCode = parseInt(nextByte.toString(), 2);
unsafeFilter += String.fromCharCode(charCode);
console.log(nextByte, charCode, unsafeFilter);
}
var filter = encodeURIComponent(unsafeFilter);
prompt("Calculated, URL-encoded filter:", filter);
});
});
|
Fix the scheduling / tracking check | def on_enter(event_data):
""" """
pocs = event_data.model
pocs.say("Analyzing image...")
try:
observation = pocs.observatory.current_observation
image_info = pocs.observatory.analyze_recent()
pocs.logger.debug("Image information: {}".format(image_info))
pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp))
if observation.current_exp >= observation.min_nexp:
if observation.current_exp % observation.exp_set_size == 0:
pocs.next_state = 'scheduling'
else:
pocs.next_state = 'tracking'
except Exception as e:
pocs.logger.error("Problem in analyzing: {}".format(e))
pocs.next_state = 'parking'
| def on_enter(event_data):
""" """
pocs = event_data.model
pocs.say("Analyzing image...")
try:
observation = pocs.observatory.current_observation
image_info = pocs.observatory.analyze_recent()
pocs.logger.debug("Image information: {}".format(image_info))
pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp))
if (observation.current_exp - observation.min_nexp) % observation.exp_set_size == 0:
pocs.next_state = 'scheduling'
else:
pocs.next_state = 'tracking'
except Exception as e:
pocs.logger.error("Problem in analyzing: {}".format(e))
pocs.next_state = 'parking'
|
Remove unused flow suppression comment | // @flow
/* global fetch */
import merge from 'lodash/merge'
type ResponseBody = Object | null | string
const fetchJSON = (url: string | Request | URL, options: Object = {}) => {
const jsonOptions = merge(
{
headers: {
'Content-Type': 'application/json'
}
},
options
)
return fetch(url, jsonOptions)
.then((response: Response) => {
return getResponseBody(response).then(body => ({
response,
body
}))
})
.then(checkStatus)
}
const getResponseBody = (response: Response): Promise<ResponseBody> => {
const contentType = response.headers.get('content-type')
return contentType && contentType.indexOf('json') >= 0
? response.text().then(tryParseJSON)
: response.text()
}
const tryParseJSON = (json: string): Object | null => {
if (!json) {
return null
}
try {
return JSON.parse(json)
} catch (e) {
throw new Error(`Failed to parse unexpected JSON response: ${json}`)
}
}
function ResponseError (status: number, response: Response, body: ResponseBody) {
this.name = 'ResponseError'
this.status = status
this.response = response
this.body = body
}
// $FlowIssue
ResponseError.prototype = Error.prototype
const checkStatus = ({ response, body }) => {
if (response.ok) {
return { response, body }
} else {
throw new ResponseError(response.status, response, body)
}
}
export default fetchJSON
| // @flow
/* global fetch */
import merge from 'lodash/merge'
type ResponseBody = Object | null | string
const fetchJSON = (url: string | Request | URL, options: Object = {}) => {
const jsonOptions = merge(
{
headers: {
'Content-Type': 'application/json'
}
},
options
)
// $FlowIssue
return fetch(url, jsonOptions)
.then((response: Response) => {
return getResponseBody(response).then(body => ({
response,
body
}))
})
.then(checkStatus)
}
const getResponseBody = (response: Response): Promise<ResponseBody> => {
const contentType = response.headers.get('content-type')
return contentType && contentType.indexOf('json') >= 0
? response.text().then(tryParseJSON)
: response.text()
}
const tryParseJSON = (json: string): Object | null => {
if (!json) {
return null
}
try {
return JSON.parse(json)
} catch (e) {
throw new Error(`Failed to parse unexpected JSON response: ${json}`)
}
}
function ResponseError (status: number, response: Response, body: ResponseBody) {
this.name = 'ResponseError'
this.status = status
this.response = response
this.body = body
}
// $FlowIssue
ResponseError.prototype = Error.prototype
const checkStatus = ({ response, body }) => {
if (response.ok) {
return { response, body }
} else {
throw new ResponseError(response.status, response, body)
}
}
export default fetchJSON
|
Add commented example of using different View renderer instead of builtin one. | <?php
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
// --------------------------------------Register: Settings
$app->setName( 'SlimApp' );
$app->config( [
'templates.path' => __DIR__ . '/templates/', //This config can be omitted because is default one
'debug' => false, // Debug is set to false to demonstrate custom error handling (Monolog)
] );
// [Container: View - Twig]
// $app->view( new \Slim\Views\Twig() );
// [Container: Logger - Monolog]
$app->container->singleton( 'log', function () use ( $app ) {
$logger = new Logger( $app->getName() );
$logger->pushProcessor( new UidProcessor() );
$logger->pushHandler( new StreamHandler( 'logs/app.log', Logger::DEBUG ) );
return $logger;
} );
// --------------------------------------Register: Routes
$app->get( '/(:name)', function ( $name = "" ) use ( $app ) {
$args = [];
if ( empty( $name ) == false ) {
$args['name'] = $name;
}
// Write Log Message
$app->getLog()->info( "{$app->getName()} '/' route", $args );
// Render View
$app->render( 'index.phtml', $args );
} ); | <?php
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
// --------------------------------------Register: Settings
$app->setName( 'SlimApp' );
// [Container: View - PhpRenderer]
// $app->view( new Slim\Views\PhpRenderer() );
// [Container: Logger - Monolog]
$app->container->singleton( 'log', function () use ( $app ) {
$logger = new Logger( $app->getName() );
$logger->pushProcessor( new UidProcessor() );
$logger->pushHandler( new StreamHandler( 'logs/app.log', Logger::DEBUG ) );
return $logger;
} );
// --------------------------------------Register: Routes
$app->get( '/(:name)', function ( $name = "" ) use ( $app ) {
$args = [];
if ( empty( $name ) == false ) {
$args['name'] = $name;
}
// Write Log Message
$app->getLog()->info( "{$app->getName()} '/' route", $args );
// Render View
$app->render( 'index.phtml', $args );
} ); |
Revert "experimenting with history location"
This reverts commit 7494e0f0954f57526f0ef28e17294c211562ed01. | var Router = Ember.Router.extend();
Router.map(function () {
this.resource("clients", function () {
this.route("new");
this.resource("client", { path: "/:client_id" }, function () {
this.route("edit");
});
});
this.resource("accounts", function () {
this.route("new");
this.resource("account", { path: "/:account_id" }, function () {
this.route("edit");
});
});
this.resource("invoices", function () {
this.route("new");
this.resource("invoice", { path: "/:invoice_id" }, function () {
this.route("show", { path: "/" });
this.route("edit");
});
});
this.resource("settings");
});
export default Router;
| var Router = Ember.Router.extend({
location: "history"
});
Router.map(function () {
this.resource("clients", function () {
this.route("new");
this.resource("client", { path: "/:client_id" }, function () {
this.route("edit");
});
});
this.resource("accounts", function () {
this.route("new");
this.resource("account", { path: "/:account_id" }, function () {
this.route("edit");
});
});
this.resource("invoices", function () {
this.route("new");
this.resource("invoice", { path: "/:invoice_id" }, function () {
this.route("show", { path: "/" });
this.route("edit");
});
});
this.resource("settings");
});
export default Router;
|
Fix backward compatibility for RN < 0.47 | /**
* Copyright (c) 2017-present, Stanislav Doskalenko - doskalenko.s@gmail.com
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Based on Asim Malik's android source code, copyright (c) 2015
*
**/
package com.reactnative.googlefit;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.*;
public class GoogleFitPackage implements ReactPackage {
public static String PACKAGE_NAME;
public GoogleFitPackage(String PACKAGE_NAME) {
this.PACKAGE_NAME = PACKAGE_NAME;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new GoogleFitModule(reactContext));
return modules;
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return new ArrayList<>();
}
} | /**
* Copyright (c) 2017-present, Stanislav Doskalenko - doskalenko.s@gmail.com
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Based on Asim Malik's android source code, copyright (c) 2015
*
**/
package com.reactnative.googlefit;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.*;
public class GoogleFitPackage implements ReactPackage {
public static String PACKAGE_NAME;
public GoogleFitPackage(String PACKAGE_NAME) {
this.PACKAGE_NAME = PACKAGE_NAME;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new GoogleFitModule(reactContext));
return modules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return new ArrayList<>();
}
} |
Fix payment method label for narrow boxes
Reviewed and approved by @fertxigan
Fix #18 | <?php
class Aplazame_Aplazame_Block_Payment_Form extends Mage_Payment_Block_Form
{
protected function _construct()
{
parent::_construct();
$this->setMethodLabel();
$this->setTemplate('aplazame/payment/form.phtml');
}
private function setMethodLabel()
{
$this->setMethodTitle("");
$html = 'Financialo con Aplazame';
$this->setMethodLabelAfterHtml($html);
}
public function getTotal()
{
return $this->getMethod()->getCheckout()->getQuote()->getGrandTotal();
}
/**
* Devuelve el country ID en formato ISO 2 caracteres
* para comunicarlo a aplazame y que pueda tomar decisiones en base al país de facturación.
* @return string
*/
public function getCountry()
{
$quote = Mage::getModel('checkout/cart')->getQuote();
$countryId = $quote->getBillingAddress()->getCountryId();
return $countryId;
}
}
| <?php
class Aplazame_Aplazame_Block_Payment_Form extends Mage_Payment_Block_Form
{
protected function _construct()
{
parent::_construct();
$this->setMethodLabel();
$this->setTemplate('aplazame/payment/form.phtml');
}
private function setMethodLabel()
{
$this->setMethodTitle("");
$logoSrc = 'https://aplazame.com/static/img/buttons/' . Mage::getStoreConfig('payment/aplazame/button_img') . '.png';
$html = '<img src="' . $logoSrc . '" height="27" class="v-middle" /> ';
$html.= 'Financia tu compra con Aplazame';
$this->setMethodLabelAfterHtml($html);
}
public function getTotal()
{
return $this->getMethod()->getCheckout()->getQuote()->getGrandTotal();
}
/**
* Devuelve el country ID en formato ISO 2 caracteres
* para comunicarlo a aplazame y que pueda tomar decisiones en base al país de facturación.
* @return string
*/
public function getCountry()
{
$quote = Mage::getModel('checkout/cart')->getQuote();
$countryId = $quote->getBillingAddress()->getCountryId();
return $countryId;
}
}
|
Make HiliteMeService public for CDI | package bean;
import java.net.URI;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import org.eclipse.microprofile.rest.client.RestClientBuilder;
import bean.MarkdownBean.SyntaxHighlighter;
import lombok.SneakyThrows;
@ApplicationScoped
public class HiliteMeHighlighter implements SyntaxHighlighter {
public interface HiliteMeService {
@POST
String highlight(
@FormParam("code") String code,
@FormParam("lexer") String lexer,
@FormParam("linenos") boolean lineNos,
@FormParam("style") String style
);
}
@Override
@SneakyThrows
public String highlight(String text, String language) {
// TODO use embedded Python interpreter?
URI apiUri = new URI("http://hilite.me/api"); //$NON-NLS-1$
HiliteMeService hiliteMe = RestClientBuilder.newBuilder()
.baseUri(apiUri)
.build(HiliteMeService.class);
return hiliteMe.highlight(text, language, true, "colorful"); //$NON-NLS-1$
}
}
| package bean;
import java.net.URI;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import org.eclipse.microprofile.rest.client.RestClientBuilder;
import bean.MarkdownBean.SyntaxHighlighter;
import lombok.SneakyThrows;
@ApplicationScoped
public class HiliteMeHighlighter implements SyntaxHighlighter {
interface HiliteMeService {
@POST
String highlight(
@FormParam("code") String code,
@FormParam("lexer") String lexer,
@FormParam("linenos") boolean lineNos,
@FormParam("style") String style
);
}
@Override
@SneakyThrows
public String highlight(String text, String language) {
// TODO use embedded Python interpreter?
URI apiUri = new URI("http://hilite.me/api"); //$NON-NLS-1$
HiliteMeService hiliteMe = RestClientBuilder.newBuilder()
.baseUri(apiUri)
.build(HiliteMeService.class);
return hiliteMe.highlight(text, language, true, "colorful"); //$NON-NLS-1$
}
}
|
Move context function creation to own function | import { Meteor } from 'meteor/meteor';
import { createGraphQLMethod } from './createGraphQLMethod';
import { createGraphQLPublication } from './createGraphQLPublication';
import {
DEFAULT_METHOD,
DEFAULT_CREATE_CONTEXT,
} from '../common/defaults';
export const DDP_APOLLO_SCHEMA_REQUIRED = 'DDP_APOLLO_SCHEMA_REQUIRED';
function contextToFunction(context) {
switch (typeof context) {
case 'object':
return defaultContext => ({ ...defaultContext, ...context });
case 'function':
return context;
default:
return DEFAULT_CREATE_CONTEXT;
}
}
export function setup({
schema,
method = DEFAULT_METHOD,
publication,
context,
} = {}) {
if (!schema) {
throw new Error(DDP_APOLLO_SCHEMA_REQUIRED);
}
const createContext = contextToFunction(context);
Meteor.methods({
[method]: createGraphQLMethod(schema, { createContext }),
});
createGraphQLPublication({
schema,
createContext,
publication,
});
}
| import { Meteor } from 'meteor/meteor';
import { createGraphQLMethod } from './createGraphQLMethod';
import { createGraphQLPublication } from './createGraphQLPublication';
import {
DEFAULT_METHOD,
DEFAULT_CREATE_CONTEXT,
} from '../common/defaults';
export const DDP_APOLLO_SCHEMA_REQUIRED = 'DDP_APOLLO_SCHEMA_REQUIRED';
export function setup({
schema,
method = DEFAULT_METHOD,
publication,
context,
} = {}) {
if (!schema) {
throw new Error(DDP_APOLLO_SCHEMA_REQUIRED);
}
let createContext;
switch (typeof context) {
case 'object':
createContext = defaultContext => ({ ...defaultContext, ...context });
break;
case 'function':
createContext = context;
break;
default:
createContext = DEFAULT_CREATE_CONTEXT;
}
Meteor.methods({
[method]: createGraphQLMethod(schema, { createContext }),
});
createGraphQLPublication({
schema,
createContext,
publication,
});
}
|
Set the port of application from process.env.PORT, which will be set by Heroku. | const express = require('express');
const path = require('path');
const chalk = require('chalk');
const initServer = require('./initServer');
const app = express();
const DOCS_PATH = '../../docs/';
const PORT = process.env.PORT || 8082;
const IP_ADRESS = 'localhost';
app.set('port', PORT);
app.set('ipAdress', IP_ADRESS);
app.use(express.static(path.join(__dirname, DOCS_PATH)));
initServer(app);
app.get('/', (req, res) => res.sendFile(path.join(__dirname, DOCS_PATH, 'index.html')));
/* eslint-disable no-console */
app.listen(
PORT,
IP_ADRESS,
() => console.log(`
=====================================================
-> Server (${chalk.bgBlue('SPA')}) 🏃 (running) on ${chalk.green(IP_ADRESS)}:${chalk.green(PORT)}
=====================================================
`),
);
/* eslint-enable no-console */
| const express = require('express');
const path = require('path');
const chalk = require('chalk');
const initServer = require('./initServer');
const app = express();
const DOCS_PATH = '../../docs/';
const PORT = 8082;
const IP_ADRESS = 'localhost';
app.set('port', PORT);
app.set('ipAdress', IP_ADRESS);
app.use(express.static(path.join(__dirname, DOCS_PATH)));
initServer(app);
app.get('/', (req, res) => res.sendFile(path.join(__dirname, DOCS_PATH, 'index.html')));
/* eslint-disable no-console */
app.listen(
PORT,
IP_ADRESS,
() => console.log(`
=====================================================
-> Server (${chalk.bgBlue('SPA')}) 🏃 (running) on ${chalk.green(IP_ADRESS)}:${chalk.green(PORT)}
=====================================================
`),
);
/* eslint-enable no-console */
|
Remove reference to 'architecture' symbol style
These symbols aren't included in the repository,
as I'm unsure of their copyright status. | define([
'symbols/base',
'symbols/dnd'
],
function(baseScaled, dndScaled, architectureScaled) {
var scaledSymbols = function(scale) {
var options = {
scale : scale,
doorOffset : 8
};
options.doorThickness = options.doorOffset;
options.doorWidth = options.scale - (options.doorOffset * 2);
options.halfThickness = options.doorThickness / 2;
var dnd = dndScaled(options);
symbols = {
door : dnd.door,
arch : dnd.arch,
secret : dnd.secret,
open : dnd.open,
porticullis : dnd.porticullis
};
return symbols;
};
return scaledSymbols;
}); | define([
'symbols/base',
'symbols/dnd',
'symbols/architecture'
],
function(baseScaled, dndScaled, architectureScaled) {
var scaledSymbols = function(scale) {
var options = {
scale : scale,
doorOffset : 8
};
options.doorThickness = options.doorOffset;
options.doorWidth = options.scale - (options.doorOffset * 2);
options.halfThickness = options.doorThickness / 2;
var dnd = dndScaled(options);
var architecture = architectureScaled(options);
symbols = {
door : dnd.door,
arch : dnd.arch,
secret : dnd.secret,
open : dnd.open,
porticullis : dnd.porticullis
};
return symbols;
};
return scaledSymbols;
}); |
Fix an error on login | angular
.module('app')
.controller('AuthLoginController', ['$scope', 'AuthService', '$state',
function ($scope, AuthService, $state) {
$scope.login = function () {
AuthService.login($scope.user.username, $scope.user.email, $scope.user.password)
.then(function () {
$state.go('area-clienti');
});
};
}])
.controller('AuthLogoutController', ['$scope', 'AuthService', '$state',
function ($scope, AuthService, $state) {
AuthService.logout()
.then(function () {
$state.go('home');
});
}])
.controller('SignUpController', ['$scope', 'AuthService', '$state',
function ($scope, AuthService, $state) {
$scope.register = function () {
AuthService.register($scope.user.username, $scope.user.email, $scope.user.password)
.then(function () {
$state.transitionTo('sign-up-success');
});
};
}]);
| angular
.module('app')
.controller('AuthLoginController', ['$scope', 'AuthService', '$state',
function ($scope, AuthService, $state) {
$scope.login = function () {
AuthService.login($scope.user.username, $scope.user.email, $scope.user.password)
.then(function () {
$state.go('area-clienti-inizio');
});
};
}])
.controller('AuthLogoutController', ['$scope', 'AuthService', '$state',
function ($scope, AuthService, $state) {
AuthService.logout()
.then(function () {
$state.go('home');
});
}])
.controller('SignUpController', ['$scope', 'AuthService', '$state',
function ($scope, AuthService, $state) {
$scope.register = function () {
AuthService.register($scope.user.username, $scope.user.email, $scope.user.password)
.then(function () {
$state.transitionTo('sign-up-success');
});
};
}]);
|
Fix header menu, by setting test plans as active | define([
'jquery',
'underscore',
'backbone',
'models/testplan/TestPlanModel',
'collections/testplan/TestPlansCollection',
'views/testplans/TestPlansListView',
'text!templates/testplans/testplansTemplate.html'
], function($, _, Backbone, TestPlanModel, TestPlansCollection, TestPlansListView, testplansTemplate) {
var ProjectsView = Backbone.View.extend({
el: $("#page"),
initialize: function(options) {
this.page = 1;
},
setPage: function(page) {
this.page = page;
},
render: function() {
$('.item').removeClass('active');
$('.item a[href="#/testplans"]').parent().addClass('active');
this.$el.html(testplansTemplate);
var testPlansCollection = new TestPlansCollection();
testPlansCollection.setPage(this.page);
var projectsListView = new TestPlansListView({
collection: testPlansCollection
});
// FIXME: garbage collect this subview
}
});
return ProjectsView;
}); | define([
'jquery',
'underscore',
'backbone',
'models/testplan/TestPlanModel',
'collections/testplan/TestPlansCollection',
'views/testplans/TestPlansListView',
'text!templates/testplans/testplansTemplate.html'
], function($, _, Backbone, TestPlanModel, TestPlansCollection, TestPlansListView, testplansTemplate) {
var ProjectsView = Backbone.View.extend({
el: $("#page"),
initialize: function(options) {
this.page = 1;
},
setPage: function(page) {
this.page = page;
},
render: function() {
$('.item').removeClass('active');
$('.item a[href="#/projects"]').parent().addClass('active');
this.$el.html(testplansTemplate);
var testPlansCollection = new TestPlansCollection();
testPlansCollection.setPage(this.page);
var projectsListView = new TestPlansListView({
collection: testPlansCollection
});
// FIXME: garbage collect this subview
}
});
return ProjectsView;
}); |
Fix a bug in the region aggregation query.
There is no full_name column for regions; it is just name. |
## this should show in red if the COUNT is less than the total
## number of regions that exist for that relationshiop
show_region_aggregation = '''
SELECT
i.name
, SUM(d.value) as value
, r.name
FROM region_relationship rr
INNER JOIN datapoint d
ON rr.region_1_id = d.region_id
INNER JOIN indicator i
ON d.indicator_id = i.id
INNER JOIN region r
ON rr.region_0_id = r.id
GROUP BY r.name, i.name,i.id ,d.campaign_id
'''
|
## this should show in red if the COUNT is less than the total
## number of regions that exist for that relationshiop
show_region_aggregation = '''
SELECT
i.name
, SUM(d.value) as value
, r.full_name
FROM region_relationship rr
INNER JOIN datapoint d
ON rr.region_1_id = d.region_id
INNER JOIN indicator i
ON d.indicator_id = i.id
INNER JOIN region r
ON rr.region_0_id = r.id
GROUP BY r.full_name, i.name,i.id ,d.campaign_id
'''
|
Add render for seven hour. | import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons'
const SevenHour = ({hourlyForecast}) => {
if(!hourlyForecast){
return(
<div></div>
)
}
const icons = new WeatherIcons();
const sevenHourForecast = hourlyForecast.slice(0, 8)
return(
<section className="seven-hour-container">
{sevenHourForecast.map((hour, i) => {
return(
<div key={i} className="hourly-box">
<h2 className="hourly-forecast">{hour.FCTTIME.civil}</h2>
<h6 className={icons[hour.icon]}></h6>
<h2 className="hourly-forecast temp">{hour.temp.english}°F</h2>
</div>
);
})}
</section>
)
}
export default SevenHour;
| import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons'
const SevenHour = ({hourlyForecast}) => {
if(!hourlyForecast){
return(
<div></div>
)
}
const icons = new WeatherIcons();
const sevenHourForecast = hourlyForecast.slice(0, 7)
return(
<article>
{sevenHourForecast.map((hour, i) => {
return(
<div key={i}>
<h4 className="hourly-forecast">{hour.temp.english}°F</h4>
<h4 className="hourly-forecast">{hour.FCTTIME.civil}</h4>
<div className={icons[hour.icon]}></div>
</div>
);
})}
</article>
)
}
export default SevenHour;
|
Add --enable-logging that enables logging | #!/usr/bin/env node
var express = require('express'),
droonga = require('./index'),
http = require('http'),
options = require('commander');
var version = require('./package.json').version;
options
.version(version)
.option('--port <port>', 'Port number', Number, 13000)
.option('--droonga-engine-port <port>', 'Port number of Droonga engine',
Number, 24224)
.option('--enable-logging', 'Enable logging to the standard output')
.parse(process.argv);
var application = express();
var server = http.createServer(application);
var MemoryStore = express.session.MemoryStore;
var sessionStore = new MemoryStore();
application.configure(function() {
if (options.enableLogging) {
application.use(express.logger());
}
application.use(express.cookieParser('secret key'));
application.use(express.session({
secret: 'secret key',
store: sessionStore
}));
});
application.droonga({
prefix: '',
defaultDataset: 'Droonga',
server: server,
sessionStore: sessionStore, // this is required to share session information by socket.io and HTTP APIs
port: options.droongaEnginePort,
plugins: [
droonga.API_REST,
droonga.API_SOCKET_IO,
droonga.API_GROONGA,
droonga.API_DROONGA
]
});
server.listen(options.port);
| #!/usr/bin/env node
var express = require('express'),
droonga = require('./index'),
http = require('http'),
options = require('commander');
var version = require('./package.json').version;
options
.version(version)
.option('--port <port>', 'Port number', Number, 13000)
.option('--droonga-engine-port <port>', 'Port number of Droonga engine',
Number, 24224)
.parse(process.argv);
var application = express();
var server = http.createServer(application);
var MemoryStore = express.session.MemoryStore;
var sessionStore = new MemoryStore();
application.configure(function() {
application.use(express.cookieParser('secret key'));
application.use(express.session({
secret: 'secret key',
store: sessionStore
}));
});
application.droonga({
prefix: '',
defaultDataset: 'Droonga',
server: server,
sessionStore: sessionStore, // this is required to share session information by socket.io and HTTP APIs
port: options.droongaEnginePort,
plugins: [
droonga.API_REST,
droonga.API_SOCKET_IO,
droonga.API_GROONGA,
droonga.API_DROONGA
]
});
server.listen(options.port);
|
Add constants for Execution Statuses IDs | <?php
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn
*
* 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.
*/
namespace Nestor\Entities;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class ExecutionStatuses extends Model implements Transformable
{
use TransformableTrait;
protected $fillable = [];
const EXECUTION_STATUS_NOT_RUN = 1;
const EXECUTION_STATUS_PASSED = 2;
const EXECUTION_STATUS_FAILED = 3;
const EXECUTION_STATUS_BLOCKED = 4;
}
| <?php
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn
*
* 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.
*/
namespace Nestor\Entities;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class ExecutionStatuses extends Model implements Transformable
{
use TransformableTrait;
protected $fillable = [];
}
|
Fix `LinkPager` css class duplicate | <?php
namespace hipanel\widgets;
use Yii;
use yii\helpers\Html;
use yii\widgets\LinkPager;
class PagerHook extends LinkPager implements HookInterface
{
use HookTrait;
public string $tag = 'div';
public string $content;
public $options = [];
public function init()
{
$this->registerJsHook('pager');
}
public function run()
{
return Html::tag($this->tag, $this->content ?? $this->getLoader(), array_merge(['id' => $this->getId()], $this->options));
}
private function getLoader(): string
{
return Html::tag('span', null, ['class' => 'fa fa-spinner fa-pulse', 'style' => 'margin-right: .7rem;']) . Yii::t('hipanel', 'loading pager...');
}
} | <?php
namespace hipanel\widgets;
use Yii;
use yii\helpers\Html;
use yii\widgets\LinkPager;
class PagerHook extends LinkPager implements HookInterface
{
use HookTrait;
public string $tag = 'div';
public string $content;
public function init()
{
$this->registerJsHook('pager');
}
public function run()
{
return Html::tag($this->tag, $this->content ?? $this->getLoader(), array_merge(['id' => $this->getId()], $this->options));
}
private function getLoader(): string
{
return Html::tag('span', null, ['class' => 'fa fa-spinner fa-pulse', 'style' => 'margin-right: .7rem;']) . Yii::t('hipanel', 'loading pager...');
}
} |
Fix tests for in promises | const fs = require('fs');
const { learn, getClassifier, } = require('../src/learn');
const intentsFile = require('../src/intents.json').intents;
const natural = require('natural');
const intents = {
hello: {
tag: 'hello',
patterns: [
'hello!',
],
responses: [
'hi!',
],
},
};
const classifierFile = __dirname + '/classifier.json';
test('learn: creates a classifier based on an intents object', () => {
const classifier = learn(intents, classifierFile);
expect(classifier).toBeInstanceOf(natural.BayesClassifier);
});
test('learn: it saves the classifier into a json file after learning', () => {
natural.BayesClassifier.load(classifierFile, null, (err, classifier) => {
expect(classifier).toBeInstanceOf(natural.BayesClassifier);
expect(err).toEqual(null);
});
});
test('getClassifier: loads classifier from a file if it exists', (d) => {
getClassifier(classifierFile)
.then(c => {
expect(c).toBeInstanceOf(natural.BayesClassifier);
d();
});
});
test('getClassifier: creates a new classifier from intents.json file if file doesn\'t exists', (d) => {
getClassifier(__dirname + '/notafile.json')
.then(c => {
expect(c).toEqual(learn(intentsFile, __dirname + '/notafile.json'));
d();
});
});
afterAll(() => {
fs.unlinkSync(classifierFile);
fs.unlinkSync(__dirname + '/notafile.json');
});
| const fs = require('fs');
const { learn, getClassifier, } = require('../src/learn');
const intentsFile = require('../src/intents.json').intents;
const natural = require('natural');
const intents = {
hello: {
tag: 'hello',
patterns: [
'hello!',
],
responses: [
'hi!',
],
},
};
const classifierFile = __dirname + '/classifier.json';
test('learn: creates a classifier based on an intents object', () => {
const classifier = learn(intents, classifierFile);
expect(classifier).toBeInstanceOf(natural.BayesClassifier);
});
test('learn: it saves the classifier into a json file after learning', () => {
natural.BayesClassifier.load(classifierFile, null, (err, classifier) => {
expect(classifier).toBeInstanceOf(natural.BayesClassifier);
expect(err).toEqual(null);
});
expect(true);
});
test('getClassifier: loads classifier from a file if it exists', () => {
getClassifier(classifierFile)
.then(c => expect(c).toBeInstanceOf(natural.BayesClassifier));
});
test('getClassifier: creates a new classifier from intents.json file if file doesn\'t exists', () => {
getClassifier(__dirname + '/notafile.json')
.then(c => {
expect(c).toEqual(learn(intentsFile));
});
});
afterAll(() => {
fs.unlinkSync(classifierFile);
});
|
Debug Google Cloud Run support | #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax: entrypoint.py <command>
#
# Author: Chris Williams <diodesign@tuta.io>
#
import os
import sys
global command_result
from flask import Flask
if __name__ == "__main__":
if not os.environ.get('K_SERVICE'):
print('Running locally')
stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:])))
output = stream.read()
output
else:
print('Running HTTP service {} {} {} for Google Cloud', os.environ.get('K_SERVICE'), os.environ.get('K_REVISION'), os.environ.get('K_CONFIGURATION'))
app = Flask(__name__)
@app.route('/')
def ContainerService():
return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
| #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax: entrypoint.py <command>
#
# Author: Chris Williams <diodesign@tuta.io>
#
import os
import sys
global command_result
from flask import Flask
if __name__ == "__main__":
print('{} {} {}', os.environ.get('K_SERVICE'), os.environ.get('K_REVISION'), os.environ.get('K_CONFIGURATION'))
if (os.environ.get('K_SERVICE')) != '':
print('Running HTTP service for Google Cloud')
# app = Flask(__name__)
# @app.route('/')
# def ContainerService():
# return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
# app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
else:
print('Running locally')
# stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:])))
# output = stream.read()
# output
|
Fix accumulateData for production series where latest year is missing a value | import {
filter,
fromPairs,
defaultTo,
head,
indexBy,
is,
keys,
last,
map,
prop,
range,
} from 'ramda'
import { productionSeries } from './csv'
export function accumulateData (data, column, series, extraYears = 0) {
let currentYear
let total = 0
const production = productionSeries(data.series)
const dataYears = filter((row) => is(Number, row[production]), data.data)
const first = parseInt(head(keys(dataYears)))
const latest = parseInt(last(keys(dataYears)))
const years = range(first, latest + extraYears)
const latestData = data.data[latest][column]
console.debug('Range:', first, latest, latestData, column, total, data)
// TODO Write separate function that uses world production data until the estimation continues!
return indexBy(prop('Year'), map((year) => {
if (year <= latest) {
currentYear = defaultTo(0, parseFloat(data.data[year][column]))
} else {
currentYear = latestData
}
total += currentYear
return fromPairs([
['Year', year],
[series, total],
])
}, years))
}
| import {
fromPairs,
defaultTo,
head,
indexBy,
keys,
last,
map,
prop,
range,
} from 'ramda'
export function accumulateData (data, column, series, extraYears = 0) {
let currentYear
let total = 0
const dataYears = keys(data.data)
const first = parseInt(head(dataYears))
const latest = parseInt(last(dataYears))
const years = range(first, latest + extraYears)
const latestData = data.data[latest][column]
console.debug('Range:', first, latest, latestData, column, total, data)
// TODO Write separate function that uses world production data until the estimation continues!
return indexBy(prop('Year'), map((year) => {
if (year <= latest) {
currentYear = defaultTo(0, parseFloat(data.data[year][column]))
} else {
currentYear = latestData
}
total += currentYear
return fromPairs([
['Year', year],
[series, total],
])
}, years))
}
|
Use injected sql from results | """"Test adapter specific config options."""
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return "adapter-specific-models"
@property
def profile_config(self):
return self.bigquery_profile()
@property
def project_config(self):
return yaml.safe_load(textwrap.dedent('''\
config-version: 2
models:
test:
materialized: table
expiring_table:
time_to_expiration: 4
'''))
@use_profile('bigquery')
def test_bigquery_time_to_expiration(self):
results = self.run_dbt()
self.assertIn(
'expiration_timestamp: TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL '
'4 hour)', results[0].node.injected_sql)
| """"Test adapter specific config options."""
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return "adapter-specific-models"
@property
def profile_config(self):
return self.bigquery_profile()
@property
def project_config(self):
return yaml.safe_load(textwrap.dedent('''\
config-version: 2
models:
test:
materialized: table
expiring_table:
time_to_expiration: 4
'''))
@use_profile('bigquery')
def test_bigquery_time_to_expiration(self):
_, stdout = self.run_dbt_and_capture()
self.assertIn(
'expiration_timestamp: TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL '
'4 hour)', stdout)
|
FIX Use correct mock assertion methods for PHPUnit 3.7 | <?php
namespace BringYourOwnIdeas\Maintenance\Tests\Tasks;
use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use SapphireTest;
use BringYourOwnIdeas\Maintenance\Tasks\UpdatePackageInfo;
class UpdatePackageInfoTest extends SapphireTest
{
public function testGetPackageInfo()
{
$loader = $this->getMockBuilder(ComposerLoader::class)->setMethods(['getLock'])->getMock();
$loader->expects($this->any())->method('getLock')->will($this->returnValue(json_decode(<<<LOCK
{
"packages": [
{
"name": "fake/package",
"description": "A faux package from a mocked composer.lock for testing purposes",
"version": "1.0.0"
}
]
}
LOCK
)));
$processor = new UpdatePackageInfo;
$output = $processor->getPackageInfo($loader->getLock()->packages);
$this->assertInternalType('array', $output);
$this->assertCount(1, $output);
$this->assertSame([
"Name" => "fake/package",
"Description" => "A faux package from a mocked composer.lock for testing purposes",
"Version" => "1.0.0"
], $output[0]);
}
}
| <?php
namespace BringYourOwnIdeas\Maintenance\Tests\Tasks;
use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use SapphireTest;
use BringYourOwnIdeas\Maintenance\Tasks\UpdatePackageInfo;
class UpdatePackageInfoTest extends SapphireTest
{
public function testGetPackageInfo()
{
$loader = $this->getMockBuilder(ComposerLoader::class)->setMethods(['getLock'])->getMock();
$loader->method('getLock')->willReturn(json_decode(<<<LOCK
{
"packages": [
{
"name": "fake/package",
"description": "A faux package from a mocked composer.lock for testing purposes",
"version": "1.0.0"
}
]
}
LOCK
));
$processor = new UpdatePackageInfo;
$output = $processor->getPackageInfo($loader->getLock()->packages);
$this->assertInternalType('array', $output);
$this->assertCount(1, $output);
$this->assertSame([
"Name" => "fake/package",
"Description" => "A faux package from a mocked composer.lock for testing purposes",
"Version" => "1.0.0"
], $output[0]);
}
}
|
Fix test bug (merged from r1484180).
git-svn-id: 13f9c63152c129021c7e766f4ef575faaaa595a2@1484183 13f79535-47bb-0310-9956-ffa450edef68 | package org.apache.lucene.util;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class TestTimSorter extends BaseSortTestCase {
public TestTimSorter() {
super(true);
}
@Override
public Sorter newSorter(Entry[] arr) {
return new ArrayTimSorter<Entry>(arr, ArrayUtil.<Entry>naturalComparator(), _TestUtil.nextInt(random(), 0, arr.length));
}
}
| package org.apache.lucene.util;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class TestTimSorter extends BaseSortTestCase {
public TestTimSorter() {
super(true);
}
@Override
public Sorter newSorter(Entry[] arr) {
return new ArrayTimSorter<Entry>(arr, ArrayUtil.<Entry>naturalComparator(), random().nextInt(arr.length));
}
}
|
3421: Add a timeout value to the AJAX request
Authors: 72d0743fa974f1b94d0389ab43a06cc7eebf90ac@davbo | (function () {
"use strict";
var root = this,
$ = root.jQuery;
if(typeof root.GOVUK === 'undefined') { root.GOVUK = {}; }
root.GOVUK.signin = {
init: function () {
},
attach: function () {
var $selectIdpForm = $('.select-idp-form');
$selectIdpForm.on('submit', function (e) {
var entityId;
e.preventDefault();
entityId = $selectIdpForm.find('button').attr('name');
$.ajax({
type: "PUT",
url: '/api/select-idp',
contentType: "application/json",
data: { entityId: entityId },
timeout: 5000
}).done(function(response) {
var $samlForm = $('#post-to-idp');
$samlForm.prop('action', response.location);
$samlForm.find('input[name=SAMLRequest]').val(response.samlRequest);
$samlForm.submit();
}).fail(function() {
$selectIdpForm.off('submit').submit();
});
return false;
});
}
};
}).call(this);
| (function () {
"use strict";
var root = this,
$ = root.jQuery;
if(typeof root.GOVUK === 'undefined') { root.GOVUK = {}; }
root.GOVUK.signin = {
init: function () {
},
attach: function () {
var $selectIdpForm = $('.select-idp-form');
$selectIdpForm.on('submit', function (e) {
var entityId;
e.preventDefault();
entityId = $selectIdpForm.find('button').attr('name');
$.ajax({
type: "PUT",
url: '/api/select-idp',
contentType: "application/json",
data: { entityId: entityId }
}).done(function(response) {
var $samlForm = $('#post-to-idp');
$samlForm.prop('action', response.location);
$samlForm.find('input[name=SAMLRequest]').val(response.samlRequest);
$samlForm.submit();
}).fail(function() {
$selectIdpForm.off('submit').submit();
});
return false;
});
}
};
}).call(this);
|
Add a method to destruct the classes | <?php
/**
*
*/
class Script
{
protected $helpMessage = '';
protected $matches;
protected $message;
protected $waConnection;
function __construct($message, $matches, $waConnection)
{
$this->matches = $matches;
$this->message = $message;
$this->waConnection = $waConnection;
}
function __destruct()
{
}
public function help()
{
return $helpMessage;
}
public function run()
{
}
public function send($from, $content, $type = 'text')
{
switch ($type) {
case 'text':
return $this->waConnection->sendMessage($from, $content);
break;
case 'image':
return $this->waConnection->sendMessageImage($from, $content);
break;
case 'audio':
return $this->waConnection->sendMessageAudio($from, $content);
break;
case 'video':
return $this->waConnection->sendMessageVideo($from, $content);
break;
case 'location':
return $this->waConnection->sendMessageLocation($from, $content);
break;
}
}
}
?>
| <?php
/**
*
*/
class Script
{
protected $helpMessage = '';
protected $matches;
protected $message;
protected $waConnection;
function __construct($message, $matches, $waConnection)
{
$this->matches = $matches;
$this->message = $message;
$this->waConnection = $waConnection;
}
public function help()
{
return $helpMessage;
}
public function run()
{
}
public function send($from, $content, $type = 'text')
{
switch ($type) {
case 'text':
return $this->waConnection->sendMessage($from, $content);
break;
case 'image':
return $this->waConnection->sendMessageImage($from, $content);
break;
case 'audio':
return $this->waConnection->sendMessageAudio($from, $content);
break;
case 'video':
return $this->waConnection->sendMessageVideo($from, $content);
break;
case 'location':
return $this->waConnection->sendMessageLocation($from, $content);
break;
}
}
}
?>
|
Make indentation of template files more consistent | <?php
/**
* Render the inset with fork button and parent link for the
* public view of a post.
*
* Required parameters:
* $post_id the ID of the post for which the inset will be
* rendered
* $image_url the URL of the fork icon image file
*/
$fork_url = add_query_arg(array(
'action' => 'persistent_fork',
'post' => $post_id,
'nonce' => wp_create_nonce('persistent_forking')
), home_url());
$parent_id = get_post_meta($post_id, '_persistfork-parent', true);
?>
<a href="<?= $fork_url ?>" title="Fork this post">
<img
src="<?= $image_url ?>"
title="Fork"
alt="Fork"
style="display: inline;"
/>
Fork
</a>
<?php if ($parent_id): ?>
| Forked from:
<a href="<?= get_permalink($parent_id) ?>">
<?= get_post($parent_id)->post_title ?>
</a>
<?php endif ?>
| <?php
/**
* Render the inset with fork button and parent link for the
* public view of a post.
*
* Required parameters:
* $post_id the ID of the post for which the inset will be
* rendered
* $image_url the URL of the fork icon image file
*/
$fork_url = add_query_arg(array(
'action' => 'persistent_fork',
'post' => $post_id,
'nonce' => wp_create_nonce('persistent_forking')
), home_url());
$parent_id = get_post_meta($post_id, '_persistfork-parent', true);
?>
<a href="<?= $fork_url ?>" title="Fork this post">
<img
src="<?= $image_url ?>"
title="Fork"
alt="Fork"
style="display: inline;"
/>
Fork
</a>
<?php if ($parent_id): ?>
| Forked from:
<a href="<?= get_permalink($parent_id) ?>">
<?= get_post($parent_id)->post_title ?>
</a>
<?php endif ?>
|
Remove key from toList() method in LocalitiesCollection class | <?php
namespace Galahad\LaravelAddressing\Collection;
use Galahad\LaravelAddressing\Entity\Locality;
/**
* Class LocalityCollection
*
* @package Galahad\LaravelAddressing
* @author Junior Grossi <juniorgro@gmail.com>
*/
class LocalityCollection extends Collection implements CollectionInterface
{
/**
* Return all the items ready for a <select> HTML element
*
* @return mixed
*/
public function toList()
{
$values = [];
/** @var Locality $locality */
foreach ($this as $locality) {
$values[] = $locality->getName();
}
return $values;
}
/**
* Override the getByKey method to return the correct instance
*
* @param int $key
* @return Locality
*/
public function getByKey($key)
{
return parent::getByKey($key);
}
/**
* Get a locality by its name
*
* @param $name
* @return Locality
*/
public function getByName($name)
{
if ($this->count()) {
$locality = $this->getByKey(0);
return $locality->getByName($name);
}
}
} | <?php
namespace Galahad\LaravelAddressing\Collection;
use Galahad\LaravelAddressing\Entity\Locality;
/**
* Class LocalityCollection
*
* @package Galahad\LaravelAddressing
* @author Junior Grossi <juniorgro@gmail.com>
*/
class LocalityCollection extends Collection implements CollectionInterface
{
/**
* Return all the items ready for a <select> HTML element
*
* @return mixed
*/
public function toList()
{
$values = [];
/** @var Locality $locality */
foreach ($this as $locality) {
$values[$locality->getName()] = $locality->getName();
}
return $values;
}
/**
* Override the getByKey method to return the correct instance
*
* @param int $key
* @return Locality
*/
public function getByKey($key)
{
return parent::getByKey($key);
}
/**
* Get a locality by its name
*
* @param $name
* @return Locality
*/
public function getByName($name)
{
if ($this->count()) {
$locality = $this->getByKey(0);
return $locality->getByName($name);
}
}
} |
Remove TLD check, allow for www | import socket
def valid_hostname(hostname: str):
"""
:param hostname: The hostname requested in the scan
:return: Hostname if it's valid, otherwise None
"""
# First, let's try to see if it's an IPv4 address
try:
socket.inet_aton(hostname) # inet_aton() will throw an exception if hostname is not a valid IP address
return None # If we get this far, it's an IP address and therefore not a valid fqdn
except:
pass
# And IPv6
try:
socket.inet_pton(socket.AF_INET6, hostname) # same as inet_aton(), but for IPv6
return None
except:
pass
# Then, try to do a lookup on the hostname; this should return at least one entry and should be the first time
# that the validator is making a network connection -- the same that requests would make.
try:
hostname_ips = socket.getaddrinfo(hostname, 443)
if len(hostname_ips) < 1:
return None
except:
return None
# If we've made it this far, then everything is good to go! Woohoo!
return hostname
| import socket
import tld
def valid_hostname(hostname: str) -> bool:
"""
:param hostname: The hostname requested in the scan
:return: True if it's a valid hostname (fqdn in DNS that's not an IP address), False otherwise
"""
# First, let's try to see if it's an IPv4 address
try:
socket.inet_aton(hostname) # inet_aton() will throw an exception if hostname is not a valid IP address
return False # If we get this far, it's an IP address and therefore not a valid fqdn
except:
pass
# And IPv6
try:
socket.inet_pton(socket.AF_INET6, hostname) # same as inet_aton(), but for IPv6
return False
except:
pass
# Then, let's see if it's a TLD; this includes things fuel.aero or co.uk that look like fqdns but aren't
if hostname in tld.get_tld_names():
return False
# Then, try to do a lookup on the hostname; this should return at least one entry and should be the first time
# that the validator is making a network connection -- the same that requests would make.
try:
hostname_ips = socket.getaddrinfo(hostname, 443)
if len(hostname_ips) < 1:
return False
except:
return False
# If we've made it this far, then everything is good to go! Woohoo!
return True
|
Use const when it makes sense in markup tests | 'use strict';
let _ = require('lodash');
let bluebird = require('bluebird');
let fs = bluebird.promisifyAll(require('fs'));
let glob = require('glob');
let hljs = require('../../build');
let path = require('path');
let utility = require('../utility');
function testLanguage(language) {
describe(language, function() {
const filePath = utility.buildPath('markup', language, '*.expect.txt'),
filenames = glob.sync(filePath);
_.each(filenames, function(filename) {
const testName = path.basename(filename, '.expect.txt'),
sourceName = filename.replace(/\.expect/, '');
it(`should markup ${testName}`, function(done) {
const sourceFile = fs.readFileAsync(sourceName, 'utf-8'),
expectedFile = fs.readFileAsync(filename, 'utf-8');
bluebird.join(sourceFile, expectedFile, function(source, expected) {
const actual = hljs.highlight(language, source).value;
actual.trim().should.equal(expected.trim());
done();
});
});
});
});
}
describe('hljs.highlight()', function() {
let markupPath = utility.buildPath('markup');
return fs.readdirAsync(markupPath).each(testLanguage);
});
| 'use strict';
let _ = require('lodash');
let bluebird = require('bluebird');
let fs = bluebird.promisifyAll(require('fs'));
let glob = require('glob');
let hljs = require('../../build');
let path = require('path');
let utility = require('../utility');
function testLanguage(language) {
describe(language, function() {
let filePath = utility.buildPath('markup', language, '*.expect.txt'),
filenames = glob.sync(filePath);
_.each(filenames, function(filename) {
let testName = path.basename(filename, '.expect.txt'),
sourceName = filename.replace(/\.expect/, '');
it(`should markup ${testName}`, function(done) {
let sourceFile = fs.readFileAsync(sourceName, 'utf-8'),
expectedFile = fs.readFileAsync(filename, 'utf-8');
bluebird.join(sourceFile, expectedFile, function(source, expected) {
let actual = hljs.highlight(language, source).value;
actual.trim().should.equal(expected.trim());
done();
});
});
});
});
}
describe('hljs.highlight()', function() {
let markupPath = utility.buildPath('markup');
return fs.readdirAsync(markupPath).each(testLanguage);
});
|
Add fpp k/d data to the model. | from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo = models.CharField(max_length=5, null=True)
duo = models.CharField(max_length=5, null=True)
squad = models.CharField(max_length=5, null=True)
solokd = models.CharField(max_length=5, null=True)
duokd = models.CharField(max_length=5, null=True)
squadkd = models.CharField(max_length=5, null=True)
solofppkd = models.CharField(max_length=5, null=True)
duofppkd = models.CharField(max_length=5, null=True)
squadfppkd = models.CharField(max_length=5, null=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.userName | from django.db import models
# Create your models here.
class RatingData(models.Model):
userName = models.CharField(max_length=30)
solofpp = models.CharField(max_length=5, null=True)
duofpp = models.CharField(max_length=5, null=True)
squadfpp = models.CharField(max_length=5, null=True)
solo = models.CharField(max_length=5, null=True)
duo = models.CharField(max_length=5, null=True)
squad = models.CharField(max_length=5, null=True)
solokd = models.CharField(max_length=5, null=True)
duokd = models.CharField(max_length=5, null=True)
squadkd = models.CharField(max_length=5, null=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.userName |
Fix bad indentation that broke the PEP8 ! | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend
This module is an Alignak REST backend
"""
# Application version and manifest
VERSION = (0, 4, 3)
__application__ = u"Alignak_Backend"
__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 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak REST backend"
__releasenotes__ = u"""Alignak REST Backend"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend"
# 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
This module is an Alignak REST backend
"""
# Application version and manifest
VERSION = (0, 4, 3)
__application__ = u"Alignak_Backend"
__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 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak REST backend"
__releasenotes__ = u"""Alignak REST Backend"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
Support a 'use' option to specify further defaults | import defaultKeymap from "./defaultkeymap"
import {Range} from "./selection"
import {Node, Pos} from "../model"
class Option {
constructor(defaultValue, update, updateOnInit) {
this.defaultValue = defaultValue
this.update = update
this.updateOnInit = updateOnInit !== false
}
}
const options = {
__proto__: null,
doc: new Option(new Node("doc", [new Node("paragraph")]), function(pm, value) {
pm.update(value)
}, false),
place: new Option(null),
keymap: new Option(defaultKeymap),
extraKeymap: new Option(Object.create(null)),
historyDepth: new Option(50),
historyEventDelay: new Option(500),
}
export function defineOption(name, defaultValue, update, updateOnInit) {
options[name] = new Option(defaultValue, update, updateOnInit)
}
export function parseOptions(obj) {
let result = Object.create(null)
let given = obj ? [obj].concat(obj.use || []) : []
outer: for (let opt in options) {
for (let i = 0; i < given.length; i++) {
if (Object.prototype.hasOwnProperty.call(given[i], opt)) {
result[opt] = given[i][opt]
continue outer
}
}
result[opt] = options[opt].defaultValue
}
return result
}
export function initOptions(pm) {
for (var opt in options) {
let desc = options[opt]
if (desc.update && desc.updateOnInit)
desc.update(pm, pm.options[opt], null, true)
}
}
| import defaultKeymap from "./defaultkeymap"
import {Range} from "./selection"
import {Node, Pos} from "../model"
class Option {
constructor(defaultValue, update, updateOnInit) {
this.defaultValue = defaultValue
this.update = update
this.updateOnInit = updateOnInit !== false
}
}
const options = {
__proto__: null,
doc: new Option(new Node("doc", [new Node("paragraph")]), function(pm, value) {
pm.update(value)
}, false),
place: new Option(null),
keymap: new Option(defaultKeymap),
extraKeymap: new Option(Object.create(null)),
historyDepth: new Option(50),
historyEventDelay: new Option(500),
}
export function defineOption(name, defaultValue, update, updateOnInit) {
options[name] = new Option(defaultValue, update, updateOnInit)
}
export function parseOptions(obj) {
let result = Object.create(null)
for (let opt in options) {
let inObj = obj && Object.prototype.hasOwnProperty.call(obj, opt)
result[opt] = inObj ? obj[opt] : options[opt].defaultValue
}
return result
}
export function initOptions(pm) {
for (var opt in options) {
let desc = options[opt]
if (desc.update && desc.updateOnInit)
desc.update(pm, pm.options[opt], null, true)
}
}
|
Use our own Monospaced component instead of applying monospace class from ui-typography | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import omit from 'lodash.omit';
import { Monospaced } from '../typography';
import theme from './theme.css';
class Counter extends PureComponent {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
color: PropTypes.oneOf([ 'neutral', 'ruby' ]),
size: PropTypes.oneOf([ 'small', 'medium' ]),
};
static defaultProps = {
color: 'neutral',
size: 'medium',
};
render () {
const {
children,
className,
color,
size,
...others
} = this.props;
const classes = cx(
theme.counter,
theme[color],
theme[size],
{
[theme.circular]: !children,
[theme.rounded]: children,
},
className,
);
const rest = omit(others, [
'color',
'size',
]);
return (
<span className={classes} {...rest} data-teamleader-ui="counter">
<Monospaced>{children}</Monospaced>
</span>
);
}
}
export default Counter;
| import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import omit from 'lodash.omit';
import theme from './theme.css';
class Counter extends PureComponent {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
color: PropTypes.oneOf([ 'neutral', 'ruby' ]),
size: PropTypes.oneOf([ 'small', 'medium' ]),
};
static defaultProps = {
color: 'neutral',
size: 'medium',
};
render () {
const {
children,
className,
color,
size,
...others
} = this.props;
const classes = cx(
theme.counter,
theme.monospaced,
theme[color],
theme[size],
{
[theme.circular]: !children,
[theme.rounded]: children,
},
className,
);
const rest = omit(others, [
'color',
'size',
]);
return (
<span className={classes} {...rest} data-teamleader-ui="counter">
{children}
</span>
);
}
}
export default Counter;
|
Return a short version of a github repo | <?php
namespace Criterion\Helper;
class Github
{
public static function toSSHUrl($url)
{
$url = str_replace(array('https://','.com/'), array('git@','.com:'), $url);
return $url;
}
public static function toHTTPSUrl($url)
{
$url = str_replace(array('git@','.com:'), array('https://','.com/'), $url);
return $url;
}
public static function commitUrl($commit, $repo)
{
$repo = self::toHTTPSUrl($repo);
return $repo . '/commit/' . $commit['hash']['long'];
}
public static function branchUrl($branch, $repo)
{
$repo = self::toHTTPSUrl($repo);
return $repo . '/tree/' . $branch;
}
public static function shortRepo($url)
{
$https_url = self::toHTTPSUrl($url);
return str_replace('https://github.com/', null, $https_url);
}
}
| <?php
namespace Criterion\Helper;
class Github
{
public static function toSSHUrl($url)
{
$url = str_replace(array('https://','.com/'), array('git@','.com:'), $url);
return $url;
}
public static function toHTTPSUrl($url)
{
$url = str_replace(array('git@','.com:'), array('https://','.com/'), $url);
return $url;
}
public static function commitUrl($commit, $repo)
{
$repo = self::toHTTPSUrl($repo);
return $repo . '/commit/' . $commit['hash']['long'];
}
public static function branchUrl($branch, $repo)
{
$repo = self::toHTTPSUrl($repo);
return $repo . '/tree/' . $branch;
}
}
|
Move call to super in tearDown after Robotium finished opened activities | package com.kousenit.helloworld;
import android.test.ActivityInstrumentationTestCase2;
import com.robotium.solo.Solo;
public class MainActivityRobotiumTest
extends ActivityInstrumentationTestCase2<MainActivity> {
private Solo solo;
public MainActivityRobotiumTest() {
super(MainActivity.class);
}
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation(), getActivity());
}
public void testMyActivity() {
solo.assertCurrentActivity("MainActivity", MainActivity.class);
}
public void testSayHello() {
solo.enterText(0, "Dolly");
solo.clickOnButton(getActivity().getString(R.string.hello_button_label));
solo.assertCurrentActivity("WelcomeActivity", WelcomeActivity.class);
solo.searchText("Hello, Dolly!");
}
public void tearDown() throws Exception {
solo.finishOpenedActivities();
super.tearDown();
}
}
| package com.kousenit.helloworld;
import android.test.ActivityInstrumentationTestCase2;
import com.robotium.solo.Solo;
public class MainActivityRobotiumTest
extends ActivityInstrumentationTestCase2<MainActivity> {
private Solo solo;
public MainActivityRobotiumTest() {
super(MainActivity.class);
}
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation(), getActivity());
}
public void testMyActivity() {
solo.assertCurrentActivity("MainActivity", MainActivity.class);
}
public void testSayHello() {
solo.enterText(0, "Dolly");
solo.clickOnButton(getActivity().getString(R.string.hello_button_label));
solo.assertCurrentActivity("WelcomeActivity", WelcomeActivity.class);
solo.searchText("Hello, Dolly!");
}
public void tearDown() throws Exception {
super.tearDown();
solo.finishOpenedActivities();
}
}
|
Throw error if GPU object not passed | let gpu = null;
module.exports = class Texture {
/**
* @desc WebGl Texture implementation in JS
* @constructor Texture
* @param {Object} texture
* @param {Array} size
* @param {Array} dimensions
* @param {Object} webGl
*/
constructor(texture, size, dimensions, webGl) {
this.texture = texture;
this.size = size;
this.dimensions = dimensions;
this.webGl = webGl;
}
/**
* @name toArray
* @function
* @memberOf Texture#
*
* @desc Converts the Texture into a JavaScript Array.
*
* @param {Object} The `gpu` Object
*
*/
toArray(gpu) {
if(!gpu) throw new Error('You need to pass the GPU object for toArray to work.');
const copy = gpu.createKernel(function(x) {
return x[this.thread.z][this.thread.y][this.thread.x];
}).setDimensions(this.dimensions);
return copy(this);
}
/**
* @name delete
* @desc Deletes the Texture.
* @function
* @memberOf Texture#
*
*
*/
delete() {
return this.webGl.deleteTexture(this.texture);
}
}; | let gpu = null;
module.exports = class Texture {
/**
* @desc WebGl Texture implementation in JS
* @constructor Texture
* @param {Object} texture
* @param {Array} size
* @param {Array} dimensions
* @param {Object} webGl
*/
constructor(texture, size, dimensions, webGl) {
this.texture = texture;
this.size = size;
this.dimensions = dimensions;
this.webGl = webGl;
}
/**
* @name toArray
* @function
* @memberOf Texture#
*
* @desc Converts the Texture into a JavaScript Array.
*
* @param {Object} The `gpu` Object
*
*/
toArray(gpu) {
const copy = gpu.createKernel(function(x) {
return x[this.thread.z][this.thread.y][this.thread.x];
}).setDimensions(this.dimensions);
return copy(this);
}
/**
* @name delete
* @desc Deletes the Texture.
* @function
* @memberOf Texture#
*
*
*/
delete() {
return this.webGl.deleteTexture(this.texture);
}
}; |
Change string concat to join() call | const compressor = require('node-minify');
const { readdirSync } = require('fs');
const { basename, join } = require('path');
const resources = (...dir) => join(...[__dirname, 'src', 'resources'].concat(dir));
const Logger = require(resources('js', 'Logger'));
function minifyAssets() {
const cssPath = resources('css');
const cssFiles = readdirSync(cssPath).filter(f => !f.endsWith('.min.css'));
const jsPath = resources('js');
const jsFiles = readdirSync(jsPath).filter(f => !f.endsWith('.min.js'));
jsFiles.splice(0, 1); // Remove eslintrc
cssFiles.forEach(fileName => {
compressor.minify({
compressor: 'clean-css',
input: join(cssPath, fileName),
output: join(cssPath, `${basename(fileName, '.css')}.min.css`),
});
});
Logger.info('CSS minification complete.');
jsFiles.forEach(fileName => {
compressor.minify({
compressor: 'uglify-es',
input: join(jsPath, fileName),
output: join(jsPath, `${basename(fileName, '.js')}.min.js`),
});
});
Logger.info('JS minification complete.');
}
module.exports = minifyAssets; | const compressor = require('node-minify');
const { readdirSync } = require('fs');
const { basename, join } = require('path');
const resources = (...dir) => join(...[__dirname, 'src', 'resources'].concat(dir));
const Logger = require(resources('js', 'Logger'));
function minifyAssets() {
const cssPath = resources('css');
const cssFiles = readdirSync(cssPath).filter(f => !f.endsWith('.min.css'));
const jsPath = resources('js');
const jsFiles = readdirSync(jsPath).filter(f => !f.endsWith('.min.js'));
jsFiles.splice(0, 1); // Remove eslintrc
cssFiles.forEach(fileName => {
compressor.minify({
compressor: 'clean-css',
input: `${cssPath}${fileName}`,
output: `${cssPath}${basename(fileName, '.css')}.min.css`
});
});
Logger.info('CSS minification complete.');
jsFiles.forEach(fileName => {
compressor.minify({
compressor: 'uglify-es',
input: `${jsPath}${fileName}`,
output: `${jsPath}${basename(fileName, '.js')}.min.js`
});
});
Logger.info('JS minification complete.');
}
module.exports = minifyAssets; |
Fix code style in RequiredInterface | <?php
/*
* This file is part of the Active Collab DatabaseStructure project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\DatabaseStructure\Behaviour\ParentInterface;
use ActiveCollab\DatabaseObject\Entity\EntityInterface;
use ActiveCollab\DatabaseStructure\Behaviour\ParentInterface;
use LogicException;
/**
* @property \ActiveCollab\DatabaseObject\PoolInterface $pool
*/
trait RequiredImplementation
{
public function getParent(bool $use_cache = true): EntityInterface
{
if ($id = $this->getParentId()) {
return $this->pool->getById($this->getParentType(), $id, $use_cache);
} else {
return null;
}
}
/**
* @param EntityInterface $value
* @return ParentInterface|$this
*/
public function &setParent(EntityInterface $value): ParentInterface
{
if (!$value->isLoaded()) {
throw new LogicException('Parent needs to be saved to the database.');
}
$this->setParentType(get_class($value));
$this->setParentId($value->getId());
return $this;
}
abstract public function getParentType(): string;
abstract public function &setParentType(string $value);
abstract public function getParentId(): int;
abstract public function &setParentId(int $value);
}
| <?php
/*
* This file is part of the Active Collab DatabaseStructure project.
*
* (c) A51 doo <info@activecollab.com>. All rights reserved.
*/
declare(strict_types=1);
namespace ActiveCollab\DatabaseStructure\Behaviour\ParentInterface;
use ActiveCollab\DatabaseObject\Entity\EntityInterface;
use ActiveCollab\DatabaseStructure\Behaviour\ParentInterface;
use LogicException;
/**
* @property \ActiveCollab\DatabaseObject\PoolInterface $pool
*/
trait RequiredImplementation
{
public function getParent(bool $use_cache = true): EntityInterface
{
if ($id = $this->getParentId()) {
return $this->pool->getById($this->getParentType(), $id, $use_cache);
} else {
return null;
}
}
/**
* @param EntityInterface $value
* @return ParentInterface|$this
*/
public function &setParent(EntityInterface $value): ParentInterface
{
if (!$value->isLoaded()) {
throw new LogicException('Parent needs to be saved to the database.');
}
$this->setParentType(get_class($value));
$this->setParentId($value->getId());
return $this;
}
abstract public function getParentType(): string;
abstract public function &setParentType(string $value);
abstract public function getParentId(): int;
abstract public function &setParentId(int $value);
}
|
Customize Messenger widget - remove useless param | KylinApp.service('MessageService', function () {
var options = {
extraClasses: 'messenger-fixed messenger-on-top messenger-on-right',
theme: 'air'
};
this.sendMsg = function (msg, type, actions, sticky) {
var data = {
message: msg,
type: angular.isDefined(type) ? type : 'info',
actions: actions,
showCloseButton: true
};
// Whether sticky the message, otherwise it will hide after a period.
if (angular.isDefined(sticky) && sticky === true) {
data.hideAfter = false;
}
Messenger(options).post(data);
}
});
| KylinApp.service('MessageService', function (GraphBuilder) {
var options = {
extraClasses: 'messenger-fixed messenger-on-top messenger-on-right',
theme: 'air'
};
this.sendMsg = function (msg, type, actions, sticky) {
var data = {
message: msg,
type: angular.isDefined(type) ? type : 'info',
actions: actions,
showCloseButton: true
};
// Whether sticky the message, otherwise it will hide after a period.
if (angular.isDefined(sticky) && sticky === true) {
data.hideAfter = false;
}
Messenger(options).post(data);
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.