text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix last issues with new implementation | from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='abraia',
version='0.3.3',
description='Abraia Python SDK',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/abraia/abraia-python',
author='Jorge Rodriguez Araujo',
author_email='jorge@abraiasoftware.com',
license='MIT',
zip_safe=False,
packages=['abraia'],
tests_require=['pytest'],
setup_requires=['setuptools>=38.6.0', 'pytest-runner'],
scripts=['scripts/abraia', 'scripts/abraia.bat'],
install_requires=['requests', 'tqdm', 'future']
)
| from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='abraia',
version='0.3.2',
description='Abraia Python SDK',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/abraia/abraia-python',
author='Jorge Rodriguez Araujo',
author_email='jorge@abraiasoftware.com',
license='MIT',
zip_safe=False,
packages=['abraia'],
tests_require=['pytest'],
setup_requires=['setuptools>=38.6.0', 'pytest-runner'],
scripts=['scripts/abraia', 'scripts/abraia.bat'],
install_requires=['requests', 'tqdm', 'future']
)
|
Fix Typo in Farsi Translations | export default {
at: {
select: {
placeholder: 'انتخاب کنید',
notFoundText: 'موردی یافت نشد'
},
modal: {
okText: 'تایید',
cancelText: 'لغو'
},
pagination: {
prevText: 'صفحهی قبل',
nextText: 'صفحهی بعد',
total: 'تمام',
item: 'مورد',
items: 'مورد',
pageSize: '/ صفحه',
goto: 'برو به',
pageText: '',
prev5Text: 'پنج صفحهی قبلی',
next5Text: 'پنج صفحهی بعدی'
},
table: {
emptyText: 'بدون داده'
}
}
}
| export default {
at: {
select: {
placeholder: 'انتخاب کنید',
notFoundText: 'موردی یافت نشد'
},
modal: {
okText: 'تایید',
cancelText: 'لغو'
},
pagination: {
prevText: 'صفحهی قبل',
nextText: 'صفحهی بعد',
total: 'تمام',
item: 'مورد',
items: 'مورد',
pageSize: '/ صفحه',
goto: 'برو به',
pageText: '',
prev5Text: 'پنج صفحهی بعدی',
next5Text: 'پنج صفحهی قبلی'
},
table: {
emptyText: 'بدون داده'
}
}
}
|
Make travis happy - maybe. | package com.tinkerpop.gremlin.console.plugin;
import com.tinkerpop.gremlin.process.graph.GraphTraversal;
import com.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory;
import org.codehaus.groovy.tools.shell.Groovysh;
import org.codehaus.groovy.tools.shell.IO;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class SugarGremlinPluginTest {
@Test
public void shouldPluginSugar() throws Exception {
final SugarGremlinPlugin plugin = new SugarGremlinPlugin();
final Groovysh groovysh = new Groovysh();
final Map<String,Object> env = new HashMap<>();
env.put("ConsolePluginAcceptor.io", new IO());
env.put("ConsolePluginAcceptor.shell", groovysh);
final SpyPluginAcceptor spy = new SpyPluginAcceptor(groovysh::execute, () -> env);
plugin.pluginTo(spy);
groovysh.getInterp().getContext().setProperty("g", TinkerFactory.createClassic());
assertEquals(6l, ((GraphTraversal) groovysh.execute("g.V()")).count().next());
assertEquals(6l, ((GraphTraversal) groovysh.execute("g.V")).count().next());
}
}
| package com.tinkerpop.gremlin.console.plugin;
import com.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory;
import com.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.codehaus.groovy.tools.shell.Groovysh;
import org.codehaus.groovy.tools.shell.IO;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class SugarGremlinPluginTest {
@Test
public void shouldPluginSugar() throws Exception {
final SugarGremlinPlugin plugin = new SugarGremlinPlugin();
final Groovysh groovysh = new Groovysh();
final Map<String,Object> env = new HashMap<>();
env.put("ConsolePluginAcceptor.io", new IO());
env.put("ConsolePluginAcceptor.shell", groovysh);
final SpyPluginAcceptor spy = new SpyPluginAcceptor(groovysh::execute, () -> env);
plugin.pluginTo(spy);
groovysh.getInterp().getContext().setProperty("g", TinkerFactory.createClassic());
assertEquals(6l, groovysh.execute("g.V().count().next()"));
assertEquals(6l, groovysh.execute("g.V.count().next()"));
}
}
|
Remove DefaultProps.js From Form Component
Remove defaultProps.js from Form component layout prop as it is no
longer in defaultProps.js | import React from 'react'
import ReactDOM from 'react-dom'
export default class Form extends React.Component {
static displayName = 'FriggingBootstrap.Form'
static defaultProps = {
layout: 'vertical',
}
static propTypes = {
formHtml: React.PropTypes.shape({
className: React.PropTypes.string,
}),
layout: React.PropTypes.string,
children: React.PropTypes.any.isRequired,
}
_formHtml() {
const className = this.props.layout ? `form-${this.props.layout}` : ''
return Object.assign({}, this.props.formHtml, {
ref: 'form',
className: `${this.props.formHtml.className || ''} ${className}`.trim(),
})
}
formData() {
const formElement = ReactDOM.findDOMNode(this.refs.form)
return new FormData(formElement)
}
render() {
return (
<form {...this._formHtml()}>
{this.props.children}
</form>
)
}
}
| import React from 'react'
import ReactDOM from 'react-dom'
import DefaultProps from '../default_props.js'
export default class Form extends React.Component {
static displayName = 'FriggingBootstrap.Form'
static defaultProps = {
layout: DefaultProps.layout,
}
static propTypes = {
formHtml: React.PropTypes.shape({
className: React.PropTypes.string,
}),
layout: React.PropTypes.string,
children: React.PropTypes.any.isRequired,
}
_formHtml() {
const className = this.props.layout ? `form-${this.props.layout}` : ''
return Object.assign({}, this.props.formHtml, {
ref: 'form',
className: `${this.props.formHtml.className || ''} ${className}`.trim(),
})
}
formData() {
const formElement = ReactDOM.findDOMNode(this.refs.form)
return new FormData(formElement)
}
render() {
return (
<form {...this._formHtml()}>
{this.props.children}
</form>
)
}
}
|
Fix : Correcting path for acme.json | var fs = require("fs");
var path = require("path");
var acme = require(__dirname + "/acme/acme.json");
if (typeof(acme) !== 'undefined' && (!acme.hasOwnProperty("DomainsCertificate") ||
!acme.DomainsCertificate.hasOwnProperty("Certs"))) {
console.log("Nothing to do");
}
else {
if(typeof(acme) !== 'undefined'){
for (var cert of acme.DomainsCertificate.Certs) {
let domain = cert.Certificate.Domain;
var certDump = new Buffer(cert.Certificate.Certificate, 'base64');
var keyDump = new Buffer(cert.Certificate.PrivateKey, 'base64');
fs.writeFileSync(path.join(__dirname, "certs/" + domain + ".crt"), certDump);
fs.writeFileSync(path.join(__dirname, "certs/" + domain + ".key"), keyDump);
}
console.log("Successfully write all your acme certs & keys");
}
} | var fs = require("fs");
var path = require("path");
var acme = require("acme/acme.json");
if (typeof(acme) !== 'undefined' && (!acme.hasOwnProperty("DomainsCertificate") ||
!acme.DomainsCertificate.hasOwnProperty("Certs"))) {
console.log("Nothing to do");
}
else {
if(typeof(acme) !== 'undefined'){
for (var cert of acme.DomainsCertificate.Certs) {
let domain = cert.Certificate.Domain;
var certDump = new Buffer(cert.Certificate.Certificate, 'base64');
var keyDump = new Buffer(cert.Certificate.PrivateKey, 'base64');
fs.writeFileSync(path.join(__dirname, "certs/" + domain + ".crt"), certDump);
fs.writeFileSync(path.join(__dirname, "certs/" + domain + ".key"), keyDump);
}
console.log("Successfully write all your acme certs & keys");
}
} |
Add a method for adding custom CSS class
Allow us to append a class for the body when it's the night | (function (g, ns) {
"use strict";
function gn() {
var Goodnight = { AM: 6, PM: 18 }, hours = new Date().getHours(), ln = [];
Goodnight.night = function () {
return hours < this.PM ? hours < this.AM ? true : false : true;
};
Goodnight.css = function (path) {
if (!path) {
return;
}
var item = document.createElement("link");
item.rel = "stylesheet";
item.href = path;
ln.push(item);
if (this.night()) {
document.documentElement.firstChild.appendChild(item);
}
};
Goodnight.class = function (cssClass) {
if (this.night()) {
document.body.className += " " + (cssClass || "goodnight");
}
};
Goodnight.toggle = function () {
for (var i = 0; i < ln.length; i++) {
if (ln[i].parentNode) {
ln[i].parentNode.removeChild(ln[i]);
} else {
document.documentElement.firstChild.appendChild(ln[i]);
}
}
};
return Goodnight;
}
g[ns] = gn();
})(window, "Goodnight");
| (function (g, ns) {
"use strict";
function gn() {
var Goodnight = { AM: 6, PM: 18 }, hours = new Date().getHours(), ln = [];
Goodnight.night = function () {
return hours < this.PM ? hours < this.AM ? true : false : true;
};
Goodnight.css = function (path) {
if (!path) {
return;
}
var item = document.createElement("link");
item.rel = "stylesheet";
item.href = path;
ln.push(item);
if (this.night()) {
document.documentElement.firstChild.appendChild(item);
}
};
Goodnight.toggle = function () {
for (var i = 0; i < ln.length; i++) {
if (ln[i].parentNode) {
ln[i].parentNode.removeChild(ln[i]);
} else {
document.documentElement.firstChild.appendChild(ln[i]);
}
}
};
return Goodnight;
}
g[ns] = gn();
})(window, "Goodnight");
|
Adjust mc version number in core mod. | package io.github.elytra.movingworld.common.asm.coremod;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.Mixins;
import java.util.Map;
@IFMLLoadingPlugin.MCVersion(value = "1.11")
public class MovingWorldCoreMod implements IFMLLoadingPlugin {
public MovingWorldCoreMod() {
MixinBootstrap.init();
Mixins.addConfiguration("mixins.movingworld.json");
}
@Override
public String[] getASMTransformerClass() {
return null;
}
@Override
public String getModContainerClass() {
return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldModContainer";
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {
}
@Override
public String getAccessTransformerClass() {
return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldAccessTransformer";
}
}
| package io.github.elytra.movingworld.common.asm.coremod;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.Mixins;
import java.util.Map;
@IFMLLoadingPlugin.MCVersion(value = "1.10.2")
public class MovingWorldCoreMod implements IFMLLoadingPlugin {
public MovingWorldCoreMod() {
MixinBootstrap.init();
Mixins.addConfiguration("mixins.movingworld.json");
}
@Override
public String[] getASMTransformerClass() {
return null;
}
@Override
public String getModContainerClass() {
return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldModContainer";
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {
}
@Override
public String getAccessTransformerClass() {
return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldAccessTransformer";
}
}
|
Add code commented note about setTimeout | ;(function(){
var app = angular.module('Communicant', []);
app.controller('ListOfMessagesController', ['$scope', '$http', function($scope, $http){
$http.get("/messages.json")
.then(function(response){
$scope.messages = response.data;
})
}]); // END ListOfMessagesController
app.controller('SendMessageController', ['$scope', '$http', function($scope, $http){
// console.log("Hello?");
$scope.newMessage = { };
$scope.submit = function(){
$http.post("/messages.json", $scope.newMessage);
};
$http.get("/messages.json")
.then(function(response){
$scope.messages = response.data;
})
}]); // END SendMessageController
// $timeout([fn], [2000], [invokeApply], [Pass]);
})(); // END IIFE
| ;(function(){
var app = angular.module('Communicant', []);
app.controller('ListOfMessagesController', ['$scope', '$http', function($scope, $http){
$http.get("/messages.json")
.then(function(response){
$scope.messages = response.data;
})
}]); // END ListOfMessagesController
app.controller('SendMessageController', ['$scope', '$http', function($scope, $http){
// console.log("Hello?");
$scope.newMessage = { };
$scope.submit = function(){
$http.post("/messages.json", $scope.newMessage);
};
$http.get("/messages.json")
.then(function(response){
$scope.messages = response.data;
})
}]); // END SendMessageController
})(); // END IIFE
|
Use abstract classs instead of interface for static methods
This is to workaround https://github.com/janino-compiler/janino/issues/69 | package com.github.vlsi.mat.calcite.functions;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.snapshot.model.IClass;
import org.eclipse.mat.snapshot.model.IObject;
@SuppressWarnings("unused")
public abstract class IClassMethods {
public static IClass getSuper(IObject clazz) {
if (clazz instanceof IClass) {
return ((IClass) clazz).getSuperClass();
}
return null;
}
public static IObject getClassLoader(IObject clazz) {
if (!(clazz instanceof IClass)) {
return null;
}
int classLoaderId = ((IClass) clazz).getClassLoaderId();
try {
return clazz.getSnapshot().getObject(classLoaderId);
} catch (SnapshotException e) {
throw new IllegalArgumentException(
"Unable to retrieve classloader of class " + clazz + " in heap " + clazz.getSnapshot(), e);
}
}
public static String getClassName(IObject clazz) {
if (clazz instanceof IClass) {
return ((IClass) clazz).getName();
}
return null;
}
}
| package com.github.vlsi.mat.calcite.functions;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.snapshot.model.IClass;
import org.eclipse.mat.snapshot.model.IObject;
@SuppressWarnings("unused")
public interface IClassMethods {
static IClass getSuper(IObject clazz) {
if (clazz instanceof IClass) {
return ((IClass) clazz).getSuperClass();
}
return null;
}
static IObject getClassLoader(IObject clazz) {
if (!(clazz instanceof IClass)) {
return null;
}
int classLoaderId = ((IClass) clazz).getClassLoaderId();
try {
return clazz.getSnapshot().getObject(classLoaderId);
} catch (SnapshotException e) {
throw new IllegalArgumentException(
"Unable to retrieve classloader of class " + clazz + " in heap " + clazz.getSnapshot(), e);
}
}
static String getClassName(IObject clazz) {
if (clazz instanceof IClass) {
return ((IClass) clazz).getName();
}
return null;
}
}
|
Update webpack settings to retain filename | 'use strict';
var gulp = require( 'gulp' );
var $ = require( 'gulp-load-plugins' )();
var pkg = require( '../config' ).pkg;
var banner = require( '../config' ).banner;
var config = require( '../config' ).scripts;
var handleErrors = require( '../utils/handleErrors' );
var browserSync = require( 'browser-sync' );
gulp.task( 'scripts', function() {
return gulp.src( config.src )
.pipe( $.sourcemaps.init() )
.pipe( $.webpack( {
output: {
filename: '[name].js'
}
} ) )
.pipe( $.uglify() )
.on( 'error', handleErrors )
.pipe( $.header( banner, { pkg: pkg } ) )
.pipe( $.rename( {
suffix: '.min'
} ) )
.pipe( $.sourcemaps.write( '.' ) )
.pipe( gulp.dest( config.dest ) )
.pipe( browserSync.reload( {
stream: true
} ) );
} );
| 'use strict';
var gulp = require( 'gulp' );
var $ = require( 'gulp-load-plugins' )();
var pkg = require( '../config' ).pkg;
var banner = require( '../config' ).banner;
var config = require( '../config' ).scripts;
var handleErrors = require( '../utils/handleErrors' );
var browserSync = require( 'browser-sync' );
gulp.task( 'scripts', function() {
return gulp.src( config.src )
.pipe( $.sourcemaps.init() )
.pipe( $.webpack() )
.pipe( $.uglify() )
.on( 'error', handleErrors )
.pipe( $.header( banner, { pkg: pkg } ) )
.pipe( $.rename( {
suffix: ".min"
} ) )
.pipe( $.sourcemaps.write( '.' ) )
.pipe( gulp.dest( config.dest ) )
.pipe( browserSync.reload( {
stream: true
} ) );
} );
|
[MIG] Change the version of module. | # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '9.0.1.0.0',
'depends': [
'l10n_br_base',
],
'data': [
'views/l10n_br_zip_view.xml',
'views/res_partner_view.xml',
'views/res_company_view.xml',
'views/res_bank_view.xml',
'wizard/l10n_br_zip_search_view.xml',
'security/ir.model.access.csv',
],
'test': [
'test/zip_demo.yml'
],
'category': 'Localization',
'installable': True,
}
| # -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
'l10n_br_base',
],
'data': [
'views/l10n_br_zip_view.xml',
'views/res_partner_view.xml',
'views/res_company_view.xml',
'views/res_bank_view.xml',
'wizard/l10n_br_zip_search_view.xml',
'security/ir.model.access.csv',
],
'test': ['test/zip_demo.yml'],
'category': 'Localization',
'installable': False,
}
|
Allow the port to be defined | // Copyright 2013 Landon Wainwright. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Starts up the blog system using the default values
package main
import (
"flag"
"github.com/landonia/simplegoblog/blog"
"log"
"os"
)
// Starts a new simple go blog server
func main() {
// Define flags
var postsdir, templatesdir, assetsdir, port string
flag.StringVar(&postsdir, "pdir", "../posts", "the directory for storing the posts")
flag.StringVar(&templatesdir, "tdir", "../templates", "the directory containing the templates")
flag.StringVar(&assetsdir, "adir", "../assets", "the directory containing the assets")
flag.StringVar(&port, "port", "8080", "the port to run the blog on")
flag.Parse()
// Create a new configuration containing the info
config := &blog.Configuration{Title: "Life thru a Lando", DevelopmentMode: true, Postsdir: postsdir, Templatesdir: templatesdir, Assetsdir: assetsdir}
// Create a new data structure for storing the data
b := blog.New(config)
// Start the blog server
err := b.Start(port)
if err != nil {
log.Println(err)
os.Exit(1)
}
}
| // Copyright 2013 Landon Wainwright. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Starts up the blog system using the default values
package main
import (
"flag"
"github.com/landonia/simplegoblog/blog"
"log"
"os"
)
// Starts a new simple go blog server
func main() {
// Define flags
var postsdir, templatesdir, assetsdir string
flag.StringVar(&postsdir, "pdir", "../posts", "the directory for storing the posts")
flag.StringVar(&templatesdir, "tdir", "../templates", "the directory containing the templates")
flag.StringVar(&assetsdir, "adir", "../assets", "the directory containing the assets")
flag.Parse()
// Create a new configuration containing the info
config := &blog.Configuration{Title: "Life thru a Lando", DevelopmentMode: true, Postsdir: postsdir, Templatesdir: templatesdir, Assetsdir: assetsdir}
// Create a new data structure for storing the data
b := blog.New(config)
// Start the blog server
err := b.Start(":8080")
if err != nil {
log.Println(err)
os.Exit(1)
}
}
|
Add webname in event model | <?php
namespace CodeDay\Clear\Controllers\Api;
use \CodeDay\Clear\Models;
class Events extends ContractualController {
protected $fields = [
'id',
'name',
'webname',
'abbr',
'full_name',
'registration_info' => [
'estimate' => 'registration_estimate',
'max' => 'max_registrations',
'is_open' => 'allow_registrations'
],
'venue',
'starts_at',
'ends_at',
'batch_name',
'waiver' => 'waiver_link',
'manager' => 'manager_username'
];
public function getIndex()
{
return $this->getContract(Models\Batch::Loaded()->events);
}
public function getEvent()
{
return $this->getContract(\Route::input('event'));
}
}
| <?php
namespace CodeDay\Clear\Controllers\Api;
use \CodeDay\Clear\Models;
class Events extends ContractualController {
protected $fields = [
'id',
'name',
'full_name',
'registration_info' => [
'estimate' => 'registration_estimate',
'max' => 'max_registrations',
'is_open' => 'allow_registrations'
],
'venue',
'starts_at',
'ends_at',
'batch_name',
'waiver' => 'waiver_link',
'manager' => 'manager_username'
];
public function getIndex()
{
return $this->getContract(Models\Batch::Loaded()->events);
}
public function getEvent()
{
return $this->getContract(\Route::input('event'));
}
} |
Abort CSP compiler pass when CSP is not enabled
When csp enabled is set to false in the configuration csp.xml will not be loaded,
so there is no service `nelmio_security.csp_report.filter` and asking the definition
for that non-existing service results in an exception.
So first we check if the service is available in the container and if it's not we bail out
(return early). | <?php
namespace Nelmio\SecurityBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class CspReportFilterCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('nelmio_security.csp_report.filter')) {
return;
}
$services = $container->findTaggedServiceIds('nelmio_security.csp_report_filter');
$cspViolationLogFilterDefinition = $container->getDefinition('nelmio_security.csp_report.filter');
foreach ($services as $id => $attributes) {
$cspViolationLogFilterDefinition->addMethodCall('addNoiseDetector', array(new Reference($id)));
}
}
}
| <?php
namespace Nelmio\SecurityBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class CspReportFilterCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$services = $container->findTaggedServiceIds('nelmio_security.csp_report_filter');
$cspViolationLogFilterDefinition = $container->getDefinition('nelmio_security.csp_report.filter');
foreach ($services as $id => $attributes) {
$cspViolationLogFilterDefinition->addMethodCall('addNoiseDetector', array(new Reference($id)));
}
}
}
|
Set renderingBaseURL on the loader | var pkg = require("../package.json");
global.navigator = global.navigator || {
userAgent: "Mozilla/5.0 " + "done-ssr/" + pkg.version
};
module.exports = function(loader){
// Ensure the extension loads before the main.
var loaderImport = loader.import;
loader.import = function(name){
if(name === loader.main) {
var args = arguments;
// Set up the renderingLoader to be used by plugins to know what root
// to attach urls to.
if(!loader.renderingLoader) {
loader.renderingLoader = loader.clone();
var baseURL = loader.renderingBaseURL || loader.baseURL;
if(baseURL.indexOf("file:") === 0) {
baseURL = "/";
}
loader.renderingLoader.baseURL =
loader.renderingBaseURL = baseURL;
}
return loaderImport.apply(loader, args);
}
return loaderImport.apply(this, arguments);
};
};
| var pkg = require("../package.json");
global.navigator = global.navigator || {
userAgent: "Mozilla/5.0 " + "done-ssr/" + pkg.version
};
module.exports = function(loader){
// Ensure the extension loads before the main.
var loaderImport = loader.import;
loader.import = function(name){
if(name === loader.main) {
var args = arguments;
// Set up the renderingLoader to be used by plugins to know what root
// to attach urls to.
if(!loader.renderingLoader) {
loader.renderingLoader = loader.clone();
var baseURL = loader.renderingBaseURL || loader.baseURL;
if(baseURL.indexOf("file:") === 0) {
baseURL = "/";
}
loader.renderingLoader.baseURL = baseURL;
}
return loaderImport.apply(loader, args);
}
return loaderImport.apply(this, arguments);
};
};
|
Add script for js file and update html tags | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo WEBSITE_NAME; ?></title>
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="<?php echo WEBSITE_NAME; ?>">
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-114.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-144.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144.png">
<link rel="icon" type="image/x-icon" href="/favicon.ico">
<link href="//<?php echo STATIC_DOMAIN; ?>/css/styles.css" media="all" rel="stylesheet" type="text/css">
<script src="//<?php echo STATIC_DOMAIN; ?>/js/scripts.js"></script>
</head>
<body> | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo WEBSITE_NAME; ?></title>
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="Website" />
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-114.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-144.png" />
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144.png" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link href="//<?php echo STATIC_DOMAIN; ?>/css/styles.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body> |
Check response code of Veooz API call | var request = require("request").defaults({
'proxy': process.env.http_proxy || process.env.HTTP_PROXY,
'timeout': 20 * 1000
});
var veoozArticleUtils = require("../articles/veoozArticleUtils.js");
var config = require('./config.json');
module.exports.pushArticle = function (article) {
return new Promise(function(resolve, reject) {
request.post(
{
url: "http://www.veooz.com/api/v2/pusharticles",
form: {
apikey: config.veoozApikey,
article: JSON.stringify(veoozArticleUtils.convertAccessibleArticle(article))
}
},
function (err, res, body) {
if (err || res.statusCode != 200) {
reject(err || res.statusCode + " - " + body);
} else {
resolve();
}
}
);
});
};
| var request = require("request").defaults({
'proxy': process.env.http_proxy || process.env.HTTP_PROXY,
'timeout': 20 * 1000
});
var veoozArticleUtils = require("../articles/veoozArticleUtils.js");
var config = require('./config.json');
module.exports.pushArticle = function (article) {
return new Promise(function(resolve, reject) {
request.post(
{
url: "http://www.veooz.com/api/v2/pusharticles",
form: {
apikey: config.veoozApikey,
article: JSON.stringify(veoozArticleUtils.convertAccessibleArticle(article))
}
},
function (err, res, body) {
if (err) {
reject(err);
} else {
resolve();
}
}
);
});
};
|
Define valid keys per platform and filter out invalid options. | var spawn = require('child_process').spawn;
var path = require('path');
module.exports = function (options) {
options = options || {};
options.url = options.url || 'http://nodejs.org';
options.name = options.name || 'nodejs';
var client;
var keys = [];
switch (process.platform) {
case 'win32':
client = path.resolve(__dirname + '/cefclient/cefclient');
keys = ['url', 'name', 'width', 'height', 'minwidth', 'minheight', 'ico'];
break;
case 'linux':
client = path.resolve(__dirname + '/build/default/topcube');
keys = ['url', 'name', 'width', 'height', 'minwidth', 'minheight'];
break;
default:
console.warn('');
return null;
break;
}
var args = [];
for (var key in options) {
if (keys.indexOf(key) !== -1) {
args.push('--' + key + '=' + options[key]);
}
}
var child = spawn(client, args);
child.on('exit', function(code) {
process.exit(code);
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
return child;
};
| var spawn = require('child_process').spawn;
var path = require('path');
module.exports = function (options) {
options = options || {};
options.url = options.url || 'http://nodejs.org';
options.name = options.name || 'nodejs';
var client;
switch (process.platform) {
case 'win32':
client = path.resolve(__dirname + '/cefclient/cefclient');
break;
case 'linux':
client = path.resolve(__dirname + '/build/default/topcube');
break;
default:
console.warn('');
return null;
break;
}
var args = [];
for (var key in options) args.push('--' + key + '=' + options[key]);
var child = spawn(client, args);
child.on('exit', function(code) {
process.exit(code);
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
return child;
};
|
Read perms off the ACL object properly | import unittest
from nose.tools import eq_
import zookeeper
class TestACL(unittest.TestCase):
def _makeOne(self, *args, **kwargs):
from kazoo.security import make_acl
return make_acl(*args, **kwargs)
def test_read_acl(self):
acl = self._makeOne("digest", ":", read=True)
eq_(acl.perms & zookeeper.PERM_READ, zookeeper.PERM_READ)
def test_all_perms(self):
acl = self._makeOne("digest", ":", write=True, create=True,
delete=True, admin=True)
for perm in [zookeeper.PERM_WRITE, zookeeper.PERM_CREATE,
zookeeper.PERM_DELETE, zookeeper.PERM_ADMIN]:
eq_(acl.perms & perm, perm)
| import unittest
from nose.tools import eq_
import zookeeper
class TestACL(unittest.TestCase):
def _makeOne(self, *args, **kwargs):
from kazoo.security import make_acl
return make_acl(*args, **kwargs)
def test_read_acl(self):
acl = self._makeOne("digest", ":", read=True)
eq_(acl['perms'] & zookeeper.PERM_READ, zookeeper.PERM_READ)
def test_all_perms(self):
acl = self._makeOne("digest", ":", write=True, create=True,
delete=True, admin=True)
for perm in [zookeeper.PERM_WRITE, zookeeper.PERM_CREATE,
zookeeper.PERM_DELETE, zookeeper.PERM_ADMIN]:
eq_(acl['perms'] & perm, perm)
|
Change config to production values | <?php
return [
/*
|--------------------------------------------------------------------------
| Config options for the zKill bot
|--------------------------------------------------------------------------
|
|
|
*/
'base_url' => 'https://zkillboard.com/api/kills/',
'kill_link' => 'https://zkillboard.com/kill/',
'ship_renders' => 'https://image.eveonline.com/Render/',
'min_value' => 1000000000,
'name' => 'DankBot',
'emoji' => ':ptb:',
'corps' => [
'ptb' => [
'id' => 398598576,
'channel' => 'ptb',
'active' => true
],
// 'wasp' => [
// 'id' => 101116365,
// 'channel' => 'api_test',
// 'active' => false
// ],
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Config options for the zKill bot
|--------------------------------------------------------------------------
|
|
|
*/
'base_url' => 'https://zkillboard.com/api/kills/',
'kill_link' => 'https://zkillboard.com/kill/',
'ship_renders' => 'https://image.eveonline.com/Render/',
'min_value' => 1000000000,
'name' => 'DankBot',
'emoji' => ':ptb:',
'corps' => [
'ptb' => [
'id' => 398598576,
'channel' => 'api_test',
'active' => true
],
'wasp' => [
'id' => 101116365,
'channel' => 'api_test',
'active' => false
],
],
];
|
Add help, make output more user friendly | '''
File: antifuzz.py
Authors: Kaitlin Keenan and Ryan Frank
'''
import sys
from shutil import copy2
import subprocess
import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("originalFile", help="File to antifuzz")
parser.add_argument("newFile", help="Name of the antifuzzed file")
args = parser.parse_args()
# Take in file
ogFile = args.originalFile
# Make copy of file
nFile = args.newFile
# Mess with the given file
mp3(ogFile, nFile)
# Hash files
ogHash = ssdeep.hash_from_file(ogFile)
newHash = ssdeep.hash_from_file(nFile)
# Compare the hashes
#print ogHash
diff=str(ssdeep.compare(ogHash, newHash))
print("The files are " + diff + "% different")
def mp3(ogFile, newFile):
cmd(['lame','--quiet', '--scale', '1', ogFile])
cmd(['mv', ogFile + ".mp3", newFile])
def cmd(command):
#if (arg2 && arg1):
p = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
return out
if __name__ == "__main__":
main()
| '''
File: antifuzz.py
Authors: Kaitlin Keenan and Ryan Frank
'''
import sys
from shutil import copy2
import subprocess
import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html
def main():
# Take in file
ogFile = sys.argv[1]
# Make copy of file
newFile = sys.argv[2]
# Mess with the given file
cmd(['lame','--quiet', '--scale', '1', ogFile])
print cmd(['mv', ogFile + ".mp3", newFile])
# Hash files
ogHash = ssdeep.hash_from_file(ogFile)
newHash = ssdeep.hash_from_file(newFile)
# Compare the hashes
#print ogHash
print ssdeep.compare(ogHash, newHash)
def cmd(command):
#if (arg2 && arg1):
p = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
return out
if __name__ == "__main__":
main()
|
Fix invalid test and disable it due to V8 bug
git-svn-id: ca18d33ed0a52a52a9e4af52a70971734132dd4e@289 27ec44a0-f51e-dfec-681c-368ff20b0e0a | class ElementHolder {
element;
getElement() { return this.element; }
makeFilterCapturedThis() {
var capturedThis = this;
return function (x) {
return x == capturedThis.element;
}
}
makeFilterLostThis() {
return function () { return this; }
}
makeFilterHidden(element) {
return function (x) { return x == element; }
}
}
// ----------------------------------------------------------------------------
var obj = new ElementHolder();
obj.element = 40;
assertEquals(40, obj.getElement());
assertTrue(obj.makeFilterCapturedThis()(40));
// http://code.google.com/p/v8/issues/detail?id=1381
// assertUndefined(obj.makeFilterLostThis()());
obj.element = 39;
assertFalse(obj.makeFilterCapturedThis()(40));
assertTrue(obj.makeFilterCapturedThis()(39));
assertFalse(obj.makeFilterHidden(41)(40));
assertTrue(obj.makeFilterHidden(41)(41));
| class ElementHolder {
element;
getElement() { return this.element; }
makeFilterCapturedThis() {
var capturedThis = this;
return function (x) {
return x == capturedThis.element;
}
}
makeFilterLostThis() {
return function (x) { return x == this.element; }
}
makeFilterHidden(element) {
return function (x) { return x == element; }
}
}
// ----------------------------------------------------------------------------
var obj = new ElementHolder();
obj.element = 40;
assertEquals(40, obj.getElement());
assertTrue(obj.makeFilterCapturedThis()(40));
assertFalse(obj.makeFilterLostThis()(40));
obj.element = 39;
assertFalse(obj.makeFilterCapturedThis()(40));
assertTrue(obj.makeFilterCapturedThis()(39));
assertFalse(obj.makeFilterHidden(41)(40));
assertTrue(obj.makeFilterHidden(41)(41));
|
Throw exception when there are multiple implementations on the classpath
Also grouped "No implementation" test in with other implementation
loading tests. | package uk.co.littlemike.jextend;
import org.junit.After;
import org.junit.Test;
import uk.co.littlemike.jextend.impl.MultipleImplementationsOnClasspathException;
import uk.co.littlemike.jextend.impl.NoImplementationOnClasspathException;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.singleton;
import static uk.co.littlemike.jextend.JExtend.*;
public class ImplementationLoaderTest {
@After
public void autodetectExtender() {
resetServiceLoader();
}
@Test(expected = NoImplementationOnClasspathException.class)
public void throwsExceptionIfNoImplementationAvailableOnClasspath() {
getExtension(List.class, ListExtension.class);
}
@Test
public void usesImplementationRepeatedlyWhenOneAvailableOnClasspath() {
setServiceLoader(c -> singleton(new StubExtender()));
getExtension(List.class, ListExtension.class);
getExtension(List.class, ListExtension.class);
}
@Test(expected = MultipleImplementationsOnClasspathException.class)
public void throwsExceptionWhenMultipleImplementationsAreAvailableOnClasspath() {
setServiceLoader(c -> Arrays.asList(new StubExtender(), new StubExtender()));
getExtension(List.class, ListExtension.class);
}
}
| package uk.co.littlemike.jextend;
import org.junit.After;
import org.junit.Test;
import uk.co.littlemike.jextend.impl.MultipleImplementationsOnClasspathException;
import uk.co.littlemike.jextend.impl.NoImplementationOnClasspathException;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.singleton;
import static uk.co.littlemike.jextend.JExtend.*;
public class ImplementationLoaderTest {
@After
public void autodetectExtender() {
resetServiceLoader();
}
@Test(expected = NoImplementationOnClasspathException.class)
public void throwsExceptionIfNoImplementationAvailableOnClasspath() {
getExtension(List.class, ListExtension.class);
}
@Test
public void usesImplementationWhenOneAvailableOnClasspath() {
setServiceLoader(c -> singleton(new StubExtender()));
getExtension(List.class, ListExtension.class);
}
@Test(expected = MultipleImplementationsOnClasspathException.class)
public void throwsExceptionWhenMultipleImplementationsAreAvailableOnClasspath() {
setServiceLoader(c -> Arrays.asList(new StubExtender(), new StubExtender()));
getExtension(List.class, ListExtension.class);
}
}
|
Modify displaying of error message | module.exports = HttpConnection;
var request = require('requestretry');
var HttpConfig = require("./HttpConfig");
var PaymayaApiError = require("./PaymayaApiError");
function HttpConnection(httpConfig) {
this._httpConfig = httpConfig;
};
HttpConnection.prototype = {
/* PUBLIC FUNCTIONS */
execute: function(data, callback) {
var httpOptions = {
url: this._httpConfig.getUrl(),
method: this._httpConfig.getMethod(),
headers: this._httpConfig.getHeaders(),
maxAttempts: this._httpConfig.getMaximumRequestAttempt()
};
if(data) {
httpOptions['body'] = JSON.stringify(data);
}
request(httpOptions, function(err, response, body) {
if(err) {
return callback(err);
}
if(!body && response.statusCode >= 400) {
var err = new PaymayaApiError(response.statusCode);
return callback(err);
}
if(typeof body != 'object') {
body = JSON.parse(body);
}
if(body.error) {
var err = new PaymayaApiError(response.statusCode, body.error);
return callback(err.message);
}
if(body.message && response.statusCode != 200) {
return callback(body.message);
}
callback(null, body);
});
}
}; | module.exports = HttpConnection;
var request = require('requestretry');
var HttpConfig = require("./HttpConfig");
var PaymayaApiError = require("./PaymayaApiError");
function HttpConnection(httpConfig) {
this._httpConfig = httpConfig;
};
HttpConnection.prototype = {
/* PUBLIC FUNCTIONS */
execute: function(data, callback) {
var httpOptions = {
url: this._httpConfig.getUrl(),
method: this._httpConfig.getMethod(),
headers: this._httpConfig.getHeaders(),
maxAttempts: this._httpConfig.getMaximumRequestAttempt()
};
if(data) {
httpOptions['body'] = JSON.stringify(data);
}
request(httpOptions, function(err, response, body) {
if(err) {
return callback(err);
}
if(!body && response.statusCode >= 400) {
var err = new PaymayaApiError(response.statusCode);
return callback(err);
}
if(typeof body != 'object') {
body = JSON.parse(body);
}
if(body.error) {
var err = new PaymayaApiError(response.statusCode, body.error);
return callback(err.message);
}
if(body.message) {
return callback(body.message);
}
callback(null, body);
});
}
}; |
Use the cache item on the memory cache | <?php
/**
* @copyright ©2014 Quicken Loans Inc. All rights reserved. Trade Secret,
* Confidential and Proprietary. Any dissemination outside of Quicken Loans
* is strictly prohibited.
*/
namespace MCP\Cache;
use MCP\DataType\Time\TimePoint;
use MCP\Cache\Item\Item;
/**
* @internal
*/
class Memory implements CacheInterface
{
/**
* @var array
*/
private $cache;
public function __construct()
{
$this->cache = [];
}
/**
* {@inheritdoc}
*/
public function get($key)
{
if (!isset($this->cache[$key])) {
return null;
}
$item = $this->cache[$key];
if (!$item instanceof Item) {
return null;
}
return $item->data();
}
/**
* $ttl is ignored. If your data is living that long in memory, you got issues.
*
* {@inheritdoc}
*/
public function set($key, $value, $ttl = 0)
{
$this->cache[$key] = new Item($value);
return true;
}
}
| <?php
/**
* @copyright ©2014 Quicken Loans Inc. All rights reserved. Trade Secret,
* Confidential and Proprietary. Any dissemination outside of Quicken Loans
* is strictly prohibited.
*/
namespace MCP\Cache;
use MCP\DataType\Time\TimePoint;
/**
* @internal
*/
class Memory implements CacheInterface
{
use ValidationTrait;
/**
* @var array
*/
private $cache;
public function __construct()
{
$this->cache = [];
}
/**
* {@inheritdoc}
*/
public function get($key)
{
if (!isset($this->cache[$key])) {
return null;
}
return $this->cache[$key];
}
/**
* $ttl is ignored. If your data is living that long in memory, you got issues.
*
* {@inheritdoc}
*/
public function set($key, $value, $ttl = 0)
{
$this->validateCacheability($value);
$this->cache[$key] = $value;
return true;
}
}
|
Use user.get_username() instead of user.username
To support custom User models | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from ...settings import get_user_model
from ...sync import sync_customer
User = get_user_model()
class Command(BaseCommand):
help = "Sync customer data with stripe"
def handle(self, *args, **options):
qs = User.objects.exclude(customer__isnull=True)
count = 0
total = qs.count()
for user in qs:
count += 1
perc = int(round(100 * (float(count) / float(total))))
print(
"[{0}/{1} {2}%] Syncing {3} [{4}]".format(
count, total, perc, user.get_username(), user.pk
)
)
sync_customer(user)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from ...settings import get_user_model
from ...sync import sync_customer
User = get_user_model()
class Command(BaseCommand):
help = "Sync customer data with stripe"
def handle(self, *args, **options):
qs = User.objects.exclude(customer__isnull=True)
count = 0
total = qs.count()
for user in qs:
count += 1
perc = int(round(100 * (float(count) / float(total))))
print(
"[{0}/{1} {2}%] Syncing {3} [{4}]".format(
count, total, perc, user.username, user.pk
)
)
sync_customer(user)
|
Add weakref assertion in test case | """ Tests for the garbage collection of Scene objects.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
import weakref
import gc
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.scene import Scene
from tvtk.tests.common import restore_gc_state
class TestScene(unittest.TestCase):
@unittest.skipIf(
ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
def test_scene_garbage_collected(self):
# given
scene_collected = []
scene_weakref = None
def scene_collected_callback(weakref):
scene_collected.append(True)
def do():
scene = Scene()
reference = weakref.ref(scene, scene_collected_callback)
scene.close()
return reference
# when
with restore_gc_state():
gc.disable()
scene_weakref = do()
# The Scene should have been collected.
self.assertTrue(scene_collected[0])
self.assertIsNone(scene_weakref())
if __name__ == "__main__":
unittest.main()
| """ Tests for the garbage collection of Scene objects.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
import weakref
import gc
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.scene import Scene
from tvtk.tests.common import restore_gc_state
class TestScene(unittest.TestCase):
@unittest.skipIf(
ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
def test_scene_garbage_collected(self):
# given
scene_collected = []
scene_weakref = None
def scene_collected_callback(weakref):
scene_collected.append(True)
def do():
scene = Scene()
reference = weakref.ref(scene, scene_collected_callback)
scene.close()
return reference
# when
with restore_gc_state():
gc.disable()
scene_weakref = do()
# The Scene should have been collected.
self.assertTrue(scene_collected[0])
if __name__ == "__main__":
unittest.main()
|
Revert "Update nullables and unused import"
This reverts commit 8ee3b4d8c5a67dcaf343ef195f750baca6e64aeb. | /**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.config;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
public final class AtlasDbConfigs {
public static final String ATLASDB_CONFIG_ROOT = "/atlasdb";
private AtlasDbConfigs() {
// uninstantiable
}
public static AtlasDbConfig load(File configFile) throws IOException {
return load(configFile, ATLASDB_CONFIG_ROOT);
}
public static AtlasDbConfig load(File configFile, String configRoot) throws IOException {
ConfigFinder finder = new ConfigFinder(configRoot);
return finder.getConfig(configFile);
}
public static AtlasDbConfig loadFromString(String fileContents, String configRoot) throws IOException {
ConfigFinder finder = new ConfigFinder(configRoot);
return finder.getConfig(fileContents);
}
}
| /**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.config;
import java.io.File;
import java.io.IOException;
import javax.annotation.Nullable;
public final class AtlasDbConfigs {
public static final String ATLASDB_CONFIG_ROOT = "/atlasdb";
private AtlasDbConfigs() {
// uninstantiable
}
public static AtlasDbConfig load(File configFile) throws IOException {
return load(configFile, ATLASDB_CONFIG_ROOT);
}
public static AtlasDbConfig load(File configFile, @Nullable String configRoot) throws IOException {
ConfigFinder finder = new ConfigFinder(configRoot);
return finder.getConfig(configFile);
}
public static AtlasDbConfig loadFromString(String fileContents, @Nullable String configRoot) throws IOException {
ConfigFinder finder = new ConfigFinder(configRoot);
return finder.getConfig(fileContents);
}
}
|
Update @postman/shipit to version v0.3.0 | #!/usr/bin/env node
// ---------------------------------------------------------------------------------------------------------------------
// This script is intended to automate the versioning and changelog generation process for a release.
// ---------------------------------------------------------------------------------------------------------------------
const shipit = require('@postman/shipit'),
// npm run release [true] [beta]
[pushToOrigin, preReleaseSuffix] = process.argv.splice(2);
// only support `beta` suffix
if (preReleaseSuffix && preReleaseSuffix !== 'beta') {
throw new Error(`Can't prerelease with \`${preReleaseSuffix}\` suffix.`);
}
// 🚢 Just Ship It!
shipit({
mainBranch: 'main',
// don't push to origin unless explicitly set
pushToOrigin: pushToOrigin === 'true',
// prerelease suffix, if any
preReleaseSuffix: preReleaseSuffix,
// make sure that following dependencies are up to date
dependencyList: [
'chai-postman', 'liquid-json', 'lodash3', 'postman-collection',
'teleport-javascript', 'uniscope', 'uvm'
]
}).then((version) => {
console.info('🚀', version);
}).catch((err) => {
console.error('🔥', err);
process.exit(1);
});
| #!/usr/bin/env node
// ---------------------------------------------------------------------------------------------------------------------
// This script is intended to automate the versioning and changelog generation process for a release.
// ---------------------------------------------------------------------------------------------------------------------
const shipit = require('@postman/shipit'),
// npm run release [true] [beta]
[pushToOrigin, preReleaseSuffix] = process.argv.splice(2);
// only support `beta` suffix
if (preReleaseSuffix && preReleaseSuffix !== 'beta') {
throw new Error(`Can't prerelease with \`${preReleaseSuffix}\` suffix.`);
}
// 🚢 Just Ship It!
shipit({
// don't push to origin unless explicitly set
pushToOrigin: pushToOrigin === 'true',
// prerelease suffix, if any
preReleaseSuffix: preReleaseSuffix,
// make sure that following dependencies are up to date
dependencyList: [
'chai-postman', 'liquid-json', 'lodash3', 'postman-collection',
'teleport-javascript', 'uniscope', 'uvm'
]
}).then((version) => {
console.info('🚀', version);
}).catch((err) => {
console.error('🔥', err);
process.exit(1);
});
|
Call remove() only for non-destroyed emptyViews in ensureEmptyViewRemoval | Flame.CollectionView = Ember.CollectionView.extend(Flame.LayoutSupport, Flame.EventManager, {
classNames: ['flame-list-view'],
init: function() {
this._super();
var emptyViewClass = this.get('emptyView');
if (emptyViewClass) {
emptyViewClass.reopen({
// Ensures removal if orphaned, circumventing the emptyView issue
// (https://github.com/emberjs/ember.js/issues/233)
ensureEmptyViewRemoval: function() {
if (!this.get('parentView')) {
Ember.run.next(this, function() {
if (!this.get('isDestroyed')) this.remove();
});
}
}.observes('parentView')
});
}
}
});
| Flame.CollectionView = Ember.CollectionView.extend(Flame.LayoutSupport, Flame.EventManager, {
classNames: ['flame-list-view'],
init: function() {
this._super();
var emptyViewClass = this.get('emptyView');
if (emptyViewClass) {
emptyViewClass.reopen({
// Ensures removal if orphaned, circumventing the emptyView issue
// (https://github.com/emberjs/ember.js/issues/233)
ensureEmptyViewRemoval: function() {
if (!this.get('parentView')) {
Ember.run.next(this, 'remove');
}
}.observes('parentView')
});
}
}
});
|
Fix incorrect section name in Foundation shim | var buildVariable = require('./buildVariable');
var format = require('util').format;
var repeat = require('repeat-string');
/**
* Builds a complete section of the settings file, which includes a title area, and a list of variables.
* @param {string} name - The title of the section.
* @param {integer} num - The number of the section, which is added before the title text.
* @param {object[]} component - A set of SassDoc variable definitions, which contain info about each variable's name and value.
* @param {boolean} shim - If `true`, a reference to the mixin `add-foundation-colors()` is added in the "Global Stlyes" section. This is needed for the Foundation for Sites settings file to work correctly.
* @returns {string} A formatted section.
*/
module.exports = function(name, num, component, shim) {
var output = '';
var title = format('%d. %s', num, name);
output += format('// %s\n// %s\n\n', title, repeat('-', title.length));
// Iterate through each variable within the component
for (var i in component) {
output += buildVariable(component[i]);
}
if (shim && name == 'Global') {
output += '\n@include add-foundation-colors;';
}
output += '\n';
return output;
}
| var buildVariable = require('./buildVariable');
var format = require('util').format;
var repeat = require('repeat-string');
/**
* Builds a complete section of the settings file, which includes a title area, and a list of variables.
* @param {string} name - The title of the section.
* @param {integer} num - The number of the section, which is added before the title text.
* @param {object[]} component - A set of SassDoc variable definitions, which contain info about each variable's name and value.
* @param {boolean} shim - If `true`, a reference to the mixin `add-foundation-colors()` is added in the "Global Stlyes" section. This is needed for the Foundation for Sites settings file to work correctly.
* @returns {string} A formatted section.
*/
module.exports = function(name, num, component, shim) {
var output = '';
var title = format('%d. %s', num, name);
output += format('// %s\n// %s\n\n', title, repeat('-', title.length));
// Iterate through each variable within the component
for (var i in component) {
output += buildVariable(component[i]);
}
if (shim && name == 'Global Styles') {
output += '\n@include add-foundation-colors;';
}
output += '\n';
return output;
}
|
Remove table var from role | <?php namespace JWS\UserSuite;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* A role may be given various permissions.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
/**
* A role may have many users.
*/
public function users()
{
return $this->belongsToMany(config('usersuite.users.model'));
}
/**
* Grant the given permission to a role.
*
* @param Permission $permission
*
* @return mixed
*/
public function givePermission(Permission $permission)
{
return $this->permissions()->save($permission);
}
/**
* Remove the given permission to a role.
*
* @param Permission $permission
*
* @return mixed
*/
public function assignRoleTo(User $user)
{
return $this->users()->save($user);
}
}
| <?php namespace JWS\UserSuite;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
//private $usersuite = config('usersuite').'role';
protected $table = config('usersuite').'.role';
/**
* A role may be given various permissions.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
/**
* A role may have many users.
*/
public function users()
{
return $this->belongsToMany(config('usersuite.users.model'));
}
/**
* Grant the given permission to a role.
*
* @param Permission $permission
*
* @return mixed
*/
public function givePermission(Permission $permission)
{
return $this->permissions()->save($permission);
}
/**
* Remove the given permission to a role.
*
* @param Permission $permission
*
* @return mixed
*/
public function assignRoleTo(User $user)
{
return $this->users()->save($user);
}
}
|
Remove unnecessary test of collection children | import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collection.find("test_root")
assert coll.name == "test_root"
assert coll.path == '/'
assert coll.parent is None
# Make sure this is the root collection
root = Collection.get_root_collection()
assert root.id == coll.id
def test_create_with_children(self):
coll = Collection.find("test_root")
assert coll.name == "test_root"
assert coll.is_root
child1 = Collection.create(name="child1", parent=str(coll.id))
child2 = Collection.create(name="child2", parent=str(coll.id))
assert child1.get_parent_collection().id == coll.id
assert child2.get_parent_collection().id == coll.id
assert child1.path == '/child1/'
assert child2.path == '/child2/'
children = coll.get_child_collections()
assert len(children) == 2
assert coll.get_child_collection_count() == 2
| import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collection.find("test_root")
assert coll.name == "test_root"
assert coll.path == '/'
assert coll.parent is None
# Make sure this is the root collection
root = Collection.get_root_collection()
assert root.id == coll.id
def test_create_with_children(self):
coll = Collection.find("test_root")
assert coll.name == "test_root"
assert coll.is_root
child1 = Collection.create(name="child1", parent=str(coll.id))
child2 = Collection.create(name="child2", parent=str(coll.id))
assert child1.get_parent_collection().id == coll.id
assert child2.get_parent_collection().id == coll.id
assert child1.path == '/child1/'
assert child2.path == '/child2/'
children = coll.get_child_collections()
assert len(children) == 2
assert coll.get_child_collection_count() == 2
assert str(children[0].id) == str(child1.id)
assert str(children[1].id) == str(child2.id) |
Add optional authorizer parameter to session class and function. | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self, authorizer=None):
"""Preprare the connection to reddit's API.
:param authorizer: An instance of :class:`Authorizer`.
"""
self.authorizer = authorizer
self._session = requests.Session()
def __enter__(self):
"""Allow this object to be used as a context manager."""
return self
def __exit__(self, *_args):
"""Allow this object to be used as a context manager."""
self.close()
def close(self):
"""Close the session and perform any clean up."""
self._session.close()
def session(authorizer=None):
"""Return a :class:`Session` instance.
:param authorizer: An instance of :class:`Authorizer`.
"""
return Session(authorizer=authorizer)
| """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self):
"""Preprare the connection to reddit's API."""
self._session = requests.Session()
def __enter__(self):
"""Allow this object to be used as a context manager."""
return self
def __exit__(self, *_args):
"""Allow this object to be used as a context manager."""
self.close()
def close(self):
"""Close the session and perform any clean up."""
self._session.close()
def session():
"""Return a :class:`Session` instance."""
return Session()
|
Update path processing to cope with hosted DerbyNet. | <?php
session_start();
// Usage e.g. /derbynet/print.php/racer/car-tags
// ["DOCUMENT_URI"]=> "/derbynet/pack153/2019/render-document.php/racer/CarTagsDocument"
// ["SCRIPT_NAME"]=> "/derbynet/pack153/2019/render-document.php"
if (isset($_SERVER['DOCUMENT_URI']) && isset($_SERVER['SCRIPT_NAME']) &&
substr($_SERVER['DOCUMENT_URI'], 0, strlen($_SERVER['SCRIPT_NAME'])) == $_SERVER['SCRIPT_NAME']) {
$exploded = explode('/', substr($_SERVER['DOCUMENT_URI'], strlen($_SERVER['SCRIPT_NAME'])));
} else {
if (isset($_SERVER['PATH_INFO'])) {
$path_info = $_SERVER['PATH_INFO'];
} else if (isset($_SERVER['ORIG_PATH_INFO'])) {
// Rewrite rules e.g. for hosted DerbyNet may leave ORIG_PATH_INFO instead of PATH_INFO
$path_info = $_SERVER['ORIG_PATH_INFO'];
} else {
echo "Debugging \$_SERVER:\n";
var_export($_SERVER);
exit(0);
}
$exploded = explode('/', $path_info);
}
while ($exploded[0] == '') {
array_shift($exploded);
}
$inc = array_shift($exploded);
function document_class() {
global $exploded;
return $exploded[0];
}
function new_document() {
$doc_class = document_class();
return new $doc_class;
}
require_once('print/'.$inc.'.inc');
?>
| <?php
session_start();
// Usage e.g. /derbynet/print.php/racer/car-tags
if (isset($_SERVER['PATH_INFO'])) {
$path_info = $_SERVER['PATH_INFO'];
} else if (isset($_SERVER['ORIG_PATH_INFO'])) {
// Rewrite rules e.g. for hosted DerbyNet may leave ORIG_PATH_INFO instead of PATH_INFO
$path_info = $_SERVER['ORIG_PATH_INFO'];
} else {
echo "Debugging \$_SERVER:\n";
var_export($_SERVER);
exit(0);
}
$exploded = explode('/', $path_info);
while ($exploded[0] == '') {
array_shift($exploded);
}
$inc = array_shift($exploded);
function document_class() {
global $exploded;
return $exploded[0];
}
function new_document() {
$doc_class = document_class();
return new $doc_class;
}
require_once('print/'.$inc.'.inc');
?>
|
Fix user query not being returned in getBy
JWTAuth::toUser($token) was not returning a User | <?php
namespace Tymon\JWTAuth\Providers\User;
use Illuminate\Database\Eloquent\Model;
class EloquentUserAdapter implements UserInterface
{
/**
* @var \Illuminate\Database\Eloquent\Model
*/
protected $user;
/**
* Create a new User instance
*
* @param \Illuminate\Database\Eloquent\Model $user
*/
public function __construct(Model $user)
{
$this->user = $user;
}
/**
* Get the user by the given key, value
*
* @param mixed $key
* @param mixed $value
* @return Illuminate\Database\Eloquent\Model
*/
public function getBy($key, $value)
{
return $this->user->where($key, $value)->first();
}
}
| <?php
namespace Tymon\JWTAuth\Providers\User;
use Illuminate\Database\Eloquent\Model;
class EloquentUserAdapter implements UserInterface
{
/**
* @var \Illuminate\Database\Eloquent\Model
*/
protected $user;
/**
* Create a new User instance
*
* @param \Illuminate\Database\Eloquent\Model $user
*/
public function __construct(Model $user)
{
$this->user = $user;
}
/**
* Get the user by the given key, value
*
* @param mixed $key
* @param mixed $value
* @return Illuminate\Database\Eloquent\Model
*/
public function getBy($key, $value)
{
$this->user->where($key, $value)->first();
}
}
|
Prepare the schema in the ConsoleHandlerTest | <?php
declare(strict_types=1);
namespace MeetupOrganizing\Command;
use MeetupOrganizing\SchemaManager;
use MeetupOrganizing\ServiceContainer;
use PHPUnit_Framework_TestCase;
use Webmozart\Console\Args\StringArgs;
use Webmozart\Console\ConsoleApplication;
use Webmozart\Console\IO\OutputStream\BufferedOutputStream;
final class ScheduleMeetupConsoleHandlerTest extends PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_schedules_a_meetup(): void
{
$container = new ServiceContainer(getenv('PROJECT_ROOT_DIR'));
/** @var SchemaManager $schemaManager */
$schemaManager = $container[SchemaManager::class];
$schemaManager->updateSchema();
$config = new MeetupApplicationConfig($container);
$config->setTerminateAfterRun(false);
$cli = new ConsoleApplication($config);
$output = new BufferedOutputStream();
$args = new StringArgs('schedule 1 Akeneo Meetup "2018-04-20 20:00"');
$cli->run($args, null, $output);
$this->assertContains(
'Scheduled the meetup successfully',
$output->fetch()
);
}
}
| <?php
declare(strict_types=1);
namespace MeetupOrganizing\Command;
use MeetupOrganizing\ServiceContainer;
use PHPUnit_Framework_TestCase;
use Webmozart\Console\Args\StringArgs;
use Webmozart\Console\ConsoleApplication;
use Webmozart\Console\IO\OutputStream\BufferedOutputStream;
final class ScheduleMeetupConsoleHandlerTest extends PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_schedules_a_meetup(): void
{
$container = new ServiceContainer(getenv('PROJECT_ROOT_DIR'));
$config = new MeetupApplicationConfig($container);
$config->setTerminateAfterRun(false);
$cli = new ConsoleApplication($config);
$output = new BufferedOutputStream();
$args = new StringArgs('schedule 1 Akeneo Meetup "2018-04-20 20:00"');
$cli->run($args, null, $output);
$this->assertContains(
'Scheduled the meetup successfully',
$output->fetch()
);
}
}
|
Add a context processor that adds the UserProfile to each context. | from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['current_site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
context['GIT_COMMIT'] = settings.GIT_COMMIT
context['site_email'] = settings.CONTACT_EMAIL
if request.is_secure():
context['protocol'] = 'https://'
else:
context['protocol'] = 'http://'
context['current_site_url'] = (context['protocol'] +
context['current_site'].domain)
return context
def profile(request):
context = {}
if request.user.is_authenticated():
context['profile'] = request.user.get_profile()
return context
def ssl_media(request):
if request.is_secure():
ssl_media_url = settings.MEDIA_URL.replace('http://','https://')
else:
ssl_media_url = settings.MEDIA_URL
return {'MEDIA_URL': ssl_media_url}
| from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['current_site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
context['GIT_COMMIT'] = settings.GIT_COMMIT
context['site_email'] = settings.CONTACT_EMAIL
if request.is_secure():
context['protocol'] = 'https://'
else:
context['protocol'] = 'http://'
context['current_site_url'] = (context['protocol'] +
context['current_site'].domain)
return context
def ssl_media(request):
if request.is_secure():
ssl_media_url = settings.MEDIA_URL.replace('http://','https://')
else:
ssl_media_url = settings.MEDIA_URL
return {'MEDIA_URL': ssl_media_url}
|
Disable smoothing by default. Smoothing can be very expensive. | package com.rockwellcollins.atc.agree.analysis.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import com.rockwellcollins.atc.agree.analysis.Activator;
/**
* Class used to initialize default preference values.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.PREF_MODEL_CHECKER, PreferenceConstants.MODEL_CHECKER_JKIND);
store.setDefault(PreferenceConstants.PREF_SOLVER, PreferenceConstants.SOLVER_YICES);
store.setDefault(PreferenceConstants.PREF_INDUCT_CEX, true);
store.setDefault(PreferenceConstants.PREF_SMOOTH_CEX, false);
store.setDefault(PreferenceConstants.PREF_DEPTH, 200);
store.setDefault(PreferenceConstants.PREF_TIMEOUT, 100);
store.setDefault(PreferenceConstants.PREF_CONSIST_DEPTH, 1);
}
}
| package com.rockwellcollins.atc.agree.analysis.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import com.rockwellcollins.atc.agree.analysis.Activator;
/**
* Class used to initialize default preference values.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.PREF_MODEL_CHECKER, PreferenceConstants.MODEL_CHECKER_JKIND);
store.setDefault(PreferenceConstants.PREF_SOLVER, PreferenceConstants.SOLVER_YICES);
store.setDefault(PreferenceConstants.PREF_INDUCT_CEX, true);
store.setDefault(PreferenceConstants.PREF_SMOOTH_CEX, true);
store.setDefault(PreferenceConstants.PREF_DEPTH, 200);
store.setDefault(PreferenceConstants.PREF_TIMEOUT, 100);
store.setDefault(PreferenceConstants.PREF_CONSIST_DEPTH, 1);
}
}
|
Change name of start_scrapers() to be more accurate | #!/usr/bin/env python3
import subprocess
import atexit
import sys
from utils.safe_schedule import SafeScheduler
from time import sleep
from glob import glob
META_IMPORT = '# narcissa import '
scheduler = SafeScheduler()
def make_exit_graceful():
original_hook = sys.excepthook
def new_hook(type, value, traceback):
if type == KeyboardInterrupt:
sys.exit("\nBye for now!")
else:
original_hook(type, value, traceback)
sys.excepthook = new_hook
def start_server():
cmd = 'waitress-serve --port=5000 server:app'
p = subprocess.Popen(cmd.split(), cwd='server')
return p
def load_scrapers():
for scraper_path in glob('scrapers/*.py'):
with open(scraper_path) as f:
print(scraper_path)
scraper_data = f.read()
exec(scraper_data)
def main():
make_exit_graceful()
server = start_server()
atexit.register(server.terminate)
load_scrapers()
while True:
scheduler.run_pending()
sleep(1)
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import subprocess
import atexit
import sys
from utils.safe_schedule import SafeScheduler
from time import sleep
from glob import glob
META_IMPORT = '# narcissa import '
scheduler = SafeScheduler()
def make_exit_graceful():
original_hook = sys.excepthook
def new_hook(type, value, traceback):
if type == KeyboardInterrupt:
sys.exit("\nBye for now!")
else:
original_hook(type, value, traceback)
sys.excepthook = new_hook
def start_server():
cmd = 'waitress-serve --port=5000 server:app'
p = subprocess.Popen(cmd.split(), cwd='server')
return p
def start_scrapers():
for scraper_path in glob('scrapers/*.py'):
with open(scraper_path) as f:
print(scraper_path)
scraper_data = f.read()
exec(scraper_data)
def main():
make_exit_graceful()
server = start_server()
atexit.register(server.terminate)
start_scrapers()
while True:
scheduler.run_pending()
sleep(1)
if __name__ == '__main__':
main()
|
Increment version number so pip will install the newest version | #!/usr/bin/env python
from distutils.core import setup
LONG_DESCRIPTION = open('README.md', 'r').read()
setup(name='captricity-python-client',
version='0.11',
description='Python client to access Captricity API',
url='https://github.com/Captricity/captools',
author='Captricity, Inc',
author_email='support@captricity.com',
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: Linux, Mac OS X",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
],
long_description = LONG_DESCRIPTION,
packages=['captools', 'captools.api'],
package_data={'captools.api': ['img/*.png']})
| #!/usr/bin/env python
from distutils.core import setup
LONG_DESCRIPTION = open('README.md', 'r').read()
setup(name='captricity-python-client',
version='0.1',
description='Python client to access Captricity API',
url='https://github.com/Captricity/captools',
author='Captricity, Inc',
author_email='support@captricity.com',
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: Linux, Mac OS X",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
],
long_description = LONG_DESCRIPTION,
packages=['captools', 'captools.api'],
package_data={'captools.api': ['img/*.png']})
|
Print exceptions since pychromecast just ignores them | #!/usr/bin/env python3
class Listener(object):
def __init__(self):
import zmqclient
self.artist = None
self.title = None
self.pub = zmqclient.pub()
def new_media_status(self, status):
if status.artist != self.artist or status.title != self.title:
self.artist = status.artist
self.title = status.title
print("{} -- {}".format(status.artist, status.title))
if status.artist != None or status.title != None:
try:
self.pub.send(b"CHROMECAST", 2) # 2 == zmq.SNDMORE FIXME
self.pub.send_json(status.media_metadata)
except Exception as e:
print(e)
if __name__ == '__main__':
import pychromecast, time
cast = pychromecast.get_chromecast()
cast.wait()
print("Connected to {}".format(cast.device.friendly_name))
zmq = Listener()
cast.media_controller.register_status_listener(zmq)
while True:
time.sleep(30)
| #!/usr/bin/env python3
class Listener(object):
def __init__(self):
import zmqclient
self.artist = None
self.title = None
pub = zmqclient.pub()
def new_media_status(self, status):
if status.artist != self.artist or status.title != self.title:
self.artist = status.artist
self.title = status.title
print("{} -- {}".format(status.artist, status.title))
if status.artist != None or status.title != None:
pub.send(b"CHROMECAST", zmq.SNDMORE)
pub.send_json(status.media_metadata)
if __name__ == '__main__':
import pychromecast, time
cast = pychromecast.get_chromecast()
cast.wait()
print("Connected to {}".format(cast.device.friendly_name))
zmq = Listener()
cast.media_controller.register_status_listener(zmq)
while True:
time.sleep(30)
|
Add message to test failure | /*
* Copyright 2007 Russell Harmon
*
* 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.eatnumber1.util;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Russell Harmon
* @since Jul 13, 2009
*/
public class NullableTest {
private void notNull( @NotNull Object obj ) {}
@Test
public void nullable() {
try {
notNull(null);
Assert.fail("@NotNull was not enforced.");
} catch( IllegalArgumentException e ) {
// Do nothing
}
}
}
| /*
* Copyright 2007 Russell Harmon
*
* 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.eatnumber1.util;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Russell Harmon
* @since Jul 13, 2009
*/
public class NullableTest {
private void notNull( @NotNull Object obj ) {}
@Test
public void nullable() {
try {
notNull(null);
Assert.fail();
} catch( IllegalArgumentException e ) {
// Do nothing
}
}
}
|
Add TestMainPage using WebTest module | import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
class TestMainPage:
"""WebTest test for title"""
def test_main_page_returns_200(self, user, testapp):
"""Login successful."""
# Goes to homepage
res = testapp.get('/')
assert res.status_code == 200
def test_main_page_returns_expected_title(self, user, testapp):
res = testapp.get('/')
assert '<title>\n \n tdd_with_python\n \n \n </title>\n' in res
| import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
|
Remove old masonry plugin code. | module.exports = Zeppelin.CollectionView.extend({
tagName: 'ol',
className: 'cards-list list-unstyled clearfix',
subscriptions: {
'cardsList:layout': 'triggerLayout'
},
addMethod: 'prepend',
wall: null,
layoutTimer: null,
itemView: function(model) {
return require('account/views/' + model.get('type'));
},
collection: function() {
return App.Cards;
},
initialize: function() {
_.bindAll(this, ['layout']);
},
triggerLayout: function() {
this.layoutTimer = _.delay(this.layout, 1);
},
layout: function() {
if (this.collection.isEmpty()) return this;
if (!this.wall) this.wall = new freewall(this.$list);
this.wall.reset({
delay: 0,
cellW: 222,
cellH: 222,
gutterX: 15,
gutterY: 15,
animate: false,
fixSize: 0,
selector: 'li.card',
onResize: _.bind(function() {
this.wall.fitWidth();
}, this)
});
this.wall.fitWidth();
return this;
},
onRenderItems: function() {
this.triggerLayout();
},
onPrependItem: function() {
if (!this.isFirstCollectionRender()) this.triggerLayout();
},
onUnplug: function() {
clearTimeout(this.layoutTimer);
}
});
| module.exports = Zeppelin.CollectionView.extend({
tagName: 'ol',
className: 'cards-list list-unstyled clearfix',
subscriptions: {
'cardsList:layout': 'triggerLayout'
},
addMethod: 'prepend',
wall: null,
layoutTimer: null,
itemView: function(model) {
return require('account/views/' + model.get('type'));
},
collection: function() {
return App.Cards;
},
initialize: function() {
_.bindAll(this, ['layout']);
},
triggerLayout: function() {
this.layoutTimer = _.delay(this.layout, 1);
},
layout: function() {
if (this.collection.isEmpty()) return this;
if (!this.wall) this.wall = new freewall(this.$list);
this.wall.reset({
delay: 0,
cellW: 222,
cellH: 222,
gutterX: 15,
gutterY: 15,
animate: false,
fixSize: 0,
selector: 'li.card',
onResize: _.bind(function() {
this.wall.fitWidth();
}, this)
});
this.wall.fitWidth();
return this;
},
onRenderItems: function() {
this.triggerLayout();
},
onPrependItem: function() {
if (!this.isFirstCollectionRender()) this.triggerLayout();
},
onUnplug: function() {
clearTimeout(this.layoutTimer);
if (this.$list.data('masonry')) this.$list.masonry('destroy');
}
});
|
Include ObjectURL in the result for CopyObject. | <?php
namespace Aws\S3\Subscriber;
use GuzzleHttp\Command\Event\ProcessEvent;
use GuzzleHttp\Event\SubscriberInterface;
/**
* Injects ObjectURL into the result model of the PutObject operation.
*
* @internal
*/
class PutObjectUrl implements SubscriberInterface
{
public function getEvents()
{
return ['process' => ['addObjectUrl', -10]];
}
public function addObjectUrl(ProcessEvent $e)
{
if ($e->getException()) {
return;
}
$name = $e->getCommand()->getName();
if ($name === 'PutObject' || $name === 'CopyObject') {
$e->getResult()['ObjectURL'] = $e->getRequest()->getUrl();
} elseif ($name === 'CompleteMultipartUpload') {
$e->getResult()['ObjectURL'] = $e->getResult()['Location'];
}
}
}
| <?php
namespace Aws\S3\Subscriber;
use GuzzleHttp\Command\Event\ProcessEvent;
use GuzzleHttp\Event\SubscriberInterface;
/**
* Injects ObjectURL into the result model of the PutObject operation.
*
* @internal
*/
class PutObjectUrl implements SubscriberInterface
{
public function getEvents()
{
return ['process' => ['addObjectUrl', -10]];
}
public function addObjectUrl(ProcessEvent $e)
{
if ($e->getException()) {
return;
}
$name = $e->getCommand()->getName();
if ($name === 'PutObject') {
$e->getResult()['ObjectURL'] = $e->getRequest()->getUrl();
} elseif ($name === 'CompleteMultipartUpload') {
$e->getResult()['ObjectURL'] = $e->getResult()['Location'];
}
}
}
|
Switch Locale::getPrimaryLanguage to procedural style | <?php
use Carbon\Carbon;
if (!function_exists('setGlobalLocale')) {
/**
* Set locale among all localizable contexts.
*
* @param string $posixLocale
*
* @return void
*/
function setGlobalLocale($posixLocale)
{
app()->setLocale($posixLocale);
setlocale(LC_TIME, $posixLocale);
Carbon::setLocale(locale_get_primary_language($posixLocale));
}
}
if (!function_exists('isAcceptedLocale')) {
/**
* Determine if is a POSIX language string is accepted by app config.
*
* @param string $posixLocale Requested language
*
* @return bool Is an accepted language for this app
*/
function isAcceptedLocale($posixLocale)
{
return array_key_exists($posixLocale, config('languages'));
}
}
| <?php
use Carbon\Carbon;
if (!function_exists('setGlobalLocale')) {
/**
* Set locale among all localizable contexts.
*
* @param string $posixLocale
*
* @return void
*/
function setGlobalLocale($posixLocale)
{
app()->setLocale($posixLocale);
setlocale(LC_TIME, $posixLocale);
Carbon::setLocale(\Locale::getPrimaryLanguage($posixLocale));
}
}
if (!function_exists('isAcceptedLocale')) {
/**
* Determine if is a POSIX language string is accepted by app config.
*
* @param string $posixLocale Requested language
*
* @return bool Is an accepted language for this app
*/
function isAcceptedLocale($posixLocale)
{
return array_key_exists($posixLocale, config('languages'));
}
}
|
Remove 'stats' prefix from scope in lynx | var kue = require('kue'),
redis = require('redis'),
url = require('url'),
config = require('../config'),
lynx = require('lynx');
var statsDClient = null;
module.exports = {
setRedisServer: function() {
var port = config.BootstrapHtml.redis_port || process.env.REDISTOGO_URL || 6379,
host = config.BootstrapHtml.redis_host;
kue.redis.createClient = function() {
var client = redis.createClient(port, host);
console.log('Redis client created at', host, 'port', port)
return client;
};
},
getStatsClient: function() {
if (statsDClient) {
return statsDClient;
}
var host = config.BootstrapHtml.statsd_host.split('//')[1].split(':');
var serverUrl = host[0];
var serverPort = host[1];
var scope = [config.environment.type, 'bshtml'].join('.');
statsDClient = new lynx(serverUrl, serverPort, {
scope: scope
});
console.log('StatsD client created at', serverUrl, serverPort);
return statsDClient;
}
};
| var kue = require('kue'),
redis = require('redis'),
url = require('url'),
config = require('../config'),
lynx = require('lynx');
var statsDClient = null;
module.exports = {
setRedisServer: function() {
var port = config.BootstrapHtml.redis_port || process.env.REDISTOGO_URL || 6379,
host = config.BootstrapHtml.redis_host;
kue.redis.createClient = function() {
var client = redis.createClient(port, host);
console.log('Redis client created at', host, 'port', port)
return client;
};
},
getStatsClient: function() {
if (statsDClient) {
return statsDClient;
}
var host = config.BootstrapHtml.statsd_host.split('//')[1].split(':');
var serverUrl = host[0];
var serverPort = host[1];
var scope = ['stats', config.environment.type, 'bshtml'].join('.');
statsDClient = new lynx(serverUrl, serverPort, {
scope: scope
});
console.log('StatsD client created at', serverUrl, serverPort);
return statsDClient;
}
};
|
Break dependency on "testing" package
Importing the "testing" standard library package automatically registers the
testing commandline flags. This side effect cluttered up the output of --help
for any program that imported msgp.
I replaced the dependency on testing.B with an interface containing the required
methods. | package msgp
type timer interface {
StartTimer()
StopTimer()
}
// EndlessReader is an io.Reader
// that loops over the same data
// endlessly. It is used for benchmarking.
type EndlessReader struct {
tb timer
data []byte
offset int
}
// NewEndlessReader returns a new endless reader
func NewEndlessReader(b []byte, tb timer) *EndlessReader {
return &EndlessReader{tb: tb, data: b, offset: 0}
}
// Read implements io.Reader. In practice, it
// always returns (len(p), nil), although it
// fills the supplied slice while the benchmark
// timer is stopped.
func (c *EndlessReader) Read(p []byte) (int, error) {
c.tb.StopTimer()
var n int
l := len(p)
m := len(c.data)
for n < l {
nn := copy(p[n:], c.data[c.offset:])
n += nn
c.offset += nn
c.offset %= m
}
c.tb.StartTimer()
return n, nil
}
| package msgp
import (
"testing"
)
// EndlessReader is an io.Reader
// that loops over the same data
// endlessly. It is used for benchmarking.
type EndlessReader struct {
tb *testing.B
data []byte
offset int
}
// NewEndlessReader returns a new endless reader
func NewEndlessReader(b []byte, tb *testing.B) *EndlessReader {
return &EndlessReader{tb: tb, data: b, offset: 0}
}
// Read implements io.Reader. In practice, it
// always returns (len(p), nil), although it
// fills the supplied slice while the benchmark
// timer is stopped.
func (c *EndlessReader) Read(p []byte) (int, error) {
c.tb.StopTimer()
var n int
l := len(p)
m := len(c.data)
for n < l {
nn := copy(p[n:], c.data[c.offset:])
n += nn
c.offset += nn
c.offset %= m
}
c.tb.StartTimer()
return n, nil
}
|
Return resource on PUT /api/v1/clusters/:name | package handlers
import (
"github.com/go-openapi/runtime/middleware"
"github.com/sapcc/kubernikus/pkg/api"
"github.com/sapcc/kubernikus/pkg/api/models"
"github.com/sapcc/kubernikus/pkg/api/rest/operations"
"github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
)
func NewUpdateCluster(rt *api.Runtime) operations.UpdateClusterHandler {
return &updateCluster{rt}
}
type updateCluster struct {
*api.Runtime
}
func (d *updateCluster) Handle(params operations.UpdateClusterParams, principal *models.Principal) middleware.Responder {
kluster, err := editCluster(d.Kubernikus.Kubernikus().Klusters(d.Namespace), principal, params.Name, func(kluster *v1.Kluster) {
//TODO: currently no field to update
})
if err != nil {
if apierrors.IsNotFound(err) {
return NewErrorResponse(&operations.UpdateClusterDefault{}, 404, "Not found")
}
return NewErrorResponse(&operations.UpdateClusterDefault{}, 500, err.Error())
}
return operations.NewUpdateClusterOK().WithPayload(clusterModelFromTPR(kluster))
}
| package handlers
import (
"github.com/go-openapi/runtime/middleware"
"github.com/sapcc/kubernikus/pkg/api"
"github.com/sapcc/kubernikus/pkg/api/models"
"github.com/sapcc/kubernikus/pkg/api/rest/operations"
"github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
)
func NewUpdateCluster(rt *api.Runtime) operations.UpdateClusterHandler {
return &updateCluster{rt}
}
type updateCluster struct {
*api.Runtime
}
func (d *updateCluster) Handle(params operations.UpdateClusterParams, principal *models.Principal) middleware.Responder {
_, err := editCluster(d.Kubernikus.Kubernikus().Klusters(d.Namespace), principal, params.Name, func(kluster *v1.Kluster) {
//TODO: currently no field to update
})
if err != nil {
if apierrors.IsNotFound(err) {
return NewErrorResponse(&operations.UpdateClusterDefault{}, 404, "Not found")
}
return NewErrorResponse(&operations.UpdateClusterDefault{}, 500, err.Error())
}
return operations.NewUpdateClusterOK()
}
|
Fix test for getAuthBlurb() result | import test from 'ava'
import authenticator from '../src/authenticator'
import testUsers from './util/testUsers'
function localUsersRepository () {
return {
getUser(id) {
const result = testUsers.find((user) => user.id === id)
if (!result) {
return Promise.reject(new Error('User not found'))
}
return Promise.resolve(result)
}
}
}
function make () {
return authenticator({
secret: 'TEST',
users: localUsersRepository()
})
}
test('getAuthBlurb promises a string', async (t) => {
const auth = make()
const user = testUsers[0]
const promise = auth.getAuthBlurb(user.id)
t.is(typeof promise.then, 'function')
const result = await promise
t.is(typeof result, 'object')
t.is(typeof result.blurb, 'string')
})
| import test from 'ava'
import authenticator from '../src/authenticator'
import testUsers from './util/testUsers'
function localUsersRepository () {
return {
getUser(id) {
const result = testUsers.find((user) => user.id === id)
if (!result) {
return Promise.reject(new Error('User not found'))
}
return Promise.resolve(result)
}
}
}
function make () {
return authenticator({
secret: 'TEST',
users: localUsersRepository()
})
}
test('getAuthBlurb promises a string', async (t) => {
const auth = make()
const user = testUsers[0]
const promise = auth.getAuthBlurb(user.id)
t.true(promise instanceof Promise)
const result = await promise
t.is(typeof result, 'object')
t.is(typeof result.blurb, 'string')
})
|
Add useStrict to the blacklist.
Ember-CLI does this automatically. | var Transpiler = require('./transpiler');
module.exports = {
name: 'ember-cli-6to5',
included: function(app) {
this._super.included.apply(this, arguments);
var options = getOptions(app.options['6to5']);
var plugin = {
name: 'ember-cli-6to5',
ext: 'js',
toTree: function(tree) {
return new Transpiler(tree, options);
}
};
app.registry.add('js', plugin);
}
};
function getOptions(options) {
options = options || {};
// Ensure modules aren't compiled unless explicitly set to compile
options.blacklist = options.blacklist || ['modules'];
if (options.compileModules === true) {
if (options.blacklist.indexOf('modules') >= 0) {
options.blacklist.splice(options.indexOf('modules'), 1);
}
} else {
if (options.blacklist.indexOf('modules') < 0) {
options.blacklist.push('modules');
}
}
// Ember-CLI inserts its own 'use strict' directive
options.blacklist.push('useStrict');
return options;
} | var Transpiler = require('./transpiler');
module.exports = {
name: 'ember-cli-6to5',
included: function(app) {
this._super.included.apply(this, arguments);
var options = getOptions(app.options['6to5']);
var plugin = {
name: 'ember-cli-6to5',
ext: 'js',
toTree: function(tree) {
return new Transpiler(tree, options);
}
};
app.registry.add('js', plugin);
}
};
function getOptions(options) {
options = options || {};
// Ensure modules aren't compiled unless explicitly set to compile
options.blacklist = options.blacklist || ['modules'];
if (options.compileModules === true) {
if (options.blacklist.indexOf('modules') >= 0) {
options.blacklist.splice(options.indexOf('modules'), 1);
}
} else {
if (options.blacklist.indexOf('modules') < 0) {
options.blacklist.push('modules');
}
}
return options;
} |
Read hits and misses stats | package main
import (
log "github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
"github.com/siebenmann/go-kstat"
"net/http"
"time"
)
func collectARCstats() {
log.Debugf("Start collecting ARC stats")
token, err := kstat.Open()
if err != nil {
log.Fatalf("Open failure: %s", err)
}
for {
log.Debugf("Collecting...")
ks, err := token.Lookup("zfs", 0, "arcstats")
if err != nil {
log.Fatalf("lookup failure on %s:0:%s: %s", "zfs", "arcstats", err)
}
log.Debugf("Collected: %v", ks)
n, err := ks.GetNamed("hits")
if err != nil {
log.Fatalf("getting '%s' from %s: %s", "hits", ks, err)
}
log.Debugf("Hits: %v", n)
n, err = ks.GetNamed("misses")
if err != nil {
log.Fatalf("getting '%s' from %s: %s", "misses", ks, err)
}
log.Debugf("Misses: %v", n)
time.Sleep(10 * time.Second)
}
}
func main() {
log.SetLevel(log.DebugLevel)
log.Debugf("Starting")
go collectARCstats()
http.Handle("/metrics", prometheus.Handler())
err := http.ListenAndServe("0.0.0.0:9102", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
| package main
import (
log "github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
"github.com/siebenmann/go-kstat"
"net/http"
"time"
)
func collectARCstats() {
log.Debugf("Start collecting ARC stats")
token, err := kstat.Open()
if err != nil {
log.Fatalf("Open failure: %s", err)
}
for {
log.Debugf("Collecting...")
ks, err := token.Lookup("zfs", 0, "arcstats")
if err != nil {
log.Fatalf("lookup failure on %s:0:%s: %s", "zfs", "arcstats", err)
}
log.Debugf("Collected: %v", ks)
time.Sleep(10 * time.Second)
}
}
func main() {
log.SetLevel(log.DebugLevel)
log.Debugf("Starting")
go collectARCstats()
http.Handle("/metrics", prometheus.Handler())
err := http.ListenAndServe("0.0.0.0:9102", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
|
Remove extra header for actions, built in | import Ember from 'ember';
export default Ember.Controller.extend({
settings: Ember.inject.service(),
sortBy: 'name',
headers: [
{
translationKey: 'generic.state',
name: 'state',
sort: ['stateSort','name','id'],
width: '121'
},
{
translationKey: 'generic.name',
name: 'name',
sort: ['name','id'],
},
{
translationKey: 'hookPage.fields.kind.label',
name: 'kind',
sort: ['displayKind','id'],
},
{
translationKey: 'hookPage.fields.detail.label',
},
{
translationKey: 'hookPage.fields.url.label',
width: '100'
},
],
});
| import Ember from 'ember';
export default Ember.Controller.extend({
settings: Ember.inject.service(),
sortBy: 'name',
headers: [
{
translationKey: 'generic.state',
name: 'state',
sort: ['stateSort','name','id'],
width: '121'
},
{
translationKey: 'generic.name',
name: 'name',
sort: ['name','id'],
},
{
translationKey: 'hookPage.fields.kind.label',
name: 'kind',
sort: ['displayKind','id'],
},
{
translationKey: 'hookPage.fields.detail.label',
},
{
translationKey: 'hookPage.fields.url.label',
width: '100'
},
{
width: '75'
},
],
});
|
Revert initE back to init, since change was breaking lots of things. | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable 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.
*/
foam.CLASS({
package: 'foam.u2.stack',
name: 'StackView',
extends: 'foam.u2.View',
requires: [
'foam.u2.stack.Stack'
],
exports: [ 'data as stack' ],
properties: [
{
name: 'data',
factory: function() { return this.Stack.create(); }
},
{
class: 'Boolean',
name: 'showActions',
value: true
}
],
methods: [
// TODO: Why is this init() instead of initE()? Investigate and maybe fix.
function init() {
this.setNodeName('div');
if ( this.showActions )
this.add(this.Stack.BACK, this.Stack.FORWARD);
this.add(this.slot(function(s) {
return foam.u2.ViewSpec.createView(s, null, this, this.__subSubContext__);
}, this.data$.dot('top')));
}
]
});
| /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable 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.
*/
foam.CLASS({
package: 'foam.u2.stack',
name: 'StackView',
extends: 'foam.u2.View',
requires: [
'foam.u2.stack.Stack'
],
exports: [ 'data as stack' ],
properties: [
{
name: 'data',
factory: function() { return this.Stack.create(); }
},
{
class: 'Boolean',
name: 'showActions',
value: true
}
],
methods: [
function initE() {
this.setNodeName('div');
if ( this.showActions )
this.add(this.Stack.BACK, this.Stack.FORWARD);
this.add(this.slot(function(s) {
return foam.u2.ViewSpec.createView(s, null, this, this.__subSubContext__);
}, this.data$.dot('top')));
}
]
});
|
Fix unique contraint in capability | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Capability(entity.Entity, db.Model):
attributes = ['id', 'name', 'url', 'method']
name = db.Column(db.String(30), nullable=False)
url = db.Column(db.String(100), nullable=False)
method = db.Column(db.String(10), nullable=False)
__table_args__ = (UniqueConstraint('url', 'method', name='capability_uk'),)
def __init__(self, id, name, url, method):
super(Capability, self).__init__(id)
self.name = name
self.url = url
self.method = method
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Capability(entity.Entity, db.Model):
attributes = ['id', 'name', 'url', 'method']
name = db.Column(db.String(30), nullable=False)
url = db.Column(db.String(100), nullable=False)
method = db.Column(db.String(10), nullable=False)
UniqueConstraint('url', 'method', name='capability_uk')
def __init__(self, id, name, url, method):
super(Capability, self).__init__(id)
self.name = name
self.url = url
self.method = method
|
Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8c | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
core.skip_ok_unless_installed('condor-cron')
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
self.skip_ok('already running')
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
| import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
if core.missing_rpm('condor-cron'):
return
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
core.skip('already running')
return
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
|
Replace <> operator to make code compatible with JDK 1.6 | package org.apache.cordova.firebase;
import com.google.firebase.messaging.RemoteMessage;
import java.util.ArrayList;
import java.util.List;
public class FirebasePluginMessageReceiverManager {
private static List<FirebasePluginMessageReceiver> receivers = new ArrayList<FirebasePluginMessageReceiver>();
public static void register(FirebasePluginMessageReceiver receiver){
receivers.add(receiver);
}
public static boolean onMessageReceived(RemoteMessage remoteMessage){
boolean handled = false;
for(FirebasePluginMessageReceiver receiver : receivers){
boolean wasHandled = receiver.onMessageReceived(remoteMessage);
if(wasHandled){
handled = true;
}
}
return handled;
}
}
| package org.apache.cordova.firebase;
import com.google.firebase.messaging.RemoteMessage;
import java.util.ArrayList;
import java.util.List;
public class FirebasePluginMessageReceiverManager {
private static List<FirebasePluginMessageReceiver> receivers = new ArrayList<>();
public static void register(FirebasePluginMessageReceiver receiver){
receivers.add(receiver);
}
public static boolean onMessageReceived(RemoteMessage remoteMessage){
boolean handled = false;
for(FirebasePluginMessageReceiver receiver : receivers){
boolean wasHandled = receiver.onMessageReceived(remoteMessage);
if(wasHandled){
handled = true;
}
}
return handled;
}
}
|
Use %v instead of %p to calm vet
Signed-off-by: Alexander Morozov <4efb7da3e38416208b41d8021a942884d8a9435c@docker.com> | package setup
import (
"fmt"
"net/http"
"strings"
"github.com/mholt/caddy/config/parse"
"github.com/mholt/caddy/middleware"
"github.com/mholt/caddy/server"
)
// NewTestController creates a new *Controller for
// the input specified, with a filename of "Testfile"
func NewTestController(input string) *Controller {
return &Controller{
Config: &server.Config{},
Dispenser: parse.NewDispenser("Testfile", strings.NewReader(input)),
}
}
// EmptyNext is a no-op function that can be passed into
// middleware.Middleware functions so that the assignment
// to the Next field of the Handler can be tested.
var EmptyNext = middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
return 0, nil
})
// SameNext does a pointer comparison between next1 and next2.
func SameNext(next1, next2 middleware.Handler) bool {
return fmt.Sprintf("%v", next1) == fmt.Sprintf("%v", next2)
}
| package setup
import (
"fmt"
"net/http"
"strings"
"github.com/mholt/caddy/config/parse"
"github.com/mholt/caddy/middleware"
"github.com/mholt/caddy/server"
)
// NewTestController creates a new *Controller for
// the input specified, with a filename of "Testfile"
func NewTestController(input string) *Controller {
return &Controller{
Config: &server.Config{},
Dispenser: parse.NewDispenser("Testfile", strings.NewReader(input)),
}
}
// EmptyNext is a no-op function that can be passed into
// middleware.Middleware functions so that the assignment
// to the Next field of the Handler can be tested.
var EmptyNext = middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
return 0, nil
})
// SameNext does a pointer comparison between next1 and next2.
func SameNext(next1, next2 middleware.Handler) bool {
return fmt.Sprintf("%p", next1) == fmt.Sprintf("%p", next2)
}
|
Fix warning for "undefined variable: user" | <?php namespace Watson\Autologin;
use Auth, Redirect;
use Illuminate\Routing\Controller;
use Watson\Autologin\Interfaces\AuthenticationInterface;
use Watson\Autologin\Interfaces\AutologinInterface;
class AutologinController extends Controller {
/**
* AuthenticationInterface provider instance.
*
* @var \Studious\Autologin\Interfaces\AuthenticationInterface
*/
protected $provider;
/**
* Studious Autologin instance.
*
* @var \Studious\Autologin\Autologin
*/
protected $autologin;
/**
* Instantiate the controller.
*/
public function __construct(AuthenticationInterface $authProvider, Autologin $autologin)
{
$this->authProvider = $authProvider;
$this->autologin = $autologin;
}
/**
* Process the autologin token and perform the redirect.
*/
public function autologin($token)
{
if ($autologin = $this->autologin->validate($token))
{
// Active token found, login the user and redirect to the
// intended path.
if ($user = $this->authProvider->loginUsingId($autologin->getUserId()))
{
return Redirect::to($autologin->getPath());
}
}
// Token was invalid, redirect back to the home page.
return Redirect::to('/');
}
} | <?php namespace Watson\Autologin;
use Auth, Redirect;
use Illuminate\Routing\Controller;
use Watson\Autologin\Interfaces\AuthenticationInterface;
use Watson\Autologin\Interfaces\AutologinInterface;
class AutologinController extends Controller {
/**
* AuthenticationInterface provider instance.
*
* @var \Studious\Autologin\Interfaces\AuthenticationInterface
*/
protected $provider;
/**
* Studious Autologin instance.
*
* @var \Studious\Autologin\Autologin
*/
protected $autologin;
/**
* Instantiate the controller.
*/
public function __construct(AuthenticationInterface $authProvider, Autologin $autologin)
{
$this->authProvider = $authProvider;
$this->autologin = $autologin;
}
/**
* Process the autologin token and perform the redirect.
*/
public function autologin($token)
{
if ($autologin = $this->autologin->validate($token))
{
// Active token found, login the user and redirect to the
// intended path.
$user = $this->authProvider->loginUsingId($autologin->getUserId());
}
if ($user)
{
return Redirect::to($autologin->getPath());
}
// Token was invalid, redirect back to the home page.
return Redirect::to('/');
}
} |
Test Class Update: Change UIScope => VaadinUIScope | package org.vaadin.spring.mvp.autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.annotation.VaadinComponent;
import org.vaadin.spring.annotation.VaadinUIScope;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
import org.vaadin.spring.mvp.FooView;
import org.vaadin.spring.mvp.Presenter;
@VaadinUIScope
@VaadinComponent
public class AutowiredPresenter extends Presenter<FooView> {
@Autowired
public AutowiredPresenter(FooView view, EventBus eventBus) {
super(view, eventBus);
}
@EventBusListenerMethod
public void onNewCaption(String caption) {
getView().setCaption(caption);
}
}
| package org.vaadin.spring.mvp.autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.UIScope;
import org.vaadin.spring.annotation.VaadinComponent;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
import org.vaadin.spring.mvp.FooView;
import org.vaadin.spring.mvp.Presenter;
@UIScope
@VaadinComponent
public class AutowiredPresenter extends Presenter<FooView> {
@Autowired
public AutowiredPresenter(FooView view, EventBus eventBus) {
super(view, eventBus);
}
@EventBusListenerMethod
public void onNewCaption(String caption) {
getView().setCaption(caption);
}
}
|
Reimplement CompositeDocumentationProvider building so that it can be cached
GitOrigin-RevId: 424ed3d9dd2e37601eb808304b2c91db795e9f94 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* @author max
*/
package com.intellij.lang;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProvider;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class LanguageDocumentation extends LanguageExtension<DocumentationProvider> {
public static final LanguageDocumentation INSTANCE = new LanguageDocumentation();
private LanguageDocumentation() {
super("com.intellij.lang.documentationProvider");
}
/**
* This method is left to preserve binary compatibility.
*/
@Override
public DocumentationProvider forLanguage(@NotNull final Language l) {
return super.forLanguage(l);
}
@Override
protected DocumentationProvider findForLanguage(@NotNull Language language) {
final List<DocumentationProvider> providers = allForLanguage(language);
if (providers.size() < 2) {
return super.findForLanguage(language);
}
return CompositeDocumentationProvider.wrapProviders(providers);
}
}
| /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* @author max
*/
package com.intellij.lang;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProvider;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class LanguageDocumentation extends LanguageExtension<DocumentationProvider> {
public static final LanguageDocumentation INSTANCE = new LanguageDocumentation();
private LanguageDocumentation() {
super("com.intellij.lang.documentationProvider");
}
@Override
public DocumentationProvider forLanguage(@NotNull final Language l) {
final List<DocumentationProvider> providers = allForLanguage(l);
if (providers.size() < 2) {
return super.forLanguage(l);
}
return CompositeDocumentationProvider.wrapProviders(providers);
}
}
|
Move documark-cache dependency to top of the document. Check for head container | var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
var cacheHelper = require('documark-cache');
module.exports = function dmpSass ($, document, done) {
sass.render({
file: 'assets/css/style.scss',
outputStyle: 'compressed',
sourceMap: false,
success: function (result) {
var cache = cacheHelper(document);
var file = cache.fileWriteStream('sass-cache.css');
var container = $.('head');
if ( !container.length ) {
container = $.root();
}
file.end(result.css);
container.append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
done();
},
error: function (error) {
done(error.message);
}
});
};
| var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
module.exports = function dmpSass ($, document, done) {
sass.render({
file: 'assets/css/style.scss',
outputStyle: 'compressed',
sourceMap: false,
success: function (result) {
var cache = require('documark-cache')(document);
var file = cache.fileWriteStream('sass-cache.css');
file.end(result.css);
$.root().append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
},
error: function (error) {
console.log(error.message);
}
});
done();
};
|
Remove cache dependency from codebase | <?php
namespace Janitor\Models;
use Illuminate\Cache\Repository;
use Symfony\Component\Finder\Finder;
/**
* The user's codebase
*
* @author Maxime Fabre <ehtnam6@gmail.com>
*/
class Codebase
{
/**
* The files that are part of the codebase
*
* @type SplFileInfo[]
*/
protected $files = [];
/**
* Serialized version of the codebase
*
* @type string[]
*/
protected $serialized;
/**
* Build a new codebase
*/
public function __construct()
{
$finder = new Finder();
$files = $finder->files()->name('/\.(php|twig)$/')->in(app_path());
$files = iterator_to_array($files);
$this->files = $files;
}
/**
* Get a serialized version of the codebase
*
* @return string[]
*/
public function getSerialized()
{
if (!$this->serialized) {
foreach ($this->files as $key => $file) {
$this->serialized[$file->getBasename()] = $file->getContents();
}
}
return $this->serialized;
}
}
| <?php
namespace Janitor\Models;
use Illuminate\Cache\Repository;
use Symfony\Component\Finder\Finder;
/**
* The user's codebase
*
* @author Maxime Fabre <ehtnam6@gmail.com>
*/
class Codebase
{
/**
* @type Repository
*/
private $cache;
/**
* @type SplFileInfo[]
*/
protected $files = [];
/**
* Build a new codebase
*
* @param Repository $cache
*/
public function __construct(Repository $cache)
{
$finder = new Finder();
$files = $finder->files()->name('/\.(php|twig)$/')->in(app_path());
$files = iterator_to_array($files);
$this->files = $files;
$this->cache = $cache;
}
/**
* Get a serialized version of the codebase
*
* @return string
*/
public function getSerialized()
{
$contents = [];
foreach ($this->files as $key => $file) {
$contents[$file->getBasename()] = $file->getContents();
}
return $contents;
}
}
|
Allow hyphens in referenced key names | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Locale;
use Symfony\Component\Translation\Loader\YamlFileLoader as BaseYamlFileLoader;
use Symfony\Component\Translation\MessageCatalogueInterface;
class YamlFileLoader extends BaseYamlFileLoader
{
/**
* {@inheritdoc}
*/
public function load($resource, $locale, $domain = 'messages')
{
$messages = parent::load($resource, $locale, $domain);
foreach ($messages->all($domain) as $id => $translation) {
$messages->set($id, $this->getTranslation($messages, $id, $domain));
}
return $messages;
}
private function getTranslation(MessageCatalogueInterface $messages, $id, $domain)
{
$translation = $messages->get($id, $domain);
if (preg_match('/^=>\s*([a-z0-9_\-\.]+)$/i', $translation, $matches)) {
return $this->getTranslation($messages, $matches[1], $domain);
}
return $translation;
}
}
| <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Locale;
use Symfony\Component\Translation\Loader\YamlFileLoader as BaseYamlFileLoader;
use Symfony\Component\Translation\MessageCatalogueInterface;
class YamlFileLoader extends BaseYamlFileLoader
{
/**
* {@inheritdoc}
*/
public function load($resource, $locale, $domain = 'messages')
{
$messages = parent::load($resource, $locale, $domain);
foreach ($messages->all($domain) as $id => $translation) {
$messages->set($id, $this->getTranslation($messages, $id, $domain));
}
return $messages;
}
private function getTranslation(MessageCatalogueInterface $messages, $id, $domain)
{
$translation = $messages->get($id, $domain);
if (preg_match('/^=>\s*([a-z0-9_\.]+)$/i', $translation, $matches)) {
return $this->getTranslation($messages, $matches[1], $domain);
}
return $translation;
}
}
|
Fix file path to the cloud-config template | // Copyright (c) 2014 The Virtual Vulcano authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE.md file.
'use strict';
var fs = require('fs'),
_ = require('lodash'),
Q = require('q'),
childProccessPromise = require('child-process-promise');
module.exports = {
create: function (clusterId) {
return Q.nfcall(fs.stat, '/root/.ssh/id_rsa')
.fail(function () {
return childProccessPromise.exec('ssh-keygen -t rsa -N "" -f /root/.ssh/id_rsa');
})
.then(function () {
return Q.all([
Q.nfcall(fs.readFile, '/web/app/assets/cloud-config.tmpl.yml', 'utf-8'),
Q.nfcall(fs.readFile, '/root/.ssh/id_rsa.pub', 'utf-8'),
]);
})
.then(function (result) {
var template = result[0];
var sshKey = result[1];
return _.template(template, {
clusterId: clusterId,
sshKey: sshKey,
});
});
},
};
| // Copyright (c) 2014 The Virtual Vulcano authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE.md file.
'use strict';
var fs = require('fs'),
_ = require('lodash'),
Q = require('q'),
childProccessPromise = require('child-process-promise');
module.exports = {
create: function (clusterId) {
return Q.nfcall(fs.stat, '/root/.ssh/id_rsa')
.fail(function () {
return childProccessPromise.exec('ssh-keygen -t rsa -N "" -f /root/.ssh/id_rsa');
})
.then(function () {
return Q.all([
Q.nfcall(fs.readFile, '/web/web/assets/cloud-config.tmpl.yml', 'utf-8'),
Q.nfcall(fs.readFile, '/root/.ssh/id_rsa.pub', 'utf-8'),
]);
})
.then(function (result) {
var template = result[0];
var sshKey = result[1];
return _.template(template, {
clusterId: clusterId,
sshKey: sshKey,
});
});
},
};
|
Fix script to update offering on instances | # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan)
strong_offering = infra_offering.offering
weaker_offering = plan_attr.get_weaker_offering()
for instance in infra_offering.databaseinfra.instances.all():
if instance.is_database:
instance.offering = strong_offering
else:
instance.oferring = weaker_offering
instance.save()
| # coding: utf-8
class UpdateInstances(object):
@staticmethod
def do():
from dbaas_cloudstack.models import DatabaseInfraOffering
from dbaas_cloudstack.models import PlanAttr
infra_offerings = DatabaseInfraOffering.objects.all()
for infra_offering in infra_offerings:
plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan)
strong_offering = infra_offering.offering
weaker_offering = plan_attr.get_weaker_offering()
for instance in infra_offering.databaseinfra.instances.all():
if instance.is_database:
instance.offering = weaker_offering
else:
instance.oferring = strong_offering
instance.save()
|
Remove alias from service provider.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Support;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class MessagesServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.messages', function () {
return new Messages;
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$app = $this->app;
$app->after(function () use ($app) {
$app['orchestra.messages']->save();
});
}
}
| <?php namespace Orchestra\Support;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class MessagesServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.messages', function () {
return new Messages;
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Messages', 'Orchestra\Support\Facades\Messages');
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$app = $this->app;
$app->after(function () use ($app) {
$app['orchestra.messages']->save();
});
}
}
|
Fix config file loading in prod | <?php
/*
* This file is part of the EmharCqrsInfrastructure bundle.
*
* (c) Emmanuel Harleaux
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Emhar\CqrsInfrastructureBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration.
*
* @link http://symfony.com/doc/current/cookbook/bundles/extension.html
*/
class EmharCqrsInfrastructureExtension extends Extension
{
/**
* {@inheritdoc}
* @throws \Exception
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
$loader->load('commands.yml');
if ($container->getParameter('kernel.debug')) {
$loader->load('datacollector.yml');
}
}
}
| <?php
/*
* This file is part of the EmharCqrsInfrastructure bundle.
*
* (c) Emmanuel Harleaux
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Emhar\CqrsInfrastructureBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration.
*
* @link http://symfony.com/doc/current/cookbook/bundles/extension.html
*/
class EmharCqrsInfrastructureExtension extends Extension
{
/**
* {@inheritdoc}
* @throws \Exception
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
if ($container->getParameter('kernel.debug')) {
$loader->load('datacollector.yml');
$loader->load('commands.yml');
}
}
}
|
Frontend: Refactor places module – use controller as mediator to decouple the components. | Teikei.module("Places", function(Places, App, Backbone, Marionette, $, _) {
Places.Controller = Backbone.Marionette.Controller.extend( {
initialize: function(){
this.collection = new Teikei.Places.Collection();
this.mapView = new Teikei.Places.MapView({
collection: this.collection
});
this.collection.fetch();
this.mapView.bind("marker:select", this.openTip);
App.mainRegion.show(this.mapView);
},
openTip: function(marker) {
var mapItemView = new Places.MapItemView({model: marker.model});
mapItemView.render();
marker.bindPopup(mapItemView.el).openPopup();
}
})
})
| Teikei.module("Places", function(Places, App, Backbone, Marionette, $, _) {
Places.Controller = Backbone.Marionette.Controller.extend( {
initialize: function(){
this.collection = new Teikei.Places.Collection();
this.mapView = new Teikei.Places.MapView({
collection: this.collection
});
this.collection.fetch();
//this.mapView.bind("marker:select", this.openTip);
App.mainRegion.show(this.mapView);
},
openTip: function(marker) {
var mapItemView = new Places.MapItemView({model: marker.model});
mapItemView.render();
marker.bindPopup(mapItemView.el).openPopup();
}
})
})
|
Simplify log messages in bioentities/buildIndex/status | package uk.ac.ebi.atlas.model.resource;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public abstract class AtlasResource<T> {
protected final Path path;
AtlasResource(Path path) {
this.path = path;
}
public boolean exists() {
return Files.exists(path);
}
public boolean existsAndIsNonEmpty() {
return exists() && (
path.toFile().isDirectory()
? path.toFile().list().length > 0
: path.toFile().length() > 0
);
}
public boolean isReadable() {
return Files.isReadable(path);
}
public abstract T get();
public Reader getReader() throws IOException {
return Files.newBufferedReader(path, StandardCharsets.UTF_8);
}
public long size() {
return path.toFile().length();
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " with path " + path.toString();
}
}
| package uk.ac.ebi.atlas.model.resource;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public abstract class AtlasResource<T> {
protected final Path path;
AtlasResource(Path path) {
this.path = path;
}
public boolean exists() {
return Files.exists(path);
}
public boolean existsAndIsNonEmpty() {
return exists() && (
path.toFile().isDirectory()
? path.toFile().list().length > 0
: path.toFile().length() > 0
);
}
public boolean isReadable() {
return Files.isReadable(path);
}
public abstract T get();
public Reader getReader() throws IOException {
return Files.newBufferedReader(path, StandardCharsets.UTF_8);
}
public long size() {
return path.toFile().length();
}
@Override
public String toString() {
return this.getClass().getName() + " with path " + path.toString();
}
}
|
Fix typo in the reverseBytes function comment | // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package strings
// reverseBytes reverse elements of a[s:e] in a.
func reverseBytes(a []byte, s, e int) {
for e > s {
a[s], a[e] = a[e], a[s]
s++
e--
}
}
// ReverseWords returns a new string containing the words from s in reverse order.
func ReverseWords(s string) string {
r := []byte(s)
reverseBytes(r, 0, len(s)-1) // Reverse whole sentence.
p := 0
for q := p; q < len(r); q++ { // Reverse each world in the reversed sentence.
if r[q] == ' ' {
reverseBytes(r, p, q-1) // q-1 exclude the ' ' character from reversal.
p = q + 1
}
}
reverseBytes(r, p, len(r)-1) // Reverse the last word.
return string(r)
}
| // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package strings
// reverseBytes reverse elements of a[s:e] in a.
func reverseBytes(a []byte, s, e int) {
for e > s {
a[s], a[e] = a[e], a[s]
s++
e--
}
}
// ReverseWords returns a new string containing the words from s in reverse order.
func ReverseWords(s string) string {
r := []byte(s)
reverseBytes(r, 0, len(s)-1) // Reverse whole sentence.
p := 0
for q := p; q < len(r); q++ { // Reverse each world in the reversed sentence.
if r[q] == ' ' {
reverseBytes(r, p, q-1) // q-1 exclude the ' ' character from reversal.
p = q + 1
}
}
reverseBytes(r, p, len(r)-1) // Reverse the last world.
return string(r)
}
|
Remove unused variables. Fix nesting bug. | /**
* jQuery if-else plugin
*
* Creates if(), else() and fi() methods that can be used in
* a chain of methods on jQuery objects
*
* @author Vegard Løkken <vegard@headspin.no>
* @copyright 2013
* @version 0.3
* @licence MIT
*/
;(function( $ ) {
/* Undef object that all chained jQuery methods work on
* if they should not be executed */
var $undef = $();
/* The original object is stored here so we can restore
* it later */
var orig;
$.fn["if"] = function(condition) {
if (this === $undef) {
return $();
} else {
orig = this;
return !!condition ? this : $undef;
}
};
$.fn["else"] = function() {
if (orig === undefined)
throw "else() can't be used before if()";
return this === $undef ? orig : $undef;
};
$.fn["fi"] = function() {
if (orig === undefined)
throw "fi() can't be used before if()";
return orig;
};
})(jQuery);
| /**
* jQuery if-else plugin
*
* Creates if(), else() and fi() methods that can be used in
* a chain of methods on jQuery objects
*
* @author Vegard Løkken <vegard@headspin.no>
* @copyright 2013
* @version 0.2
* @licence MIT
*/
;(function( $ ) {
/* Undef object that all chained jQuery methods work on
* if they should not be executed */
var $undef = $();
/* The original object is stored here so we can restore
* it later */
var orig;
/* We store the condition given in the if() method */
var condition;
$.fn["if"] = function(options) {
orig = this;
condition = !!options;
if (!condition) {
return $undef;
} else {
return this;
}
};
$.fn["else"] = function( options) {
if (orig === undefined)
throw "else() can't be used before if()";
return this === $undef ? orig : $undef;
};
$.fn["fi"] = function(options) {
if (orig === undefined)
throw "fi() can't be used before if()";
return orig;
};
})(jQuery);
|
api/clubs/list/test: Use `pytest-voluptuous` to simplify JSON compare code | from pytest_voluptuous import S
from voluptuous.validators import ExactSequence
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == S(
{
"clubs": ExactSequence(
[
{"id": int, "name": "LV Aachen"},
{"id": int, "name": "Sportflug Niederberg"},
]
)
}
)
def test_name_filter(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])})
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == S({"clubs": ExactSequence([])})
| from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == {
"clubs": [
{"id": lva.id, "name": "LV Aachen"},
{"id": sfn.id, "name": "Sportflug Niederberg"},
]
}
def test_name_filter(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs?name=LV%20Aachen")
assert res.status_code == 200
assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]}
def test_name_filter_with_unknown_club(db_session, client):
res = client.get("/clubs?name=Unknown")
assert res.status_code == 200
assert res.json == {"clubs": []}
|
Rectify Msession Model and specify pivot table name -bergynj | <?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Msessions extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'msessions';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['session_time','cinema_id', 'movie_id'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['created_at', 'updated_at'];
/**
* The cinema associated with this session time
*
* @param
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function cinemas()
{
return $this->belongsToMany('App\Cinemas','cinema_msession')->withTimestamps();
}
/**
* The movie associated with this session time
*
* @param
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function movies()
{
return $this->belongsToMany('App\Movies','movie_msession')->withTimestamps();
}
}
| <?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Msessions extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'msessions';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['session_time','cinema_id', 'movie_id'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['created_at', 'updated_at'];
/**
* The cinema associated with this session time
*
* @param
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function cinemas()
{
return $this->belongsToMany(App\Cinemas)->withTimestamps();
}
/**
* The movie associated with this session time
*
* @param
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function movies()
{
return $this->belongsToMany(App\Movies)->withTimestamps();
}
}
|
Introduce `swix-signatre` which is handled by switools/swisignature | # Copyright (c) 2018 Arista Networks, Inc.
# Use of this source code is governed by the Apache License 2.0
# that can be found in the LICENSE file.
from setuptools import setup
setup( name='switools',
version='1.0',
description='Tools for handling Arista SWI/X',
packages=['switools', 'swixtools'],
install_requires=[ 'M2Crypto' ],
test_suite="tests",
entry_points = {
'console_scripts': [ 'verify-swi=switools.verifyswi:main',
'swi-signature=switools.swisignature:main',
'swix-create=swixtools.create:main',
'swix-signature=switools.swisignature:main',
],
},
url='https://github.com/aristanetworks/swi-tools',
zip_safe=False,
include_package_data=True )
| # Copyright (c) 2018 Arista Networks, Inc.
# Use of this source code is governed by the Apache License 2.0
# that can be found in the LICENSE file.
from setuptools import setup
setup( name='switools',
version='1.0',
description='Tools for handling Arista SWI/X',
packages=['switools', 'swixtools'],
install_requires=[ 'M2Crypto' ],
test_suite="tests",
entry_points = {
'console_scripts': [ 'verify-swi=switools.verifyswi:main',
'swi-signature=switools.swisignature:main',
'swix-create=swixtools.create:main' ],
},
url='https://github.com/aristanetworks/swi-tools',
zip_safe=False,
include_package_data=True )
|
Remove warnings about raw types | package org.socialsignin.spring.data.dynamodb.repository.support;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshaller;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.socialsignin.spring.data.dynamodb.domain.sample.User;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings("unused")
public class DynamoDBEntityMetadataSupportUnitTest {
@Test
public void testGetMarshallerForProperty_WhenAnnotationIsOnField_AndReturnsDynamoDBMarshaller()
{
DynamoDBEntityMetadataSupport support = new DynamoDBEntityMetadataSupport<>(User.class);
DynamoDBMarshaller fieldAnnotation = support.getMarshallerForProperty("joinYear");
Assert.assertNotNull(fieldAnnotation);
}
@Test
public void testGetMarshallerForProperty_WhenAnnotationIsOnMethod_AndReturnsDynamoDBMarshaller()
{
DynamoDBEntityMetadataSupport support = new DynamoDBEntityMetadataSupport<>(User.class);
DynamoDBMarshaller methodAnnotation = support.getMarshallerForProperty("leaveDate");
Assert.assertNotNull(methodAnnotation);
}
}
| package org.socialsignin.spring.data.dynamodb.repository.support;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshaller;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.socialsignin.spring.data.dynamodb.domain.sample.User;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings("unused")
public class DynamoDBEntityMetadataSupportUnitTest {
@Test
public void testGetMarshallerForProperty_WhenAnnotationIsOnField_AndReturnsDynamoDBMarshaller()
{
DynamoDBEntityMetadataSupport support = new DynamoDBEntityMetadataSupport(User.class);
DynamoDBMarshaller fieldAnnotation = support.getMarshallerForProperty("joinYear");
Assert.assertNotNull(fieldAnnotation);
}
@Test
public void testGetMarshallerForProperty_WhenAnnotationIsOnMethod_AndReturnsDynamoDBMarshaller()
{
DynamoDBEntityMetadataSupport support = new DynamoDBEntityMetadataSupport(User.class);
DynamoDBMarshaller methodAnnotation = support.getMarshallerForProperty("leaveDate");
Assert.assertNotNull(methodAnnotation);
}
}
|
Allow to pass a runner to Process. | from __future__ import absolute_import
import os
from .tee import run
from .exit import trace
catch_keyboard_interrupts = True
class Process(object):
"""Process related functions using the tee module."""
rc_keyboard_interrupt = 54321
def __init__(self, quiet=False, env=None, runner=run):
self.quiet = quiet
self.env = env
self.runner = runner
def popen(self, cmd, echo=True, echo2=True):
# env *replaces* os.environ
trace(cmd)
if self.quiet:
echo = echo2 = False
try:
return self.runner(cmd, echo, echo2, shell=True, env=self.env)
except KeyboardInterrupt:
if catch_keyboard_interrupts:
return self.rc_keyboard_interrupt, []
raise
def pipe(self, cmd):
rc, lines = self.popen(cmd, echo=False)
if rc == 0 and lines:
return lines[0]
return ''
def system(self, cmd):
rc, lines = self.popen(cmd)
return rc
| from __future__ import absolute_import
import os
from .tee import run
from .exit import trace
catch_keyboard_interrupts = True
class Process(object):
"""Process related functions using the tee module."""
rc_keyboard_interrupt = 54321
def __init__(self, quiet=False, env=None):
self.quiet = quiet
self.env = env
def popen(self, cmd, echo=True, echo2=True):
# env *replaces* os.environ
trace(cmd)
if self.quiet:
echo = echo2 = False
try:
return run(cmd, echo, echo2, shell=True, env=self.env)
except KeyboardInterrupt:
if catch_keyboard_interrupts:
return self.rc_keyboard_interrupt, []
raise
def pipe(self, cmd):
rc, lines = self.popen(cmd, echo=False)
if rc == 0 and lines:
return lines[0]
return ''
def system(self, cmd):
rc, lines = self.popen(cmd)
return rc
|
Remove unnecessary byline in sidebar | import React from "react";
import { connect } from "react-redux";
import { withTranslation } from "react-i18next";
import Toggle from "./toggle";
import { controlsWidth } from "../../util/globals";
import { TOGGLE_TRANSMISSION_LINES } from "../../actions/types";
@connect((state) => {
return {
showTransmissionLines: state.controls.showTransmissionLines
};
})
class TransmissionLines extends React.Component {
render() {
const { t } = this.props;
return (
<div style={{marginBottom: 10, width: controlsWidth, fontSize: 14}}>
<Toggle
display
on={this.props.showTransmissionLines}
callback={() => {
this.props.dispatch({ type: TOGGLE_TRANSMISSION_LINES, data: !this.props.showTransmissionLines });
}}
label={t("sidebar:Show transmission lines")}
/>
</div>
);
}
}
export default withTranslation()(TransmissionLines);
| import React from "react";
import { connect } from "react-redux";
import { withTranslation } from "react-i18next";
import Toggle from "./toggle";
import { controlsWidth } from "../../util/globals";
import { TOGGLE_TRANSMISSION_LINES } from "../../actions/types";
import { SidebarSubtitle } from "./styles";
@connect((state) => {
return {
showTransmissionLines: state.controls.showTransmissionLines
};
})
class TransmissionLines extends React.Component {
render() {
const { t } = this.props;
return (
<>
<SidebarSubtitle spaceAbove>
{t("sidebar:Transmission lines")}
</SidebarSubtitle>
<div style={{marginBottom: 10, width: controlsWidth, fontSize: 14}}>
<Toggle
display
on={this.props.showTransmissionLines}
callback={() => {
this.props.dispatch({ type: TOGGLE_TRANSMISSION_LINES, data: !this.props.showTransmissionLines });
}}
label={t("sidebar:Show transmission lines")}
/>
</div>
</>
);
}
}
export default withTranslation()(TransmissionLines);
|
Add clear, week start and format. | /**
* Spanish translation for bootstrap-datepicker
* Bruno Bonamin <bruno.bonamin@gmail.com>
*/
;(function($){
$.fn.datepicker.dates['es'] = {
days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"],
daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"],
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
today: "Hoy",
clear: "Limpiar",
weekStart: 1,
format: "dd.mm.yyyy"
};
}(jQuery));
| /**
* Spanish translation for bootstrap-datepicker
* Bruno Bonamin <bruno.bonamin@gmail.com>
*/
;(function($){
$.fn.datepicker.dates['es'] = {
days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"],
daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"],
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
today: "Hoy"
};
}(jQuery));
|
Fix Python versions for PKG-INFO | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
settings = dict()
# Publish
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
settings.update(
name='whenpy',
version='0.1.0',
description='Friendly Dates and Times',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/when.py',
packages=['when'],
install_requires=['pytz'],
license=open('LICENSE').read(),
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
setup(**settings)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
settings = dict()
# Publish
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
settings.update(
name='whenpy',
version='0.1.0',
description='Friendly Dates and Times',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/when.py',
packages=['when'],
install_requires=['pytz'],
license=open('LICENSE').read(),
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: Python 2.6',
'Programming Language :: Python :: Python 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
setup(**settings)
|
Move test to use namespaced PHPUnit TestCase | <?php
namespace Test\Phinx\Console\Command;
use Phinx\Console\PhinxApplication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\ApplicationTester;
class ListTest extends TestCase
{
public function testVersionInfo()
{
$application = new PhinxApplication();
$application->setAutoExit(false); // Set autoExit to false when testing
$application->setCatchExceptions(false);
$appTester = new ApplicationTester($application);
$appTester->run(['command' => 'list', '--format' => 'txt']);
$stream = $appTester->getOutput()->getStream();
rewind($stream);
$this->assertEquals(1, substr_count(stream_get_contents($stream), 'Phinx by CakePHP - https://phinx.org'));
}
}
| <?php
namespace Test\Phinx\Console\Command;
use Phinx\Console\PhinxApplication;
use Symfony\Component\Console\Tester\ApplicationTester;
class ListTest extends \PHPUnit_Framework_TestCase
{
public function testVersionInfo()
{
$application = new PhinxApplication();
$application->setAutoExit(false); // Set autoExit to false when testing
$application->setCatchExceptions(false);
$appTester = new ApplicationTester($application);
$appTester->run(['command' => 'list', '--format' => 'txt']);
$stream = $appTester->getOutput()->getStream();
rewind($stream);
$this->assertEquals(1, substr_count(stream_get_contents($stream), 'Phinx by CakePHP - https://phinx.org'));
}
}
|
Handle blank git user emails | define([
'knockout'
, '../util'
, 'text!./git_user.html'
], function(ko, util, template) {
function GitUserModel(params) {
this.el = util.param(params['el'])
this.name = util.param(params['name'])
this.email = util.param(params['email'])
this.size = ko.computed(function () {
return $(this.el()).height() + 20
}.bind(this))
this.gravatarUrl = ko.computed(function () {
email = this.email()
if (!util.isEmpty(email)) {
return util.gravatarUrl(this.email(), this.size())
} else {
return null
}
}.bind(this))
}
ko.components.register('git-user', {
viewModel: GitUserModel, template: template,
})
return GitUserModel
})
| define([
'knockout'
, '../util'
, 'text!./git_user.html'
], function(ko, util, template) {
function GitUserModel(params) {
this.el = util.param(params['el'])
this.name = util.param(params['name'])
this.email = util.param(params['email'])
this.size = ko.computed(function () {
return $(this.el()).height() + 20
}.bind(this))
this.gravatarUrl = ko.computed(function () {
return util.gravatarUrl(this.email(), this.size())
}.bind(this))
}
ko.components.register('git-user', {
viewModel: GitUserModel, template: template,
})
return GitUserModel
})
|
Add argparse as a dependency for python versions < 2.7 | import setuptools, sys
setuptools.setup(
name="sc2reader",
version="0.2.0",
license="MIT",
author="Graylin Kim",
author_email="graylin.kim@gmail.com",
url="https://github.com/GraylinKim/sc2reader",
description="Utility for parsing Starcraft II replay files",
long_description=''.join(open("README.txt").readlines()),
keywords=["starcraft 2","sc2","parser","replay"],
classifiers=[
"Environment :: Console",
"Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Environment :: Other Environment",
"Topic :: Utilities",
"Topic :: Software Development :: Libraries",
"Topic :: Games/Entertainment :: Real Time Strategy",
],
entry_points={
'console_scripts': [
'sc2autosave = sc2reader.scripts.sc2autosave:main',
'sc2printer = sc2reader.scripts.sc2printer:main',
'sc2store = sc2reader.scripts.sc2store:main',
]
},
install_requires=['mpyq','argparse'] if float(sys.version[:3]) < 2.7 else ['mpyq'],
packages=['sc2reader', 'sc2reader.scripts'],
)
| import setuptools
setuptools.setup(
name="sc2reader",
version="0.2.0",
license="MIT",
author="Graylin Kim",
author_email="graylin.kim@gmail.com",
url="https://github.com/GraylinKim/sc2reader",
description="Utility for parsing Starcraft II replay files",
long_description=''.join(open("README.txt").readlines()),
keywords=["starcraft 2","sc2","parser","replay"],
classifiers=[
"Environment :: Console",
"Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Environment :: Other Environment",
"Topic :: Utilities",
"Topic :: Software Development :: Libraries",
"Topic :: Games/Entertainment :: Real Time Strategy",
],
entry_points={
'console_scripts': [
'sc2autosave = sc2reader.scripts.sc2autosave:main',
'sc2printer = sc2reader.scripts.sc2printer:main',
'sc2store = sc2reader.scripts.sc2store:main',
]
},
requires=['mpyq'],
install_requires=['mpyq==0.1.5'],
packages=['sc2reader', 'sc2reader.scripts'],
)
|
Fix wordings of test statements | function focusDoc(browser, docType) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/`);
browser.expect.element('#app').to.be.visible.before(5000);
const createButton = `#button-create-${docType}`;
const docToFocus = `.${docType}`;
browser
.click(createButton)
.pause(500);
browser
.click(docToFocus)
.pause(500);
browser
.expect.element('#button-delete .md-inactive')
.to.not.be.present;
browser
.expect.element('#button-download .md-inactive')
.to.not.be.present;
}
describe('FileManager\'s download and delete button', function() {
after((browser, done) => {
browser.end(() => done());
});
it('should be enabled when a file is focused', (browser) => {
focusDoc(browser, 'file');
});
it('should be enabled when a folder is focused', (browser) => {
focusDoc(browser, 'folder');
});
});
| function focusDoc(browser, docType) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/`);
browser.expect.element('#app').to.be.visible.before(5000);
const createButton = `#button-create-${docType}`;
const docToFocus = `.${docType}`;
browser
.click(createButton)
.pause(500);
browser
.click(docToFocus)
.pause(500);
browser
.expect.element('#button-delete .md-inactive')
.to.not.be.present;
browser
.expect.element('#button-download .md-inactive')
.to.not.be.present;
}
describe('FileManager\'s download and delete button', function() {
after((browser, done) => {
browser.end(() => done());
});
it('should be enable when a file is focused', (browser) => {
focusDoc(browser, 'file');
});
it('should be created when a folder is focused', (browser) => {
focusDoc(browser, 'folder');
});
});
|
Correct extra * in javadoc. | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene;
/** Lucene's package information, including version. */
public final class LucenePackage {
private LucenePackage() {} // can't construct
/** Return Lucene's package, including version information. */
public static Package get() {
return LucenePackage.class.getPackage();
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene;
/** Lucene's package information, including version. * */
public final class LucenePackage {
private LucenePackage() {} // can't construct
/** Return Lucene's package, including version information. */
public static Package get() {
return LucenePackage.class.getPackage();
}
}
|
Use public github URL for package homepage | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(name="hal-json",
version="0.1",
description="Parse and encode links according to RFC 5988 or HAL specs",
author="Michael Burrows, Carlos Martín",
author_email="inean.es@gmail.com",
url="https://github.com/inean/LinkHeader.git",
packages=find_packages(),
license="BSD",
keywords="RFC5988, HAL, json",
zip_safe=True,
long_description="""
A simple module to allow developers to format
or encode links according to RFC 5988 or trying to follow HAL
specifications (http://stateless.co/hal_specification.html)
""",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules"
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(name="hal-json",
version="0.1",
description="Parse and encode links according to RFC 5988 or HAL specs",
author="Michael Burrows, Carlos Martín",
author_email="inean.es@gmail.com",
url="https://inean@github.com/inean/LinkHeader.git",
packages=find_packages(),
license="BSD",
keywords="RFC5988, HAL, json",
zip_safe=True,
long_description="""
A simple module to allow developers to format
or encode links according to RFC 5988 or trying to follow HAL
specifications (http://stateless.co/hal_specification.html)
""",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules"
]
)
|
Set spotlight inner angle to glTF defaults | const Signal = require('signals')
function SpotLight (opts) {
this.type = 'SpotLight'
this.enabled = true
this.changed = new Signal()
this.target = [0, 0, 0]
this.color = [1, 1, 1, 1]
this.intensity = 1
this.angle = Math.PI / 4
this.innerAngle = 0
this.range = 10
this.castShadows = false
this.set(opts)
}
SpotLight.prototype.init = function (entity) {
this.entity = entity
}
SpotLight.prototype.set = function (opts) {
Object.assign(this, opts)
if (opts.color !== undefined || opts.intensity !== undefined) {
this.color[3] = this.intensity
}
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new SpotLight(opts)
}
| const Signal = require('signals')
function SpotLight (opts) {
this.type = 'SpotLight'
this.enabled = true
this.changed = new Signal()
this.target = [0, 0, 0]
this.color = [1, 1, 1, 1]
this.intensity = 1
this.angle = Math.PI / 4
this.innerAngle = Math.PI / 6
this.range = 10
this.castShadows = false
this.set(opts)
}
SpotLight.prototype.init = function (entity) {
this.entity = entity
}
SpotLight.prototype.set = function (opts) {
Object.assign(this, opts)
if (opts.color !== undefined || opts.intensity !== undefined) {
this.color[3] = this.intensity
}
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new SpotLight(opts)
}
|
Set options in connect (serverless) | 'use strict'
const mongoose = require('mongoose')
const { ApolloServer } = require('apollo-server-lambda')
const { UnsignedIntResolver, UnsignedIntTypeDefinition, DateTimeResolver, DateTimeTypeDefinition } = require('graphql-scalars')
const isAuthenticated = require('../src/utils/isAuthenticated')
const isDemoMode = require('../src/utils/isDemoMode')
const createDate = require('../src/utils/createDate')
const dbUrl = process.env.ACKEE_MONGODB || process.env.MONGODB_URI
if (dbUrl == null) {
throw new Error('MongoDB connection URI missing in environment')
}
mongoose.connect(dbUrl, {
useFindAndModify: false,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
const apolloServer = new ApolloServer({
introspection: false,
playground: false,
debug: false,
// formatError: handleGraphError,
typeDefs: [
UnsignedIntTypeDefinition,
DateTimeTypeDefinition,
require('../src/types')
],
resolvers: {
UnsignedInt: UnsignedIntResolver,
DateTime: DateTimeResolver,
...require('../src/resolvers')
},
context: async (integrationContext) => ({
isDemoMode,
isAuthenticated: await isAuthenticated(integrationContext.event.headers['authorization']),
dateDetails: createDate(integrationContext.event.headers['time-zone']),
req: integrationContext.req
})
})
exports.handler = apolloServer.createHandler() | 'use strict'
const mongoose = require('mongoose')
const { ApolloServer } = require('apollo-server-lambda')
const { UnsignedIntResolver, UnsignedIntTypeDefinition, DateTimeResolver, DateTimeTypeDefinition } = require('graphql-scalars')
const isAuthenticated = require('../src/utils/isAuthenticated')
const isDemoMode = require('../src/utils/isDemoMode')
const createDate = require('../src/utils/createDate')
const dbUrl = process.env.ACKEE_MONGODB || process.env.MONGODB_URI
if (dbUrl == null) {
throw new Error('MongoDB connection URI missing in environment')
}
mongoose.set('useFindAndModify', false)
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
const apolloServer = new ApolloServer({
introspection: false,
playground: false,
debug: false,
// formatError: handleGraphError,
typeDefs: [
UnsignedIntTypeDefinition,
DateTimeTypeDefinition,
require('../src/types')
],
resolvers: {
UnsignedInt: UnsignedIntResolver,
DateTime: DateTimeResolver,
...require('../src/resolvers')
},
context: async (integrationContext) => ({
isDemoMode,
isAuthenticated: await isAuthenticated(integrationContext.event.headers['authorization']),
dateDetails: createDate(integrationContext.event.headers['time-zone']),
req: integrationContext.req
})
})
exports.handler = apolloServer.createHandler() |
Change notice comment concerning the changes of the PFBC class | <?php
/**
* Changes made by Pierre-Henry Soria.
*/
// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;
class Textarea extends \PFBC\Element
{
protected $attributes = array('class' => 'pfbc-textarea', 'rows' => '5');
public function jQueryDocumentReady()
{
echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
}
public function render()
{
$iLength = (!empty($this->attributes['value'])) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : '0';
echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';
if (!empty($this->attributes['value'])) {
echo $this->filter($this->attributes['value']);
}
echo '</textarea><p><span id="', $this->attributes['id'], '_rem_len">' . $iLength . '</span> ', t('character(s).'), '</p>';
}
}
| <?php
/**
* We made many changes in this code.
* By pH7 (Pierre-Henry SORIA).
*/
// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;
class Textarea extends \PFBC\Element
{
protected $attributes = array('class' => 'pfbc-textarea', 'rows' => '5');
public function jQueryDocumentReady()
{
echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
}
public function render()
{
$iLength = (!empty($this->attributes['value'])) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : '0';
echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';
if (!empty($this->attributes['value'])) {
echo $this->filter($this->attributes['value']);
}
echo '</textarea><p><span id="', $this->attributes['id'], '_rem_len">' . $iLength . '</span> ', t('character(s).'), '</p>';
}
}
|
Fix copy and paste error | <?php
Class migration_241 extends Migration {
static $publish_filtering_disabled = false;
static function getVersion(){
return '2.4.1';
}
static function getReleaseNotes(){
return 'http://getsymphony.com/download/releases/version/2.4.1/';
}
static function upgrade() {
// Add association interfaces
try {
Symphony::Database()->query('
ALTER TABLE `tbl_sections_association`
ADD `interface` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
ADD `editor` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL;
');
}
catch (Exception $ex) {}
// Update the version information
return parent::upgrade();
}
static function preUpdateNotes(){
return array();
}
static function postUpdateNotes(){
return array();
}
}
| <?php
Class migration_241 extends Migration {
static $publish_filtering_disabled = false;
static function getVersion(){
return '2.4.1';
}
static function getReleaseNotes(){
return 'http://getsymphony.com/download/releases/version/2.4.1/';
}
static function upgrade() {
// Add association interfaces
try {
Symphony::Database()->query('
ALTER TABLE `tbl_fields_date`
ADD `interface` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
ADD `editor` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL;
');
}
catch (Exception $ex) {}
// Update the version information
return parent::upgrade();
}
static function preUpdateNotes(){
return array();
}
static function postUpdateNotes(){
return array();
}
}
|
Add row join command for merging berkeley DBs | #! /usr/bin/env python
from __future__ import print_function
import shutil
import logging
logger = logging.getLogger(__name__)
from atlasseq.storage.base import BerkeleyDBStorage
def rowjoin(partitioned_data, out_db, N=25000000):
N = int(N)
db_out = BerkeleyDBStorage(config={'filename': out_db})
for x in ["colour_to_sample_lookup", "sample_to_colour_lookup", "metadata"]:
shutil.copy("".join([partitioned_data, "_0", x]), "".join([out_db, x]))
batch = 0
db = BerkeleyDBStorage(
config={'filename': "".join([partitioned_data, "_", str(batch)])})
for i in range(N):
if i % 10000 == 0 and not i == 0:
logger.info("%i of %i %f%% " % (i, N, 100*i/N))
db.storage.close()
batch += 1
db = BerkeleyDBStorage(
config={'filename': "".join([partitioned_data, "_", str(batch)])})
db_out[i] = db[i]
return {'graph': out_db}
| #! /usr/bin/env python
from __future__ import print_function
import shutil
import logging
logger = logging.getLogger(__name__)
from atlasseq.storage.base import BerkeleyDBStorage
def rowjoin(partitioned_data, out_db, N=25000000):
db_out = BerkeleyDBStorage(config={'filename': out_db})
for x in ["colour_to_sample_lookup", "sample_to_colour_lookup", "metadata"]:
shutil.copy("".join([partitioned_data, "_0", x]), "".join([out_db, x]))
batch = 0
db = BerkeleyDBStorage(
config={'filename': "".join([partitioned_data, "_", str(batch)])})
for i in range(N):
if i % 10000 == 0 and not i == 0:
logger.info("%i of %i %f%% " % (i, N, 100*i/N))
db.storage.close()
batch += 1
db = BerkeleyDBStorage(
config={'filename': "".join([partitioned_data, "_", str(batch)])})
db_out[i] = db[i]
return {'graph': out_db}
|
Add an underscore to a private property | import ko from "knockout";
function Viewer(vivliostyle, viewerSettings, opt_viewerOptions) {
this.viewer_ = new vivliostyle.viewer.Viewer(viewerSettings, opt_viewerOptions);
this.state = {
cfi: ko.observable(""),
status: ko.observable("loading"),
pageProgression: ko.observable(vivliostyle.constants.LTR)
};
this.setupViewerEventHandler();
["navigateToLeft", "navigateToRight"].forEach(function(methodName) {
this[methodName] = this[methodName].bind(this);
}, this);
}
Viewer.prototype.setupViewerEventHandler = function() {
this.viewer_.addListener("loaded", function() {
this.state.pageProgression(this.viewer_.getCurrentPageProgression());
this.state.status("complete");
}.bind(this));
this.viewer_.addListener("nav", function(payload) {
var cfi = payload.cfi;
if (cfi) {
this.state.cfi(cfi);
}
}.bind(this));
};
Viewer.prototype.loadDocument = function(url, opt_documentOptions) {
this.viewer_.loadDocument(url, opt_documentOptions);
};
Viewer.prototype.navigateToLeft = function() {
this.viewer_.navigateToPage("left");
};
Viewer.prototype.navigateToRight = function() {
this.viewer_.navigateToPage("right");
};
export default Viewer;
| import ko from "knockout";
function Viewer(vivliostyle, viewerSettings, opt_viewerOptions) {
this.viewer = new vivliostyle.viewer.Viewer(viewerSettings, opt_viewerOptions);
this.state = {
cfi: ko.observable(""),
status: ko.observable("loading"),
pageProgression: ko.observable(vivliostyle.constants.LTR)
};
this.setupViewerEventHandler();
["navigateToLeft", "navigateToRight"].forEach(function(methodName) {
this[methodName] = this[methodName].bind(this);
}, this);
}
Viewer.prototype.setupViewerEventHandler = function() {
this.viewer.addListener("loaded", function() {
this.state.pageProgression(this.viewer.getCurrentPageProgression());
this.state.status("complete");
}.bind(this));
this.viewer.addListener("nav", function(payload) {
var cfi = payload.cfi;
if (cfi) {
this.state.cfi(cfi);
}
}.bind(this));
};
Viewer.prototype.loadDocument = function(url, opt_documentOptions) {
this.viewer.loadDocument(url, opt_documentOptions);
};
Viewer.prototype.navigateToLeft = function() {
this.viewer.navigateToPage("left");
};
Viewer.prototype.navigateToRight = function() {
this.viewer.navigateToPage("right");
};
export default Viewer;
|
Make tracking ID a config option for Heroku deploys | var express = require('express');
var app = express();
var forceSsl = function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
res.header("Strict-Transport-Security", "max-age=31536000");
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
return next();
};
app.set('port', (process.env.PORT || 5000));
app.use(forceSsl);
app.get('/config.js', function(request, response) {
var config = " \
'use strict'; \
angular.module('config', []) \
.constant('config', { \
'endpoint' : '" + process.env.ALERTA_ENDPOINT + "', \
'provider' : '" + process.env.PROVIDER + "', \
'client_id' : '" + process.env.CLIENT_ID + "', \
'gitlab_url' : '" + process.env.GITLAB_URL + "', \
'tracking_id' : '" + process.env.TRACKING_ID + "' \
});";
response.send(config);
});
app.use(express.static(__dirname + '/app'));
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
| var express = require('express');
var app = express();
var forceSsl = function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
res.header("Strict-Transport-Security", "max-age=31536000");
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
return next();
};
app.set('port', (process.env.PORT || 5000));
app.use(forceSsl);
app.get('/config.js', function(request, response) {
var config = " \
'use strict'; \
angular.module('config', []) \
.constant('config', { \
'endpoint' : '" + process.env.ALERTA_ENDPOINT + "', \
'provider' : '" + process.env.PROVIDER + "', \
'client_id' : '" + process.env.CLIENT_ID + "', \
'gitlab_url' : '" + process.env.GITLAB_URL + "' \
});";
response.send(config);
});
app.use(express.static(__dirname + '/app'));
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
|
Replace count check with more correct reparent check | function unsplay (items, key, parentKey) {
var nodes = items.reduce(function (nodes, item) {
nodes[item[key]] = {item: item, children: []};
return nodes;
}, {});
do {
var reparented = false;
nodes = Object.keys(nodes).reduce(function (newNodes, id) {
var node = nodes[id];
var parentId = node.item[parentKey];
if (parentId in nodes) {
nodes[parentId].children.push(node);
reparented = true;
}
else newNodes[id] = node;
return newNodes;
}, {});
} while (reparented);
return Object.keys(nodes).map(function (id) { return nodes[id]; });
}
module.exports = unsplay;
| function unsplay (items, key, parentKey) {
var nodes = items.reduce(function (nodes, item) {
nodes[item[key]] = {item: item, children: []};
return nodes;
}, {});
var lastCount, count;
do {
lastCount = count;
count = 0;
nodes = Object.keys(nodes).reduce(function (newNodes, id) {
var node = nodes[id];
var parentId = node.item[parentKey];
if (parentId in nodes) nodes[parentId].children.push(node);
else {
newNodes[id] = node;
count++;
}
return newNodes;
}, {});
} while (lastCount !== count);
return Object.keys(nodes).map(function (id) { return nodes[id]; });
}
module.exports = unsplay;
|
Fix a issue when a provider has not been added | # Stdlib imports
# E.g.: from math import sqrt
# Core Django imports
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
# Third-party app imports
# E.g.: from django_extensions.db.models import TimeStampedModel
# Imports from local apps
from tokens.models import BearerToken, Provider
from .snooper import Snooper
def home(request, template='home.html'):
if not request.user.is_authenticated():
return redirect('showcase_tour')
args = {
'name_drive': Provider.NAME_DRIVE,
'name_gmail': Provider.NAME_GMAIL,
'name_facebook': Provider.NAME_FACEBOOK,
'name_twitter': Provider.NAME_TWITTER,
'name_dropbox': Provider.NAME_DROPBOX,
}
args.update(BearerToken.objects.providers_breakdown_for_user(request.user))
return render(request, template, args)
@login_required
def search(request, template='search.html'):
q = request.GET.get('q', '')
args = dict()
for provider_name, __ in Provider.NAME_CHOICES:
is_selected = True if request.GET.get(provider_name, '').lower() == 'true' else False
args['{}_is_selected'.format(provider_name)] = is_selected
results = Snooper(provider_name, request.user).search(q) if is_selected else []
args['{}_results'.format(provider_name)] = results
return render(request, template, args) | # Stdlib imports
# E.g.: from math import sqrt
# Core Django imports
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
# Third-party app imports
# E.g.: from django_extensions.db.models import TimeStampedModel
# Imports from local apps
from tokens.models import BearerToken, Provider
from .snooper import Snooper
def home(request, template='home.html'):
if not request.user.is_authenticated():
return redirect('showcase_tour')
args = {
'name_drive': Provider.NAME_DRIVE,
'name_gmail': Provider.NAME_GMAIL,
'name_facebook': Provider.NAME_FACEBOOK,
'name_twitter': Provider.NAME_TWITTER,
'name_dropbox': Provider.NAME_DROPBOX,
}
args.update(BearerToken.objects.providers_breakdown_for_user(request.user))
return render(request, template, args)
@login_required
def search(request, template='search.html'):
q = request.GET.get('q', '')
args = dict()
for provider_name, __ in Provider.NAME_CHOICES:
is_selected = True if request.GET.get(provider_name).lower() == 'true' else False
args['{}_is_selected'.format(provider_name)] = is_selected
results = Snooper(provider_name, request.user).search(q) if is_selected else []
args['{}_results'.format(provider_name)] = results
return render(request, template, args) |
Disable Vaadin test until SWARM-249 is resolved. | package org.wildfly.swarm.it.vaadin;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.wildfly.swarm.it.AbstractIntegrationTest;
import static org.fest.assertions.Assertions.assertThat;
/**
* @author Bob McWhirter
*/
//@RunWith(Arquillian.class)
public class VaadinApplicationIT extends AbstractIntegrationTest {
@Drone
PhantomJSDriver browser;
//disabled until SWARM-249
//@Test
public void testIt() throws Exception {
browser.manage().window().setSize( new Dimension(1024, 768));
browser.navigate().to("http://localhost:8080/");
browser.findElementByClassName( "v-button" ).click();
WebElement notification = browser.findElementByClassName("v-Notification");
assertThat( notification.getText() ).contains( "Howdy at" );
}
}
| package org.wildfly.swarm.it.vaadin;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.wildfly.swarm.it.AbstractIntegrationTest;
import static org.fest.assertions.Assertions.assertThat;
/**
* @author Bob McWhirter
*/
@RunWith(Arquillian.class)
public class VaadinApplicationIT extends AbstractIntegrationTest {
@Drone
PhantomJSDriver browser;
@Test
public void testIt() throws Exception {
browser.manage().window().setSize( new Dimension(1024, 768));
browser.navigate().to("http://localhost:8080/");
browser.findElementByClassName( "v-button" ).click();
WebElement notification = browser.findElementByClassName("v-Notification");
assertThat( notification.getText() ).contains( "Howdy at" );
}
}
|
Fix ember-flexberry blueprint add dependencies | /* globals module */
module.exports = {
afterInstall: function() {
var _this = this;
return this.addBowerPackagesToProject([
{ name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
{ name: 'blueimp-file-upload', target: '9.11.2' },
{ name: 'devicejs', target: '0.2.7' },
{ name: 'localforage', target: '1.3.3' }
]).then(function() {
return _this.addAddonsToProject({
packages: [
{ name: 'semantic-ui-ember', target: '0.9.3' },
{ name: 'ember-moment', target: '6.0.0' },
{ name: 'ember-link-action', target: '0.0.34' },
{ name: 'broccoli-jscs', target: '1.2.2' },
{ name: 'ember-browserify', target: '1.1.9' },
{ name: 'dexie', target: '1.3.6' },
'https://github.com/Flexberry/ember-localforage-adapter.git'
]
});
});
},
normalizeEntityName: function() {}
};
| /* globals module */
module.exports = {
afterInstall: function() {
var _this = this;
return this.addBowerPackagesToProject([
{ name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
{ name: 'blueimp-file-upload', target: '9.11.2' },
{ name: 'devicejs', target: '0.2.7' },
{ name: 'localforage', target: '1.3.3' }
]).then(function() {
return _this.addAddonsToProject({
packages: [
{ name: 'semantic-ui-ember', target: '0.9.3' },
{ name: 'ember-moment', target: '6.0.0' },
{ name: 'ember-link-action', target: '0.0.34' },
{ name: 'broccoli-jscs', target: '1.2.2' },
'https://github.com/Flexberry/ember-localforage-adapter.git'
]
});
});
},
normalizeEntityName: function() {}
};
|
Move done argument to the right place | "use strict";
var chai = require("chai");
chai.use(require("chai-subset"));
var expect = chai.expect;
var util = require("util");
var libtidy = require("../");
describe("High-level API:", function() {
var testDoc1 = Buffer('<!DOCTYPE html>\n<html><head></head>\n' +
'<body><p>foo</p></body></html>');
describe("tidyBuffer:", function() {
it("on simple document", function(done) {
libtidy.tidyBuffer(testDoc1, function(err, res) {
expect(err).to.be.null;
expect(res).to.contain.key("output");
expect(res).to.contain.key("errlog");
expect(res.errlog).to.match(/inserting missing/);
expect(res.errlog).to.match(/looks like HTML5/);
expect(res.errlog).to.match(/were found/);
expect(Buffer.isBuffer(res.output)).ok;
expect(res.output.toString()).to.match(/<title>.*<\/title>/);
done();
});
});
});
});
| "use strict";
var chai = require("chai");
chai.use(require("chai-subset"));
var expect = chai.expect;
var util = require("util");
var libtidy = require("../");
describe("High-level API:", function() {
var testDoc1 = Buffer('<!DOCTYPE html>\n<html><head></head>\n' +
'<body><p>foo</p></body></html>');
describe("tidyBuffer:", function(done) {
it("on simple document", function() {
libtidy.tidyBuffer(testDoc1, function(err, res) {
expect(err).to.be.null;
expect(res).to.contain.key("output");
expect(res).to.contain.key("errlog");
expect(res.errlog).to.match(/inserting missing/);
expect(res.errlog).to.match(/looks like HTML5/);
expect(res.errlog).to.match(/were found/);
expect(Buffer.isBuffer(res.output)).ok;
expect(res.output.toString()).to.match(/<title>.*<\/title>/);
done();
});
});
});
});
|
Update intersphinx mapping to Django 1.8 | # -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.8': 'http://docs.djangoproject.com/en/1.8/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
| # -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.7': 'http://docs.djangoproject.com/en/1.7/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.