text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix PHP 8.1 deprecation errors
|
<?php
/**
* League.Csv (https://csv.thephpleague.com)
*
* (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace League\Csv;
use IteratorIterator;
use Traversable;
/**
* Map value from an iterator before yielding.
*
* @internal used internally to modify CSV content
*/
final class MapIterator extends IteratorIterator
{
/**
* The callback to apply on all InnerIterator current value.
*
* @var callable
*/
private $callable;
/**
* New instance.
*/
public function __construct(Traversable $iterator, callable $callable)
{
parent::__construct($iterator);
$this->callable = $callable;
}
/**
* @return mixed The value of the current element.
*/
#[\ReturnTypeWillChange]
public function current()
{
return ($this->callable)(parent::current(), parent::key());
}
}
|
<?php
/**
* League.Csv (https://csv.thephpleague.com)
*
* (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace League\Csv;
use IteratorIterator;
use Traversable;
/**
* Map value from an iterator before yielding.
*
* @internal used internally to modify CSV content
*/
final class MapIterator extends IteratorIterator
{
/**
* The callback to apply on all InnerIterator current value.
*
* @var callable
*/
private $callable;
/**
* New instance.
*/
public function __construct(Traversable $iterator, callable $callable)
{
parent::__construct($iterator);
$this->callable = $callable;
}
/**
* @return mixed The value of the current element.
*/
public function current()
{
return ($this->callable)(parent::current(), parent::key());
}
}
|
Hide Jumbotron on movie details page.
|
/**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 01 June, 2016
* License: MIT
*
* React App Main Layout Component
*/
import React from "react";
import Header from "./Header/Header";
import Jumbotron from "./Section/Jumbotron";
import Footer from "./Footer/Footer";
export default
class Home extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<Header/>
<section class="container poster-section">
<Jumbotron hide={this.props.params.movieId ? true : false}/>
{this.props.children}
</section>
<Footer/>
</div>
);
}
}
|
/**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 01 June, 2016
* License: MIT
*
* React App Main Layout Component
*/
import React from "react";
import Header from "./Header/Header";
import Jumbotron from "./Section/Jumbotron";
import Footer from "./Footer/Footer";
export default
class Home extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<Header/>
<section class="container poster-section">
<Jumbotron/>
{this.props.children}
</section>
<Footer/>
</div>
);
}
}
|
Return bad request for any method
We don't restrict this to GET, copied that in error.
|
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class BadRequestController
*/
class BadRequestController extends AbstractController
{
/**
* This is the catch-all action for the api.
* It sends a 404 and dies.
*/
#[Route(
'/api/{url}',
requirements: [
'url' => '(?!doc).+',
],
defaults: [
'url' => null,
],
priority: -1,
)]
public function indexAction()
{
throw $this->createNotFoundException();
}
}
|
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class BadRequestController
*/
class BadRequestController extends AbstractController
{
/**
* This is the catch-all action for the api.
* It sends a 404 and dies.
*/
#[Route(
'/api/{url}',
requirements: [
'url' => '(?!doc).+',
],
defaults: [
'url' => null,
],
methods: ['GET'],
priority: -1,
)]
public function indexAction()
{
throw $this->createNotFoundException();
}
}
|
Update 10_condor to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16522 4e558342-562e-0410-864c-e07659590f8c
|
import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondor(osgunittest.OSGTestCase):
def test_01_start_condor(self):
core.config['condor.lockfile'] = '/var/lock/subsys/condor_master'
core.state['condor.started-service'] = False
core.state['condor.running-service'] = False
core.skip_ok_unless_installed('condor')
if os.path.exists(core.config['condor.lockfile']):
core.state['condor.running-service'] = True
self.skip_ok('already running')
command = ('service', 'condor', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor.lockfile']),
'Condor run lock file missing')
core.state['condor.started-service'] = True
core.state['condor.running-service'] = True
|
import os
import osgtest.library.core as core
import unittest
class TestStartCondor(unittest.TestCase):
def test_01_start_condor(self):
core.config['condor.lockfile'] = '/var/lock/subsys/condor_master'
core.state['condor.started-service'] = False
core.state['condor.running-service'] = False
if core.missing_rpm('condor'):
return
if os.path.exists(core.config['condor.lockfile']):
core.state['condor.running-service'] = True
core.skip('apparently running')
return
command = ('service', 'condor', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor.lockfile']),
'Condor run lock file missing')
core.state['condor.started-service'] = True
core.state['condor.running-service'] = True
|
Fix extending service provider name
|
<?php
/*
* This file is part of Laravel Reviewable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Reviewable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Reviewable;
use BrianFaust\ServiceProvider\AbstractServiceProvider;
class ReviewableServiceProvider extends AbstractServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
$this->publishMigrations();
$this->publishConfig();
}
/**
* Register the application services.
*/
public function register(): void
{
parent::register();
$this->mergeConfig();
}
/**
* Get the default package name.
*
* @return string
*/
public function getPackageName(): string
{
return 'reviewable';
}
}
|
<?php
/*
* This file is part of Laravel Reviewable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Reviewable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Reviewable;
use BrianFaust\ServiceProvider\ServiceProvider;
class ReviewableServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
$this->publishMigrations();
$this->publishConfig();
}
/**
* Register the application services.
*/
public function register(): void
{
parent::register();
$this->mergeConfig();
}
/**
* Get the default package name.
*
* @return string
*/
public function getPackageName(): string
{
return 'reviewable';
}
}
|
Change return type of ID to integer
|
<?php
namespace MovingImage\Client\VMPro\Entity;
use JMS\Serializer\Annotation\Type;
use MovingImage\Meta\Interfaces\VideoManagerInterface;
/**
* Class VideoManager.
*/
class VideoManager implements VideoManagerInterface
{
/**
* @Type("integer")
*/
private $id;
/**
* @Type("string")
*/
private $name;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param $id integer
*
* @return VideoManager
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param $name string
*
* @return VideoManager
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
|
<?php
namespace MovingImage\Client\VMPro\Entity;
use JMS\Serializer\Annotation\Type;
use MovingImage\Meta\Interfaces\VideoManagerInterface;
/**
* Class VideoManager.
*/
class VideoManager implements VideoManagerInterface
{
/**
* @Type("string")
*/
private $id;
/**
* @Type("string")
*/
private $name;
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @param $id
*
* @return VideoManager
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param $name
*
* @return VideoManager
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
|
Modify default line separator from CRLF to LF
|
/*
* Find scopes from AST
* @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com)
* @lastmodifiedDate 2015-07-27
*/
var walkes = require('walkes');
/**
* ScopeFinder
* @constructor
*/
function ScopeFinder() {
}
/**
* Find function scopes of AST parsed from source
* @param {Object} ast JS parsed AST
* @returns {Object} Array of ASTs, each corresponds to global or function scope
*/
ScopeFinder.prototype.findScopes = function (ast) {
'use strict';
var scopes = [];
function handleInnerFunction(astNode, recurse) {
scopes.push(astNode);
recurse(astNode.body);
}
walkes(ast, {
Program: function (node, recurse) {
scopes.push(node);
node.body.forEach(function (elem) {
recurse(elem);
});
},
FunctionDeclaration: handleInnerFunction,
FunctionExpression: handleInnerFunction
});
return scopes;
};
var finder = new ScopeFinder();
module.exports = finder;
|
/*
* Find scopes from AST
* @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com)
* @lastmodifiedDate 2015-07-27
*/
var walkes = require('walkes');
/**
* ScopeFinder
* @constructor
*/
function ScopeFinder() {
}
/**
* Find function scopes of AST parsed from source
* @param {Object} ast JS parsed AST
* @returns {Object} Array of ASTs, each corresponds to global or function scope
*/
ScopeFinder.prototype.findScopes = function (ast) {
'use strict';
var scopes = [];
function handleInnerFunction(astNode, recurse) {
scopes.push(astNode);
recurse(astNode.body);
}
walkes(ast, {
Program: function (node, recurse) {
scopes.push(node);
node.body.forEach(function (elem) {
recurse(elem);
});
},
FunctionDeclaration: handleInnerFunction,
FunctionExpression: handleInnerFunction
});
return scopes;
};
var finder = new ScopeFinder();
module.exports = finder;
|
Allow error_reporting config to contain constants
|
<?php
/**
* A base implementation for exceptions thrown by the framework.
*
* @author Jorgen Evens <jorgen@wlab.be>
* @package WebLab
* @subpackage Exception
*
*/
abstract class WebLab_Exception extends Exception {
protected $_trace;
public static function reporting() {
$error_reporting = WebLab_Config::getApplicationConfig()->get( 'Application.Error.reporting' );
if( is_string( $error_reporting ) ) {
$error_reporting = constant( $error_reporting );
}
error_reporting( $error_reporting );
}
protected function _updateTrace() {
if( empty( $this->_trace ) )
$this->_trace = $this->getTrace();
}
public function getClass() {
$this->_updateTrace();
return $this->_trace[0]['class'];
}
public function getMethod() {
$this->_updateTrace();
return $this->_trace[0]['function'];
}
}
|
<?php
/**
* A base implementation for exceptions thrown by the framework.
*
* @author Jorgen Evens <jorgen@wlab.be>
* @package WebLab
* @subpackage Exception
*
*/
abstract class WebLab_Exception extends Exception {
protected $_trace;
public static function reporting() {
$error_reporting = WebLab_Config::getApplicationConfig()->get( 'Application.Error.reporting' );
error_reporting( $error_reporting );
}
protected function _updateTrace() {
if( empty( $this->_trace ) )
$this->_trace = $this->getTrace();
}
public function getClass() {
$this->_updateTrace();
return $this->_trace[0]['class'];
}
public function getMethod() {
$this->_updateTrace();
return $this->_trace[0]['function'];
}
}
|
Add team id field to API output
|
from django.contrib.auth.models import User
from rest_framework import serializers
from competition.models import Team
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ('id', 'name', 'slug', 'url')
url = serializers.SerializerMethodField(read_only=True)
def get_url(self, obj):
return obj.get_absolute_url()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('name', 'url')
name = serializers.SerializerMethodField(read_only=True)
url = serializers.SerializerMethodField(read_only=True)
def get_name(self, obj):
username = obj.username
full_name = obj.get_full_name()
if full_name:
return u"{} ({})".format(username, full_name)
return username
def get_url(self, obj):
return obj.get_absolute_url()
|
from django.contrib.auth.models import User
from rest_framework import serializers
from competition.models import Team
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ('name', 'slug', 'url')
url = serializers.SerializerMethodField(read_only=True)
def get_url(self, obj):
return obj.get_absolute_url()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('name', 'url')
name = serializers.SerializerMethodField(read_only=True)
url = serializers.SerializerMethodField(read_only=True)
def get_name(self, obj):
username = obj.username
full_name = obj.get_full_name()
if full_name:
return u"{} ({})".format(username, full_name)
return username
def get_url(self, obj):
return obj.get_absolute_url()
|
Install in correct virtual environment in test server
|
# -*- coding: utf-8 -*-
# http://docs.fabfile.org/en/1.5/tutorial.html
from fabric.api import *
from fabric.network import ssh
project = "gastosabertos"
env.user = 'gastosabertos'
env.hosts = ['gastosabertos.org']
#env.key_filename = '~/.ssh/ga_id_rsa'
def reset():
"""
Reset local debug env.
"""
local("rm -rf /tmp/instance")
local("mkdir /tmp/instance")
def setup():
"""
Setup virtual env.
"""
local("virtualenv env")
activate_this = "env/bin/activate_this.py"
execfile(activate_this, dict(__file__=activate_this))
local("python setup.py install")
reset()
def deploy():
"""
Deploy project to Gastos Abertos server
"""
project_dir = '/home/gastosabertos/gastos_abertos'
with cd(project_dir):
run("git pull")
run("workon ga")
run("python setup.py install")
run("touch wsgi.py")
def d():
"""
Debug.
"""
reset()
local("python manage.py run")
def babel():
"""
Babel compile.
"""
local("python setup.py compile_catalog --directory `find -name translations` --locale zh -f")
|
# -*- coding: utf-8 -*-
# http://docs.fabfile.org/en/1.5/tutorial.html
from fabric.api import *
from fabric.network import ssh
project = "gastosabertos"
env.user = 'gastosabertos'
env.hosts = ['gastosabertos.org']
#env.key_filename = '~/.ssh/ga_id_rsa'
def reset():
"""
Reset local debug env.
"""
local("rm -rf /tmp/instance")
local("mkdir /tmp/instance")
def setup():
"""
Setup virtual env.
"""
local("virtualenv env")
activate_this = "env/bin/activate_this.py"
execfile(activate_this, dict(__file__=activate_this))
local("python setup.py install")
reset()
def deploy():
"""
Deploy project to Gastos Abertos server
"""
project_dir = '/home/gastosabertos/gastos_abertos'
with cd(project_dir):
run("git pull")
run("python setup.py install")
run("touch wsgi.py")
def d():
"""
Debug.
"""
reset()
local("python manage.py run")
def babel():
"""
Babel compile.
"""
local("python setup.py compile_catalog --directory `find -name translations` --locale zh -f")
|
Replace absolute paths with relative paths
This is a workaround for https://github.com/mochajs/mocha/issues/2126 but since
relative paths are usually much nicer to look at it also has its own advantages
|
var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var globAll = require('glob-all');
var cli = new CLIEngine({});
function test(p, opts) {
it('should have no errors in ' + p, function () {
var format, warn;
if (opts && opts.timeout) {
this.timeout(opts.timeout);
}
if (opts && opts.formatter) {
format = opts.formatter;
}
if (opts && opts.hasOwnProperty('alwaysWarn')) {
warn = opts.alwaysWarn;
} else { // Show warnings by default
warn = true;
}
var report = cli.executeOnFiles([p]);
var formatter = cli.getFormatter(format);
if (
report &&
report.errorCount > 0
) {
throw new Error(
chalk.red('Code did not pass lint rules') +
// remove process.cwd() to convert absolute to relative paths
formatter(report.results).replace(process.cwd() + '/', '')
);
} else if (
warn &&
report &&
report.warningCount > 0
) {
console.log(formatter(report.results));
}
});
}
module.exports = function (patterns, options) {
describe('eslint', function () {
globAll.sync(patterns).forEach(function (file) {
test(file, options);
});
});
};
|
var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var globAll = require('glob-all');
var cli = new CLIEngine({});
function test(p, opts) {
it('should have no errors in ' + p, function () {
var format, warn;
if (opts && opts.timeout) {
this.timeout(opts.timeout);
}
if (opts && opts.formatter) {
format = opts.formatter;
}
if (opts && opts.hasOwnProperty('alwaysWarn')) {
warn = opts.alwaysWarn;
} else { // Show warnings by default
warn = true;
}
var report = cli.executeOnFiles([p]);
var formatter = cli.getFormatter(format);
if (
report &&
report.errorCount > 0
) {
throw new Error(
chalk.red('Code did not pass lint rules') +
formatter(report.results)
);
} else if (
warn &&
report &&
report.warningCount > 0
) {
console.log(formatter(report.results));
}
});
}
module.exports = function (patterns, options) {
describe('eslint', function () {
globAll.sync(patterns).forEach(function (file) {
test(file, options);
});
});
};
|
Make short-circuiting redux store optional
|
import urlQueryReducer from './urlQueryReducer';
import urlQueryConfig from '../urlQueryConfig';
/**
* Middleware to handle updating the URL query params
*/
const urlQueryMiddleware = (options = {}) => ({ getState }) => next => (action) => {
// if not a URL action, do nothing.
if (!action.meta || !action.meta.urlQuery) {
return next(action);
}
// otherwise, handle with URL handler -- doesn't go to Redux dispatcher
// update the URL
// use the default reducer if none provided
const reducer = options.reducer || urlQueryConfig.reducer || urlQueryReducer;
// if configured to read from the redux store (react-router-redux), do so and pass it to
// the reducer
const readLocationFromStore = options.readLocationFromStore == null ?
urlQueryConfig.readLocationFromStore : options.readLocationFromStore;
if (readLocationFromStore) {
const location = readLocationFromStore(getState());
reducer(action, location);
} else {
reducer(action);
}
// shortcircuit by default (don't pass to redux store), unless explicitly set
// to false.
if (options.shortcircuit === false) {
return next(action);
}
return undefined;
};
export default urlQueryMiddleware;
|
import urlQueryReducer from './urlQueryReducer';
import urlQueryConfig from '../urlQueryConfig';
/**
* Middleware to handle updating the URL query params
*/
const urlQueryMiddleware = (options = {}) => ({ getState }) => next => (action) => {
// if not a URL action, do nothing.
if (!action.meta || !action.meta.urlQuery) {
return next(action);
}
// otherwise, handle with URL handler -- doesn't go to Redux dispatcher
// update the URL
// use the default reducer if none provided
const reducer = options.reducer || urlQueryConfig.reducer || urlQueryReducer;
// if configured to read from the redux store (react-router-redux), do so and pass it to
// the reducer
const readLocationFromStore = options.readLocationFromStore == null ?
urlQueryConfig.readLocationFromStore : options.readLocationFromStore;
if (readLocationFromStore) {
const location = readLocationFromStore(getState());
return reducer(action, location);
}
return reducer(action);
};
export default urlQueryMiddleware;
|
Add unit tests back to default grunt task
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
// Add the grunt-mocha-test tasks.
[
'grunt-mocha-test',
'grunt-contrib-watch'
]
.forEach( grunt.loadNpmTasks );
grunt.initConfig({
// Configure a mochaTest task
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js' ]
},
},
watch: {
options: {
atBegin: true
},
scripts: {
files: [ 'src/**/*.js', 'test/**/*.js' ],
tasks: ['eslint', 'mochaTest' ]
}
},
eslint: {
target: ['src/**/*.js']
}
});
grunt.registerTask( 'default', [ 'eslint' , 'mochaTest' ]);
grunt.registerTask( 'debug', [ 'watch' ]);
};
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
// Add the grunt-mocha-test tasks.
[
'grunt-mocha-test',
'grunt-contrib-watch'
]
.forEach( grunt.loadNpmTasks );
grunt.initConfig({
// Configure a mochaTest task
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js' ]
},
},
watch: {
options: {
atBegin: true
},
scripts: {
files: [ 'src/**/*.js', 'test/**/*.js' ],
tasks: ['eslint', 'mochaTest' ]
}
},
eslint: {
target: ['src/**/*.js']
}
});
grunt.registerTask( 'default', [ 'eslint' ]);
grunt.registerTask( 'debug', [ 'watch' ]);
};
|
Change indentation from 2 spaces (Google standard) to 4 spaces (PEP-8).
Add comments.
|
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""A tiny Python program to check that Python is working.
Try running this program from the command line like this:
python hello.py
python hello.py Alice
That should print:
Hello World -or- Hello Alice
Try changing the 'Hello' to 'Howdy' and run again.
Once you have that working, you're ready for class -- you can edit
and run Python code; now you just need to learn Python!
"""
import sys
# Define a main() function that prints a little greeting.
def main():
# Get the name from the command line, using 'World' as a fallback.
if len(sys.argv) >= 2:
# by convention the script name is put at argv[0]
# the person's name is argv[1]
name = sys.argv[1]
else:
name = 'World'
# print inserts a space between arguments
print 'Howdy', name
print 'yay'
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
|
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""A tiny Python program to check that Python is working.
Try running this program from the command line like this:
python hello.py
python hello.py Alice
That should print:
Hello World -or- Hello Alice
Try changing the 'Hello' to 'Howdy' and run again.
Once you have that working, you're ready for class -- you can edit
and run Python code; now you just need to learn Python!
"""
import sys
# Define a main() function that prints a little greeting.
def main():
# Get the name from the command line, using 'World' as a fallback.
if len(sys.argv) >= 2:
name = sys.argv[1]
else:
name = 'World'
print 'Howdy', name
print 'yay'
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
|
Use `'html'` as output format
Per jstransformers/jstransformer#3.
|
'use strict';
var jade = require('jade');
var fs = require('fs');
exports.name = 'jade';
exports.outputFormat = 'html';
exports.compile = function (source, options) {
var fn = jade.compile(source, options);
return {fn: fn, dependencies: fn.dependencies}
};
exports.compileClient = function (source, options) {
return jade.compileClientWithDependenciesTracked(source, options);
};
exports.compileFile = function (path, options) {
var fn = jade.compileFile(path, options);
return {fn: fn, dependencies: fn.dependencies}
};
exports.compileFileClient = function (path, options) {
// There is no compileFileClientWithDependenciesTracked so gotta do it
// manually.
options = options || {};
options.filename = options.filename || path;
return exports.compileClient(fs.readFileSync(path, 'utf8'), options);
};
|
'use strict';
var jade = require('jade');
var fs = require('fs');
exports.name = 'jade';
exports.outputFormat = 'xml';
exports.compile = function (source, options) {
var fn = jade.compile(source, options);
return {fn: fn, dependencies: fn.dependencies}
};
exports.compileClient = function (source, options) {
return jade.compileClientWithDependenciesTracked(source, options);
};
exports.compileFile = function (path, options) {
var fn = jade.compileFile(path, options);
return {fn: fn, dependencies: fn.dependencies}
};
exports.compileFileClient = function (path, options) {
// There is no compileFileClientWithDependenciesTracked so gotta do it
// manually.
options = options || {};
options.filename = options.filename || path;
return exports.compileClient(fs.readFileSync(path, 'utf8'), options);
};
|
Allow an engine to be initialised using a constructor.
|
/**
* Basic engine support.
*/
require('../lib/setModuleDefaults');
var config = require('config');
var engineConfig = config.engines || {};
/**
* Return a function that creates a plugin:
*/
module.exports = function(language){
return {
attach: function (/* options */){
var languageConfig = engineConfig[language] || {};
/**
* If there is a specified engine for this language then use it,
* otherwise just use the provided name:
*/
var engine = require(languageConfig.module || language);
this.engine = (languageConfig.useConstructor) ? new engine() : engine;
this.languageConfig = languageConfig;
/**
* Add key methods:
*/
var renderFileMethodName = languageConfig.renderFileMethodName
|| 'renderFile';
this.__express = this.engine.__express || undefined;
this.renderFile = this.engine[renderFileMethodName] || undefined;
this.render = this.engine.render || undefined;
}
, name: 'adapter-' + language
};
};
|
/**
* Basic engine support.
*/
require('../lib/setModuleDefaults');
var config = require('config');
var engineConfig = config.engines || {};
/**
* Return a function that creates a plugin:
*/
module.exports = function(language){
return {
attach: function (/* options */){
var languageConfig = engineConfig[language] || {};
/**
* If there is a specified engine for this language then use it,
* otherwise just use the provided name:
*/
this.engine = require(languageConfig.module || language);
this.languageConfig = languageConfig;
/**
* Add key methods:
*/
var renderFileMethodName = languageConfig.renderFileMethodName
|| 'renderFile';
this.__express = this.engine.__express || undefined;
this.renderFile = this.engine[renderFileMethodName] || undefined;
this.render = this.engine.render || undefined;
}
, name: 'adapter-' + language
};
};
|
Make sure mixpanel is fully loaded by checking not only the object but also the relevant field in the mixpanel global
|
/**
* @license Angulartics v0.14.15
* (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
* Contributed by http://github.com/L42y
* License: MIT
*/
(function(angular) {
'use strict';
/**
* @ngdoc overview
* @name angulartics.mixpanel
* Enables analytics support for Mixpanel (http://mixpanel.com)
*/
angular.module('angulartics.mixpanel', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {
angulartics.waitForVendorApi('mixpanel', 500, 'track', function (mixpanel) {
$analyticsProvider.registerPageTrack(function (path) {
mixpanel.track( "Page Viewed", { "page": path } );
});
});
angulartics.waitForVendorApi('mixpanel', 500, 'track', function (mixpanel) {
$analyticsProvider.registerEventTrack(function (action, properties) {
mixpanel.track(action, properties);
});
});
}]);
})(angular);
|
/**
* @license Angulartics v0.14.15
* (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
* Contributed by http://github.com/L42y
* License: MIT
*/
(function(angular) {
'use strict';
/**
* @ngdoc overview
* @name angulartics.mixpanel
* Enables analytics support for Mixpanel (http://mixpanel.com)
*/
angular.module('angulartics.mixpanel', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {
angulartics.waitForVendorApi('mixpanel', 500, function (mixpanel) {
$analyticsProvider.registerPageTrack(function (path) {
mixpanel.track( "Page Viewed", { "page": path } );
});
});
angulartics.waitForVendorApi('mixpanel', 500, function (mixpanel) {
$analyticsProvider.registerEventTrack(function (action, properties) {
mixpanel.track(action, properties);
});
});
}]);
})(angular);
|
Set `@babel/plugin-proposal-class-properties` as option in webpack
Fixes webpack build error due to class properties
https://stackoverflow.com/a/52693007/452233
|
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'public'),
},
module: {
rules: [
{
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react',
{ plugins: ['@babel/plugin-proposal-class-properties'] },
],
},
},
test: /\.js$/,
exclude: /node_modules/,
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
],
};
|
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'public'),
},
module: {
rules: [
{
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
test: /\.js$/,
exclude: /node_modules/,
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
],
};
|
fix(angularDateInterceptor): Fix regexp to correctly detect dates
|
(function () {
'use strict';
angular.module('angularDateInterceptor', [])
.service('angularDateInterceptor', AngularDateInterceptor)
.config(config);
function AngularDateInterceptor() {
var iso8601 = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/;
this.response = function (response) {
convertToDate(response.data);
return response;
};
function isIso8601(value) {
return angular.isString(value) && iso8601.test(value);
}
function convertToDate(input) {
if (!angular.isObject(input)) {
return input;
}
angular.forEach(input, function (value, key) {
if (isIso8601(value)) {
input[key] = new Date(value);
} else if (angular.isObject(value)) {
convertToDate(value);
}
});
}
}
config.$inject = ['$httpProvider'];
function config($httpProvider) {
$httpProvider.interceptors.push('angularDateInterceptor');
}
})();
|
(function () {
'use strict';
angular.module('angularDateInterceptor', [])
.service('angularDateInterceptor', AngularDateInterceptor)
.config(config);
function AngularDateInterceptor() {
var iso8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
this.response = function (response) {
convertToDate(response.data);
return response;
};
function isIso8601(value) {
return angular.isString(value) && iso8601.test(value);
}
function convertToDate(input) {
if (!angular.isObject(input)) {
return input;
}
angular.forEach(input, function (value, key) {
if (isIso8601(value)) {
input[key] = new Date(value);
} else if (angular.isObject(value)) {
convertToDate(value);
}
});
}
}
config.$inject = ['$httpProvider'];
function config($httpProvider) {
$httpProvider.interceptors.push('angularDateInterceptor');
}
})();
|
Remove unused private variables from DES segment data class.
This should have been part of the previous commit, but its already pushed...
|
/**
* Copyright (c) Codice Foundation
*
* This is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. A copy of the GNU Lesser General Public License
* is distributed along with this program and can be found at
* <http://www.gnu.org/licenses/lgpl.html>.
*
**/
package org.codice.nitf.filereader;
import java.text.ParseException;
public class NitfDataExtensionSegment extends AbstractCommonNitfSegment {
private int desVersion = -1;
private String desData = null;
public NitfDataExtensionSegment() {
}
public final void parse(final NitfReader nitfReader, final int desLength) throws ParseException {
new NitfDataExtensionSegmentParser(nitfReader, desLength, this);
}
public final void setDESVersion(final int version) {
desVersion = version;
}
public final int getDESVersion() {
return desVersion;
}
public final void setData(final String data) {
desData = data;
}
}
|
/**
* Copyright (c) Codice Foundation
*
* This is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. A copy of the GNU Lesser General Public License
* is distributed along with this program and can be found at
* <http://www.gnu.org/licenses/lgpl.html>.
*
**/
package org.codice.nitf.filereader;
import java.text.ParseException;
public class NitfDataExtensionSegment extends AbstractCommonNitfSegment {
private String desIdentifier = null;
private int desVersion = -1;
private NitfSecurityMetadata securityMetadata = null;
private String desData = null;
public NitfDataExtensionSegment() {
}
public final void parse(final NitfReader nitfReader, final int desLength) throws ParseException {
new NitfDataExtensionSegmentParser(nitfReader, desLength, this);
}
public final void setDESVersion(final int version) {
desVersion = version;
}
public final int getDESVersion() {
return desVersion;
}
public final void setData(final String data) {
desData = data;
}
}
|
Allow SQLAlchemy as old as 1.0
|
#!/usr/bin/env python
from setuptools import setup, find_packages
install_requires = [
'MySQL-python>=1.0.0',
'SQLAlchemy>=1.0.0',
]
f = open('README.rst')
readme = f.read()
f.close()
setup(
name='sqldd',
version='0.9.2',
author='Rick Keilty',
author_email='rkeilty@gmail.com',
url='http://github.com/rkeilty/sql-data-dependency',
description='A toolkit for analyzing dependencies in SQL databases.',
long_description=readme,
license='BSD',
packages=find_packages(),
install_requires=install_requires,
include_package_data=True,
scripts=[
'bin/sqldd'
],
zip_safe=False,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Topic :: Software Development'
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
install_requires = [
'MySQL-python>=1.0.0',
'SQLAlchemy>=1.1.0',
]
f = open('README.rst')
readme = f.read()
f.close()
setup(
name='sqldd',
version='0.9.1',
author='Rick Keilty',
author_email='rkeilty@gmail.com',
url='http://github.com/rkeilty/sql-data-dependency',
description='A toolkit for analyzing dependencies in SQL databases.',
long_description=readme,
license='BSD',
packages=find_packages(),
install_requires=install_requires,
include_package_data=True,
scripts=[
'bin/sqldd'
],
zip_safe=False,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Topic :: Software Development'
],
)
|
Update the docstring for the mapper to reflect what it does correctly.
|
# Copyright 2013 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Mapreduce to insert dummy data for GCI student data for safe-harboring."""
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted")
|
# Copyright 2013 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Mapreduce to delete GCI data for safe-harboring.
"""
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted")
|
Fix attempt for invalid/missing user agent string
|
<?php
namespace Grav\Common;
/**
* Simple wrapper for the very simple parse_user_agent() function
*/
class Browser
{
protected $useragent = [];
public function __construct()
{
try {
$this->useragent = parse_user_agent();
} catch (\InvalidArgumentException $e) {
$this->useragent = parse_user_agent("Mozilla/5.0 (compatible; Unknown;)");
}
}
public function getBrowser()
{
return strtolower($this->useragent['browser']);
}
public function getPlatform()
{
return strtolower($this->useragent['platform']);
}
public function getLongVersion()
{
return $this->useragent['version'];
}
public function getVersion()
{
$version = explode('.', $this->getLongVersion());
return intval($version[0]);
}
}
|
<?php
namespace Grav\Common;
/**
* Simple wrapper for the very simple parse_user_agent() function
*/
class Browser {
protected $useragent;
public function __construct()
{
$this->useragent = parse_user_agent();
}
public function getBrowser()
{
return strtolower($this->useragent['browser']);
}
public function getPlatform()
{
return strtolower($this->useragent['platform']);
}
public function getLongVersion()
{
return $this->useragent['version'];
}
public function getVersion()
{
$version = explode('.', $this->getLongVersion());
return intval($version[0]);
}
}
|
Fix example mit license script
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var exec = require('../util/exec');
var repoDir = process.env.REPO_DIR;
var file = repoDir + '/package.json';
var pkg;
if (!fs.existsSync(file)) {
return;
}
// Read package json
pkg = require(file);
// Is it ok already?
if (pkg.license === 'MIT') {
process.stdout.write('Nothing to be changed.\n');
process.exit();
}
// Change to MIT and save file
pkg.license = 'MIT';
fs.writeFileSync(file, JSON.stringify(pkg, null, 2) + '\n');
// Commit & push
exec('git', ['commit', '-a', '-m', 'Change license to MIT (made with screpto)'], { cwd: repoDir });
exec('git', ['push'], { cwd: repoDir, stdio: 'inherit' });
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var exec = require('../util/exec');
var repoDir = process.env.REPO_DIR;
var file = repoDir + '/package.json';
var pkg;
if (!fs.existsSync(file)) {
return;
}
// Read package json
pkg = require(file);
// Is it ok already?
if (pkg.license === 'MIT') {
process.stdout.write('Nothing to be changed.\n');
process.exit();
}
// Change to MIT and save file
pkg.license = 'MIT';
fs.writeFileSync(file + '/package.json', JSON.stringify(pkg, null, 2) + '\n');
// Commit & push
exec('git', ['commit', '-a', '-m', 'Change license to MIT (made with screpto)'], { cwd: repoDir });
exec('git', ['push'], { cwd: repoDir, stdio: 'inherit' });
|
Add start and reset fn
|
$(function(){
var
$start = $('#start'),
$btns = $('.btns .btn'),
colors = ['#1ABC9C','#2ECC71','#3498DB','#34495E','#9B59B6','#F1C40F','#E67E22','#E74C3C','#7F8C8D','#2980B9','#95A5A6','#C0392B','#D35400','#F39C12','#666'],
selected = null,
rnd = function(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
},
randColor = function(){
return colors[rnd(0,colors.length-1)];
},
setColors = function(){
$btns.each(function(){
$(this).css({
'background-color': randColor()
});
});
},
exploid = function(){
$btns.each(function(){
$(this).animate({
left : rnd(0,90) + '%',
top : rnd(0,90) + '%'
},400);
});
},
choose1 = function(){
},
start = function(){
exploid();
$btns.click(choose1);
},
reset = function(){
window.location.reload(); // cheap as posible !
},
init = function(){
$start.click(start);
setColors();
};
init();
});
|
$(function(){
var
$btns = $('.btn'),
colors = ['#1ABC9C','#2ECC71','#3498DB','#34495E','#9B59B6','#F1C40F','#E67E22','#E74C3C','#7F8C8D','#2980B9','#95A5A6','#C0392B','#D35400','#F39C12','#666'],
selected = null,
rnd = function(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
},
setColors = function(){
$btns.each(function(){
$(this).css({
'background-color': colors[rnd(0,14)]
});
});
},
exploid = function(){
$btns.each(function(){
$(this).css({
left : rnd(0,90) + '%',
top : rnd(0,90) + '%'
});
});
},
choose1 = function(){
},
setEvents = function(){
$btns.click(choose1);
},
init = function(){
setColors();
exploid();
setEvents();
};
init();
});
|
Add maxOpacity for backdrop fade
|
const options = {
duration: 700,
easing: 'easeInOutQuint'
};
const crossOptions = {
maxOpacity: 0.8
};
export default function defaultTransition(context) {
if (!context || typeof context.transition !== 'function') {
throw new Error('[bootstrap-modal] Invalid transitions context supplied');
}
return context.transition(
context.hasClass('bootstrap-modal'),
// hack to get reverse working..
context.toValue(true),
context.use('explode', {
pick: '.modal-dialog',
use: ['to-down', options]
}, {
pick: '.modal-backdrop',
use: ['crossFade', crossOptions]
}),
context.reverse('explode', {
pick: '.modal-dialog',
use: ['to-up', options]
}, {
pick: '.modal-backdrop',
use: ['crossFade', crossOptions]
})
);
}
|
const options = {
duration: 700,
easing: 'easeInOutQuint'
};
export default function defaultTransition(context) {
if (!context || typeof context.transition !== 'function') {
throw new Error('[bootstrap-modal] Invalid transitions context supplied');
}
return context.transition(
context.hasClass('bootstrap-modal'),
// hack to get reverse working..
context.toValue(true),
context.use('explode', {
pick: '.modal-dialog',
use: ['to-down', options]
}, {
pick: '.modal-backdrop',
use: 'crossFade'
}),
context.reverse('explode', {
pick: '.modal-dialog',
use: ['to-up', options]
}, {
pick: '.modal-backdrop',
use: 'crossFade'
})
);
}
|
Fix import path for semver package
|
// Package fontawesome defines template assets and functions for
// using fontawesome (see http://fontawesome.io).
//
// Importing this package registers a template asset with the following
// format:
//
// fontawesome:<version>
//
// Where version is the Font Awesome version you want to use.
//
// Additionally, this package defines the following template function:
//
// fa <string>: returns the font awesome 4 (and hopefully future versions) icon named by string
// e.g. {{ fa "external-link" } => <i class="fa fa-external-link"></i>
//
package fontawesome
import (
"fmt"
"gnd.la/template/assets"
"github.com/rainycape/semver"
)
const (
fontAwesomeFmt = "//netdna.bootstrapcdn.com/font-awesome/%s/css/font-awesome.min.css"
)
func fontAwesomeParser(m *assets.Manager, version string, opts assets.Options) ([]*assets.Asset, error) {
faVersion, err := semver.Parse(version)
if err != nil || faVersion.Major != 4 || faVersion.PreRelease != "" || faVersion.Build != "" {
return nil, fmt.Errorf("invalid font awesome version %q, must in 4.x.y form", faVersion)
}
return []*assets.Asset{assets.CSS(fmt.Sprintf(fontAwesomeFmt, version))}, nil
}
func init() {
assets.Register("fontawesome", assets.SingleParser(fontAwesomeParser))
}
|
// Package fontawesome defines template assets and functions for
// using fontawesome (see http://fontawesome.io).
//
// Importing this package registers a template asset with the following
// format:
//
// fontawesome:<version>
//
// Where version is the Font Awesome version you want to use.
//
// Additionally, this package defines the following template function:
//
// fa <string>: returns the font awesome 4 (and hopefully future versions) icon named by string
// e.g. {{ fa "external-link" } => <i class="fa fa-external-link"></i>
//
package fontawesome
import (
"fmt"
"semver"
"gnd.la/template/assets"
)
const (
fontAwesomeFmt = "//netdna.bootstrapcdn.com/font-awesome/%s/css/font-awesome.min.css"
)
func fontAwesomeParser(m *assets.Manager, version string, opts assets.Options) ([]*assets.Asset, error) {
faVersion, err := semver.Parse(version)
if err != nil || faVersion.Major != 4 || faVersion.PreRelease != "" || faVersion.Build != "" {
return nil, fmt.Errorf("invalid font awesome version %q, must in 4.x.y form", faVersion)
}
return []*assets.Asset{assets.CSS(fmt.Sprintf(fontAwesomeFmt, version))}, nil
}
func init() {
assets.Register("fontawesome", assets.SingleParser(fontAwesomeParser))
}
|
Fix adding Item to cache.
|
// Package lru1 implement Least Recently Used based on doubly linked list.
package lru1
import "container/list"
// Item is an element in cache.
type Item struct {
key string
value string
}
// Cache is a sized LRU cache.
type Cache struct {
capacity int
data map[string]*list.Element
lst *list.List
}
// NewCache returns an initialized LRU cache.
func NewCache(capacity int) *Cache {
cache := new(Cache)
cache.capacity = capacity
cache.data = make(map[string]*list.Element)
return cache
}
// Put inserts new Item to cache.
// If cache is full removes oldest Item first.
func (c *Cache) Put(key, value string) {
if len(c.data) == c.capacity {
delete(c.data, c.lst.Back().Value.(*Item).key)
c.lst.Remove(c.lst.Back())
}
c.data[key] = c.lst.PushFront(&Item{key, value})
}
// Get returns Item from cache by key.
// nil is returned if there is no such key in the cache.
func (c *Cache) Get(key string) *Item {
if c.data[key] != nil {
c.lst.MoveToFront(c.data[key])
return c.data[key].Value.(*Item)
}
return nil
}
|
package lru1
import "container/list"
type Item struct {
key string
value string
}
type Cache struct {
capacity int
data map[string]*list.Element
lst *list.List
}
func NewCache(capacity int) *Cache {
cache := new(Cache)
cache.capacity = capacity
cache.data = make(map[string]*list.Element)
return cache
}
func (c *Cache) Put(key, value string) {
if len(c.data) == c.capacity {
delete(c.data, c.lst.Back().Value.(*Item).key)
c.lst.Remove(c.lst.Back())
}
}
func (c *Cache) Get(key string) *Item {
if c.data[key] != nil {
c.lst.MoveToFront(c.data[key])
return c.data[key].Value.(*Item)
}
return nil
}
|
Call to stop the reactor now uses the correct convention when closing from a thread other than the main reactor thread.
Fixes Issue 5.
git-svn-id: a0251d2471cc357dbf602d275638891bc89eba80@9 4515f058-c067-11dd-9cb5-179210ed59e1
|
"""A simple example of Pyglet/Twisted integration. A Pyglet window
is displayed, and both Pyglet and Twisted are making scheduled calls
and regular intervals. Interacting with the window doesn't interfere
with either calls.
"""
import pyglet
import pygletreactor
pygletreactor.install() # <- this must come before...
from twisted.internet import reactor, task # <- ...importing this reactor!
# Create a Pyglet window with a simple message
window = pyglet.window.Window()
label = pyglet.text.Label('hello world',
x = window.width / 2,
y = window.height / 2,
anchor_x = 'center',
anchor_y = 'center')
@window.event
def on_draw():
window.clear()
label.draw()
@window.event
def on_close():
reactor.callFromThread(reactor.stop)
# Return true to ensure that no other handlers
# on the stack receive the on_close event
return True
# Schedule a function call in Pyglet
def runEverySecondPyglet(dt):
print "pyglet call: one second has passed"
pyglet.clock.schedule_interval(runEverySecondPyglet, 1)
# Schedule a function call in Twisted
def runEverySecondTwisted():
print "twisted call: 1.5 seconds have passed"
l = task.LoopingCall(runEverySecondTwisted)
l.start(1.5)
# Start the reactor
reactor.run()
|
"""A simple example of Pyglet/Twisted integration. A Pyglet window
is displayed, and both Pyglet and Twisted are making scheduled calls
and regular intervals. Interacting with the window doesn't interfere
with either calls.
"""
import pyglet
import pygletreactor
pygletreactor.install() # <- this must come before...
from twisted.internet import reactor, task # <- ...importing this reactor!
# Create a Pyglet window with a simple message
window = pyglet.window.Window()
label = pyglet.text.Label('hello world',
x = window.width / 2,
y = window.height / 2,
anchor_x = 'center',
anchor_y = 'center')
@window.event
def on_draw():
window.clear()
label.draw()
@window.event
def on_close():
reactor.stop()
# Return true to ensure that no other handlers
# on the stack receive the on_close event
return True
# Schedule a function call in Pyglet
def runEverySecondPyglet(dt):
print "pyglet call: one second has passed"
pyglet.clock.schedule_interval(runEverySecondPyglet, 1)
# Schedule a function call in Twisted
def runEverySecondTwisted():
print "twisted call: 1.5 seconds have passed"
l = task.LoopingCall(runEverySecondTwisted)
l.start(1.5)
# Start the reactor
reactor.run()
|
Test edge cases on largest sum
|
package interviewquestions;
/**
* Given an array of integers (positive and negative) find the
* largest continuous sum
*/
public class ContinuousSum extends TestCase {
public static int largestSum(int[] array) {
assert(array.length > 0);
int maxsum = array[0];
int current = array[0];
for (int i = 1; i < array.length; i++) {
current = Math.max(current + array[i], array[i]);
maxsum = Math.max(current, maxsum);
}
return maxsum;
}
public static void main(String[] args) {
assertEquals(21, largestSum(new int[] { 1, 2, 3, 4, 5, 6 }));
assertEquals(15, largestSum(new int[] { 1, 2, -3, 4, 5, 6 }));
assertEquals(102, largestSum(new int[] { 100, 2, -300, 4, 5, 6 }));
assertEquals(1, largestSum(new int[] { -1, -2, -3, 1, -5, -6 }));
assertEquals(0, largestSum(new int[] { 0, 0, 0, 0 }));
assertEquals(-10, largestSum(new int[] { -15, -10, -20, -30 }));
}
}
|
package interviewquestions;
/**
* Given an array of integers (positive and negative) find the
* largest continuous sum
*/
public class ContinuousSum extends TestCase {
public static int largestSum(int[] array) {
assert(array.length > 0);
int maxsum = array[0];
int current = array[0];
for (int i = 1; i < array.length; i++) {
current = Math.max(current + array[i], array[i]);
maxsum = Math.max(current, maxsum);
}
return maxsum;
}
public static void main(String[] args) {
assertEquals(21, largestSum(new int[] { 1, 2, 3, 4, 5, 6 }));
assertEquals(15, largestSum(new int[] { 1, 2, -3, 4, 5, 6 }));
assertEquals(102, largestSum(new int[] { 100, 2, -300, 4, 5, 6 }));
assertEquals(1, largestSum(new int[] { -1, -2, -3, 1, -5, -6 }));
}
}
|
Update dev version to 1.10
|
# file findingaids/__init__.py
#
# Copyright 2012 Emory University Library
#
# 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.
__version_info__ = (1, 10, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
# file findingaids/__init__.py
#
# Copyright 2012 Emory University Library
#
# 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.
__version_info__ = (1, 9, 0, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
Fix broken test on some java 8 versions
|
package com.novoda.simplechromecustomtabs;
import com.novoda.notils.exception.DeveloperError;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;
@RunWith(RobolectricTestRunner.class)
public class SimpleChromeCustomTabsTest {
@Test
public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() {
/** Please forgive me for what you are seeing. Given some incompatibility issues between Robolectric 3.1.4 and some versions of
* Java 8, the @Test(expected = DeveloperError.class) wasn't working.
* Will fix when we figure out how.
**/
try {
SimpleChromeCustomTabs.getInstance();
fail("A Developer error exception was expected, but there was nothing");
} catch (DeveloperError e) {
// passes
}
}
@Test
public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() {
SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application);
assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class);
}
}
|
package com.novoda.simplechromecustomtabs;
import com.novoda.notils.exception.DeveloperError;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;
@RunWith(RobolectricTestRunner.class)
public class SimpleChromeCustomTabsTest {
@Test
public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() {
try {
SimpleChromeCustomTabs.getInstance();
fail("A Developer error exception was expected, but there was nothing");
} catch (DeveloperError e) {
// passes
}
}
@Test
public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() {
SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application);
assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class);
}
}
|
restapi: Fix return type of vms/{vm:id}/numanodes
Currently the type returned by the "list" operation of this resources is
"NumaNodes", but it should be "VirtualNumaNodes", otherwise the
generator of the Java SDK will not work correctly.
Change-Id: I57af48c044012fe9009e51b48c8813114319980b
Bug-Url: https://bugzilla.redhat.com/1115610
Signed-off-by: Juan Hernandez <59e5b8140de97cc91c3fb6c5342dce948469af8c@redhat.com>
|
package org.ovirt.engine.api.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.ovirt.engine.api.model.VirtualNumaNode;
import org.ovirt.engine.api.model.VirtualNumaNodes;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {
@GET
@Formatted
public VirtualNumaNodes list();
@POST
@Formatted
@Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public Response add(VirtualNumaNode node);
@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id);
@Path("{iden}")
public VmNumaNodeResource getVmNumaNodeSubResource(@PathParam("iden") String id);
}
|
package org.ovirt.engine.api.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.ovirt.engine.api.model.NumaNodes;
import org.ovirt.engine.api.model.VirtualNumaNode;
@Produces({ ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML })
public interface VmNumaNodesResource {
@GET
@Formatted
public NumaNodes list();
@POST
@Formatted
@Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public Response add(VirtualNumaNode node);
@DELETE
@Path("{id}")
public Response remove(@PathParam("id") String id);
@Path("{iden}")
public VmNumaNodeResource getVmNumaNodeSubResource(@PathParam("iden") String id);
}
|
Fix getter for text representation
|
<?php
namespace MusicBrainz\Value\Property;
use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\TextRepresentation;
/**
* Provides a getter for the text representation.
*/
trait TextRepresentationTrait
{
/**
* A text representation
*
* @var TextRepresentation
*/
private $textRepresentation;
/**
* Returns the text representation.
*
* @return TextRepresentation
*/
public function getTextRepresentation(): TextRepresentation
{
return $this->textRepresentation;
}
/**
* Sets the text representation by extracting it from a given input array.
*
* @param array $input An array returned by the webservice
*
* @return void
*/
private function setTextRepresentationFromArray(array $input): void
{
$this->textRepresentation = is_null($textRepresentation = ArrayAccess::getArray($input, 'text-representation'))
? new TextRepresentation
: new TextRepresentation($textRepresentation);
}
}
|
<?php
namespace MusicBrainz\Value\Property;
use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\TextRepresentation;
/**
* Provides a getter for the text representation.
*/
trait TextRepresentationTrait
{
/**
* A text representation
*
* @var TextRepresentation
*/
private $textRepresentation;
/**
* Returns the text representation.
*
* @return TextRepresentation
*/
public function getText(): TextRepresentation
{
return $this->textRepresentation;
}
/**
* Sets the text representation by extracting it from a given input array.
*
* @param array $input An array returned by the webservice
*
* @return void
*/
private function setTextRepresentationFromArray(array $input): void
{
$this->textRepresentation = is_null($textRepresentation = ArrayAccess::getArray($input, 'text-representation'))
? new TextRepresentation
: new TextRepresentation($textRepresentation);
}
}
|
Add exports annotation for isPromise
|
/**
Utility Functions
@description a collection of utility functions, aka junk drawer
@exports {function} isCacheableRequest
@exports {function} isPromise
**/
/**
@name isCacheableRequest
@desc determines if the request is cacheable based on HTTP verb used,
will return false for actionable HTTP verbs like POST or DELETE
@param {string} httpMethod
@returns {boolean} result
**/
const uncacheableMethods = [ 'POST', 'PUT', 'DELETE' ];
export function isCacheableRequest(httpMethod) {
return !~uncacheableMethods.indexOf(httpMethod.toUpperCase());
}
/**
@name isPromise
@desc determines if a given value is a promise
@param {any} potentialPromise
@returns {boolean} result
**/
export function isPromise(potentialPromise) {
return potentialPromise && typeof potentialPromise.then === 'function' &&
typeof potentialPromise['catch'] === 'function'; // eslint-disable-line
}
|
/**
Utility Functions
@description a collection of utility functions, aka junk drawer
@exports {function} isCacheableRequest
**/
/**
@name isCacheableRequest
@desc determines if the request is cacheable based on HTTP verb used,
will return false for actionable HTTP verbs like POST or DELETE
@param {string} httpMethod
@returns {boolean} result
**/
const uncacheableMethods = [ 'POST', 'PUT', 'DELETE' ];
export function isCacheableRequest(httpMethod) {
return !~uncacheableMethods.indexOf(httpMethod.toUpperCase());
}
/**
@name isPromise
@desc determines if a given value is a promise
@param {any} potentialPromise
@returns {boolean} result
**/
export function isPromise(potentialPromise) {
return potentialPromise && typeof potentialPromise.then === 'function' &&
typeof potentialPromise['catch'] === 'function'; // eslint-disable-line
}
|
Fix failing build: Unexpected token, expected { (3:0)
|
const map = ColorRamp.createColorTexture(this.refs.colorbar, (i) =>
ColorRamp.map(this.props.steps, i))
function createColorTexture (canvas, colorFunction = () => 'transparent') {
// const canvas = document.createElement('canvas')
// const canvas = ReactDOM.findDOMNode(canvas)
const context = canvas.getContext('2d')
canvas.width = 256
canvas.height = 16
for (let i = 0; i < canvas.width; i++) {
context.fillStyle = colorFunction(i)
context.fillRect(i, 0, 1, canvas.height)
}
return context.getImageData(0, 0, canvas.width, canvas.height)
}
function map (steps, i) {
const offset = i / 255 * (steps.length - 1.0)
const base = Math.trunc(offset)
let color = ColorRamp.mix(steps[base], steps[base + 1], offset - base)
return 'rgba(' + color.values.rgb.toString() + ', 1.0)'
}
|
function createColorTextureFromSteps()
const map = ColorRamp.createColorTexture(this.refs.colorbar, (i) =>
ColorRamp.map(this.props.steps, i))
function createColorTexture (canvas, colorFunction = () => 'transparent') {
// const canvas = document.createElement('canvas')
// const canvas = ReactDOM.findDOMNode(canvas)
const context = canvas.getContext('2d')
canvas.width = 256
canvas.height = 16
for (let i = 0; i < canvas.width; i++) {
context.fillStyle = colorFunction(i)
context.fillRect(i, 0, 1, canvas.height)
}
return context.getImageData(0, 0, canvas.width, canvas.height)
}
function map (steps, i) {
const offset = i / 255 * (steps.length - 1.0)
const base = Math.trunc(offset)
let color = ColorRamp.mix(steps[base], steps[base + 1], offset - base)
return 'rgba(' + color.values.rgb.toString() + ', 1.0)'
}
|
Bump version for new release with Python 3 compatibility.
|
from setuptools import setup, find_packages
setup(
name = "pyRFC3339",
version = "0.2",
author = "Kurt Raschke",
author_email = "kurt@kurtraschke.com",
description = "Generate and parse RFC 3339 timestamps",
keywords = "rfc 3339 timestamp",
license = "MIT",
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet"
],
packages = find_packages(),
install_requires = ['pytz'],
test_suite = 'nose.collector',
tests_require = ['nose']
)
|
from setuptools import setup, find_packages
setup(
name = "pyRFC3339",
version = "0.1",
author = "Kurt Raschke",
author_email = "kurt@kurtraschke.com",
description = "Generate and parse RFC 3339 timestamps",
keywords = "rfc 3339 timestamp",
license = "MIT",
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet"
],
packages = find_packages(),
install_requires = ['pytz'],
test_suite = 'nose.collector',
tests_require = ['nose']
)
|
Fix a python undefined name in test scripts
Signed-off-by: Laurent Bonnans <0909bc0a3d1b0c91d8e00372b9633e8e9ea958de@here.com>
|
import platform
import re
import subprocess
def verify_provisioned(akt_info, conf):
# Verify that device HAS provisioned.
stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned'])
machine = platform.node()
if (b'Device ID: ' not in stdout or
b'Primary ecu hardware ID: ' + machine.encode() not in stdout or
b'Fetched metadata: yes' not in stdout):
print('Provisioning failed: ' + stderr.decode() + stdout.decode())
return 1
p = re.compile(r'Device ID: ([a-z0-9-]*)\n')
m = p.search(stdout.decode())
if not m or m.lastindex <= 0:
print('Device ID could not be read: ' + stderr.decode() + stdout.decode())
return 1
print('Device successfully provisioned with ID: ' + m.group(1))
return 0
def run_subprocess(command, **kwargs):
print('> Running {}'.format(' '.join(command)))
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
try:
stdout, stderr = proc.communicate(timeout=60)
except subprocess.TimeoutExpired:
proc.kill()
stdout, stderr = proc.communicate()
return stdout, stderr, proc.returncode
|
import platform
import re
import subprocess
from time import sleep
def verify_provisioned(akt_info, conf):
# Verify that device HAS provisioned.
stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned'])
machine = platform.node()
if (b'Device ID: ' not in stdout or
b'Primary ecu hardware ID: ' + machine.encode() not in stdout or
b'Fetched metadata: yes' not in stdout):
print('Provisioning failed: ' + stderr.decode() + stdout.decode())
return 1
p = re.compile(r'Device ID: ([a-z0-9-]*)\n')
m = p.search(stdout.decode())
if not m or m.lastindex <= 0:
print('Device ID could not be read: ' + stderr.decode() + stdout.decode())
return 1
print('Device successfully provisioned with ID: ' + m.group(1))
return 0
def run_subprocess(command, **kwargs):
print('> Running {}'.format(' '.join(command)))
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
try:
stdout, stderr = proc.communicate(timeout=60)
except TimeoutExpired:
proc.kill()
stdout, stderr = proc.communicate()
return stdout, stderr, proc.returncode
|
Fix generation of string literals
|
package de.sormuras.bach.execution;
import java.nio.file.Path;
import java.util.StringJoiner;
/** Snippet producer and default Java source code helpers. */
interface Scribe {
/** Convert the string representation of the given object into a {@code String} literal. */
default String $(Object object) {
if (object == null) return "null";
return '"' + object.toString().replace("\\", "\\\\") + '"';
}
/** Create {@code Path.of("some/path/...")} literal. */
default String $(Path path) {
return "Path.of(" + $((Object) path) + ")";
}
/** Create {@code "first" [, "second" [, ...]]} literal. */
default String $(String[] strings) {
if (strings.length == 0) return "";
if (strings.length == 1) return $(strings[0]);
if (strings.length == 2) return $(strings[0]) + ", " + $(strings[1]);
var joiner = new StringJoiner(", ");
for(var string : strings) joiner.add($(string));
return joiner.toString();
}
/** Return source code snippet. */
Snippet toSnippet();
}
|
package de.sormuras.bach.execution;
import java.nio.file.Path;
/** Snippet producer and default Java source code helpers. */
interface Scribe {
/** Convert the string representation of the given object into a {@code String} literal. */
default String $(Object object) {
if (object == null) return "null";
return '"' + object.toString().replace("\\", "\\\\") + '"';
}
/** Create {@code Path.of("some/path/...")} literal. */
default String $(Path path) {
return "Path.of(" + $((Object) path) + ")";
}
/** Create {@code "first" [, "second" [, ...]]} literal. */
default String $(String[] strings) {
if (strings.length == 0) return "";
if (strings.length == 1) return $(strings[0]);
if (strings.length == 2) return $(strings[0]) + ", " + $(strings[1]);
return String.join(", ", strings);
}
/** Return source code snippet. */
Snippet toSnippet();
}
|
Add some methods to the base test class
Allow creating users, moderators, and admins quickly and easily
|
<?php namespace Tests;
use App\Data\Role;
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected $oldExceptionHandler;
protected function setUp()
{
parent::setUp();
$this->disableExceptionHandling();
}
protected function signIn($user = null)
{
$user = ($user) ?: create('App\Data\User');
$this->actingAs($user);
}
protected function createUser()
{
$user = create('App\Data\User');
$user->attachRole(Role::find(11));
return $user;
}
protected function createAdmin()
{
$user = $this->createModerator();
$user->attachRole(Role::find(10));
return $user;
}
protected function createModerator()
{
$user = $this->createUser();
$user->attachRole(Role::find(12));
return $user;
}
protected function disableExceptionHandling()
{
$this->oldExceptionHandler = $this->app->make(ExceptionHandler::class);
$this->app->instance(ExceptionHandler::class, new class extends Handler {
public function __construct() {}
public function report(\Exception $e) {}
public function render($request, \Exception $e) {
throw $e;
}
});
}
protected function withExceptionHandling()
{
$this->app->instance(ExceptionHandler::class, $this->oldExceptionHandler);
return $this;
}
}
|
<?php namespace Tests;
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected $oldExceptionHandler;
protected function setUp()
{
parent::setUp();
$this->disableExceptionHandling();
}
protected function signIn($user = null)
{
$user = ($user) ?: create('App\Data\User');
$this->actingAs($user);
}
protected function disableExceptionHandling()
{
$this->oldExceptionHandler = $this->app->make(ExceptionHandler::class);
$this->app->instance(ExceptionHandler::class, new class extends Handler {
public function __construct() {}
public function report(\Exception $e) {}
public function render($request, \Exception $e) {
throw $e;
}
});
}
protected function withExceptionHandling()
{
$this->app->instance(ExceptionHandler::class, $this->oldExceptionHandler);
return $this;
}
}
|
Handle incoming messages that aren't JSON objects.
|
import json
import socket
from orderbook import create_confirm
def send_msg(ip, port, message):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(message)
response = sock.recv(1024)
finally:
sock.close()
return response
def send_offer(ip, port, offer):
message = json.dumps(offer)
return send_msg(ip, port, message)
def handle_response(response):
try:
response = json.loads(response)
if response and isinstance(response, basestring):
return None
if response and response['type'] == 'trade':
return handle_trade(response)
except ValueError:
return None
def handle_trade(trade):
id = trade['trade-id'].split(';')[0]
return create_confirm(
id = id,
trade_id = trade['trade-id']
)
|
import json
import socket
from orderbook import create_confirm
def send_msg(ip, port, message):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(message)
response = sock.recv(1024)
print "Received: {}".format(response)
finally:
sock.close()
return response
def send_offer(ip, port, offer):
message = json.dumps(offer)
return send_msg(ip, port, message)
def handle_response(response):
response = json.loads(response)
if response:
if response['type'] == 'trade':
return handle_trade(response)
return "Nothing"
def handle_trade(trade):
id = trade['trade-id'].split(';')[0]
return create_confirm(
id = id,
trade_id = trade['trade-id']
)
|
Fix history and scale down not working in production mode
In dev mode guacamole-client targets localhost:1337 for the backend
In production mode guacamole-client targets backend:1337 for the backend
Update isGuacamole policy to take the production setup into account
|
/**
* Nanocloud turns any traditional software into a cloud solution, without
* changing or redeveloping existing source code.
*
* Copyright (C) 2016 Nanocloud Software
*
* This file is part of Nanocloud.
*
* Nanocloud is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Nanocloud is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Pass to next middleware only if incoming request comes from Guacamole
* For now we consider a request to originate from Guacamole if req.host is set to
* "localhost:1337" or "backend:1337" which is the case for guacamole because it directly targets
* the backend without passing through the proxy
*/
module.exports = function(req, res, next) {
let host = req.get('host');
if (host === 'localhost:1337' || host === 'backend:1337') {
return next(null);
}
return res.send(401, 'Request did not originate from local network');
};
|
/**
* Nanocloud turns any traditional software into a cloud solution, without
* changing or redeveloping existing source code.
*
* Copyright (C) 2016 Nanocloud Software
*
* This file is part of Nanocloud.
*
* Nanocloud is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Nanocloud is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Pass to next middleware only if incoming request comes from Guacamole
* For now we consider a request to originate from Guacamole if req.host is set to
* "localhost:1337" which is the case for guacamole because it directly targets
* the backend without passing through the proxy
*/
module.exports = function(req, res, next) {
if (req.get('host') === 'localhost:1337') {
return next(null);
}
return res.send(401, 'Request did not originate from local network');
};
|
Add pandas as an optional dependency
|
#!/usr/bin/env python
import glob
import os
from setuptools import setup, find_packages
setup(name='openmc',
version='0.6.2',
packages=find_packages(),
scripts=glob.glob('scripts/openmc-*'),
# Required dependencies
install_requires=['numpy', 'scipy', 'h5py', 'matplotlib'],
# Optional dependencies
extras_require={
'pandas': ['pandas'],
'vtk': ['vtk', 'silomesh'],
'validate': ['lxml']
},
# Metadata
author='Will Boyd',
author_email='wbinventor@gmail.com',
description='OpenMC Python API',
url='https://github.com/mit-crpg/openmc',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Scientific/Engineering'
]
)
|
#!/usr/bin/env python
import glob
import os
from setuptools import setup, find_packages
setup(name='openmc',
version='0.6.2',
packages=find_packages(),
scripts=glob.glob('scripts/openmc-*'),
# Required dependencies
install_requires=['numpy', 'scipy', 'h5py', 'matplotlib'],
# Optional dependencies
extras_require={
'vtk': ['vtk', 'silomesh'],
'validate': ['lxml'],
},
# Metadata
author='Will Boyd',
author_email='wbinventor@gmail.com',
description='OpenMC Python API',
url='https://github.com/mit-crpg/openmc',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Scientific/Engineering'
]
)
|
Insert custom commands through the getCommands() function.
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Banners
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Banners Toolbar Class
*
* @author Cristiano Cucco <http://nooku.assembla.com/profile/cristiano.cucco>
* @category Nooku
* @package Nooku_Server
* @subpackage Banners
*/
class ComBannersControllerToolbarBanners extends ComDefaultControllerToolbarDefault
{
public function getCommands()
{
$this->addSeperator()
->addEnable()
->addDisable()
->addSeperator()
->addPreferences(array('height' => 88));
return parent::getCommands();
}
}
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Articles
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Banners Toolbar Class
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @category Nooku
* @package Nooku_Server
* @subpackage Articles
*/
class ComBannersControllerToolbarBanners extends ComDefaultControllerToolbarDefault
{
public function __construct(KConfig $config)
{
parent::__construct($config);
$this->addSeperator()
->addEnable()
->addDisable()
->addSeperator()
->addPreferences(array('height' => 88));
}
}
|
Clean up some loose ends
|
"""Functions for checking files"""
import os
import stat
from .checker import is_link
def is_fastq(path):
"""Check whether a given file is a fastq file."""
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return 'PROB_FILE_IS_FASTQ'
def sam_should_compress(path):
"""Check if a *.SAM file should be compressed or deleted"""
name, ext = os.path.splitext(path)
if ext == '.sam':
if os.path.isfile('.'.join((name, 'bam'))):
return 'PROB_SAM_AND_BAM_EXIST'
else:
return 'PROB_SAM_SHOULD_COMPRESS'
|
"""Functions for checking files"""
import os
import stat
from .checker import is_link
def file_exists(path):
try:
with open(path, mode='r') as test:
pass
except FileNotFoundError:
if is_link(path):
return 'PROB_BROKEN_LINK'
except OSError:
return 'PROB_UNKNOWN_ERROR'
def is_fastq(path):
"""Check whether a given file is a fastq file."""
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return 'PROB_FILE_IS_FASTQ'
def sam_should_compress(path):
"""Check if a *.SAM file should be compressed or deleted"""
name, ext = os.path.splitext(path)
if ext == '.sam':
if os.path.isfile('.'.join((name, 'bam'))):
return 'PROB_SAM_AND_BAM_EXIST'
else:
return 'PROB_SAM_SHOULD_COMPRESS'
|
Throw error on not connected
|
<?php
namespace Purekid\Mongodm\Test\TestCase;
use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;
/**
* Test Case Base Class for using Phactory *
*/
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
protected static $db;
protected static $phactory;
public static function setUpBeforeClass()
{
MongoDB::setConfigBlock('testing', array(
'connection' => array(
'hostnames' => 'localhost',
'database' => 'test_db'
)
));
self::$db = MongoDB::instance('testing');
self::$db->connect();
if (!self::$phactory) {
if (!self::$db->getDB() instanceof \MongoDB) {
throw new \Exception('Could not connect to MongoDB');
}
self::$phactory = new Phactory(self::$db->getDB());
self::$phactory->reset();
}
//set up Phactory db connection
self::$phactory->reset();
}
public static function tearDownAfterClass()
{
foreach (self::$db->getDB()->getCollectionNames() as $collection) {
self::$db->getDB()->$collection->drop();
}
}
protected function setUp()
{
}
protected function tearDown()
{
self::$phactory->recall();
}
}
|
<?php
namespace Purekid\Mongodm\Test\TestCase;
use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;
/**
* Test Case Base Class for using Phactory *
*/
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
protected static $db;
protected static $phactory;
public static function setUpBeforeClass()
{
MongoDB::setConfigBlock('testing', array(
'connection' => array(
'hostnames' => 'localhost',
'database' => 'test_db'
)
));
self::$db = MongoDB::instance('testing');
self::$db->connect();
if (!self::$phactory) {
self::$phactory = new Phactory(self::$db->getDB());
self::$phactory->reset();
}
//set up Phactory db connection
self::$phactory->reset();
}
public static function tearDownAfterClass()
{
foreach (self::$db->getDB()->getCollectionNames() as $collection) {
self::$db->getDB()->$collection->drop();
}
}
protected function setUp()
{
}
protected function tearDown()
{
self::$phactory->recall();
}
}
|
Add Python 3 to the classifiers.
|
from setuptools import setup
setup(name='s3same',
version='0.1',
description='Configure Travis-CI artifact uploading to S3',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
keywords='travis ci s3 artifact',
url='http://github.com/vokal/s3same',
author='Isaac Greenspan',
author_email='isaac.greenspan@vokal.io',
license='MIT',
packages=['s3same'],
install_requires=[
'click',
'boto3',
'pycrypto',
'python-dotenv',
'pyyaml',
'travispy',
],
include_package_data=True,
scripts=[
'bin/s3same',
],
zip_safe=False)
|
from setuptools import setup
setup(name='s3same',
version='0.1',
description='Configure Travis-CI artifact uploading to S3',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='travis ci s3 artifact',
url='http://github.com/vokal/s3same',
author='Isaac Greenspan',
author_email='isaac.greenspan@vokal.io',
license='MIT',
packages=['s3same'],
install_requires=[
'click',
'boto3',
'pycrypto',
'python-dotenv',
'pyyaml',
'travispy',
],
include_package_data=True,
scripts=[
'bin/s3same',
],
zip_safe=False)
|
[native] Use hook instead of connect functions and HOC in EditSettingButton
Test Plan: Flow
Reviewers: ashoat, palys-swm
Reviewed By: ashoat
Subscribers: zrebcu411, Adrian
Differential Revision: https://phabricator.ashoat.com/D482
|
// @flow
import * as React from 'react';
import { TouchableOpacity, StyleSheet, Platform } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { useColors } from '../themes/colors';
import type { TextStyle } from '../types/styles';
type Props = {|
+onPress: () => void,
+canChangeSettings: boolean,
+style?: TextStyle,
|};
function EditSettingButton(props: Props) {
const colors = useColors();
if (!props.canChangeSettings) {
return null;
}
const appliedStyles = [styles.editIcon];
if (props.style) {
appliedStyles.push(props.style);
}
const { link: linkColor } = colors;
return (
<TouchableOpacity onPress={props.onPress}>
<Icon name="pencil" size={16} style={appliedStyles} color={linkColor} />
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
editIcon: {
paddingLeft: 10,
paddingTop: Platform.select({ android: 1, default: 0 }),
textAlign: 'right',
},
});
export default EditSettingButton;
|
// @flow
import { connect } from 'lib/utils/redux-utils';
import * as React from 'react';
import { TouchableOpacity, StyleSheet, Platform } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import type { AppState } from '../redux/redux-setup';
import type { Colors } from '../themes/colors';
import { colorsSelector } from '../themes/colors';
import type { TextStyle } from '../types/styles';
type Props = {|
onPress: () => void,
canChangeSettings: boolean,
style?: TextStyle,
// Redux state
colors: Colors,
|};
function EditSettingButton(props: Props) {
if (!props.canChangeSettings) {
return null;
}
const appliedStyles = [styles.editIcon];
if (props.style) {
appliedStyles.push(props.style);
}
const { link: linkColor } = props.colors;
return (
<TouchableOpacity onPress={props.onPress}>
<Icon name="pencil" size={16} style={appliedStyles} color={linkColor} />
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
editIcon: {
paddingLeft: 10,
paddingTop: Platform.select({ android: 1, default: 0 }),
textAlign: 'right',
},
});
export default connect((state: AppState) => ({
colors: colorsSelector(state),
}))(EditSettingButton);
|
Remove react warnings by properly defining externals
|
const webpack = require('webpack');
const env = process.env.NODE_ENV;
const config = {
devtool: 'source-map',
output: {
libraryTarget: 'umd',
library: 'Pic'
},
plugins: [],
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
externals: {
'react': {
root: 'React',
amd: 'react',
commonjs2: 'react',
commonjs: 'react'
},
'react-dom': {
root: 'ReactDOM',
amd: 'react-dom',
commonjs2: 'react-dom',
commonjs: 'react-dom'
}
}
};
if (env === 'production') {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
);
}
module.exports = config;
|
const webpack = require('webpack');
const env = process.env.NODE_ENV;
const config = {
devtool: 'source-map',
output: {
libraryTarget: 'umd',
library: 'Pic'
},
plugins: [],
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
}
};
if (env === 'production') {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
);
}
module.exports = config;
|
Fix error message when logging in with locked account.
|
/**
* @module myModule
* @summary: This module's purpose is to:
*
* @description:
*
* Author: Justin Mooser
* Created On: 2015-05-15.
* @license Apache-2.0
*/
"use strict";
module.exports = function construct(config, $http) {
var m = {};
config = config ? config : {};
config = _.defaults(config, {});
m.login = function(params) {
return $http.post('/token', params)
.then(function(res) {
if (res.body) {
throw 'Failed to login. Endpoint missing.';
}
try {
return p.resolve(res.data);
}
catch (ex) {
console.log('/token API response:', res);
throw 'Failed to login. Endpoint version mismatch.';
}
}, function(err) {
if (err.status == 401) {
if (err.data.message) throw err.data.message;
throw 'Failed to login: invalid credentials.';
}
console.error(err);
throw 'Failed to login. Connection failure.';
});
};
m.logout = function() {
return p.resolve();
};
m.reauthenticate = function(params) {
return m.login(params);
};
return m;
};
|
/**
* @module myModule
* @summary: This module's purpose is to:
*
* @description:
*
* Author: Justin Mooser
* Created On: 2015-05-15.
* @license Apache-2.0
*/
"use strict";
module.exports = function construct(config, $http) {
var m = {};
config = config ? config : {};
config = _.defaults(config, {});
m.login = function(params) {
return $http.post('/token', params)
.then(function(res) {
if (res.body) {
throw 'Failed to login. Endpoint missing.';
}
try {
return p.resolve(res.data);
}
catch (ex) {
console.log('/token API response:', res);
throw 'Failed to login. Endpoint version mismatch.';
}
}, function(err) {
if (err.status == 401) {
throw 'Failed to login: invalid credentials.';
}
console.error(err);
throw 'Failed to login. Connection failure.';
});
};
m.logout = function() {
return p.resolve();
};
m.reauthenticate = function(params) {
return m.login(params);
};
return m;
};
|
Call helper method instead of hard-coding class-equivalent structures here.
|
package annotator.find;
import com.sun.source.tree.*;
import com.sun.source.util.TreePath;
/**
* Represents the criterion that a program element is not enclosed by any
* method (i.e. it's a field, class type parameter, etc.).
*/
final class NotInMethodCriterion implements Criterion {
/**
* {@inheritDoc}
*/
@Override
public Kind getKind() {
return Kind.NOT_IN_METHOD;
}
/** {@inheritDoc} */
@Override
public boolean isSatisfiedBy(TreePath path, Tree leaf) {
assert path == null || path.getLeaf() == leaf;
return isSatisfiedBy(path);
}
/** {@inheritDoc} */
@Override
public boolean isSatisfiedBy(TreePath path) {
do {
Tree tree = path.getLeaf();
if (tree.getKind() == Tree.Kind.METHOD)
return false;
if (Criteria.isClassEquiv(tree)) {
return true;
}
path = path.getParentPath();
} while (path != null && path.getLeaf() != null);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "not in method";
}
}
|
package annotator.find;
import com.sun.source.tree.*;
import com.sun.source.util.TreePath;
/**
* Represents the criterion that a program element is not enclosed by any
* method (i.e. it's a field, class type parameter, etc.).
*/
final class NotInMethodCriterion implements Criterion {
/**
* {@inheritDoc}
*/
public Kind getKind() {
return Kind.NOT_IN_METHOD;
}
/** {@inheritDoc} */
@Override
public boolean isSatisfiedBy(TreePath path, Tree leaf) {
assert path == null || path.getLeaf() == leaf;
return isSatisfiedBy(path);
}
/** {@inheritDoc} */
@Override
public boolean isSatisfiedBy(TreePath path) {
do {
Tree tree = path.getLeaf();
if (tree.getKind() == Tree.Kind.METHOD)
return false;
if (tree.getKind() == Tree.Kind.CLASS || tree.getKind() == Tree.Kind.NEW_CLASS) {
return true;
}
path = path.getParentPath();
} while (path != null && path.getLeaf() != null);
return true;
}
/**
* {@inheritDoc}
*/
public String toString() {
return "not in method";
}
}
|
Add paging token to EffectRecord
|
package db
import (
"database/sql"
"encoding/json"
"fmt"
sq "github.com/lann/squirrel"
)
var EffectRecordSelect sq.SelectBuilder = sq.
Select("heff.*").
From("history_effects heff")
type EffectRecord struct {
HistoryAccountID int64 `db:"history_account_id"`
HistoryOperationID int64 `db:"history_operation_id"`
Order int32 `db:"order"`
Type int32 `db:"type"`
DetailsString sql.NullString `db:"details"`
}
func (r EffectRecord) Details() (result map[string]interface{}, err error) {
if !r.DetailsString.Valid {
return
}
err = json.Unmarshal([]byte(r.DetailsString.String), &result)
return
}
// ID returns a lexically ordered id for this effect record
func (r EffectRecord) ID() string {
return fmt.Sprintf("%019d-%010d", r.HistoryOperationID, r.Order)
}
func (r EffectRecord) PagingToken() string {
return fmt.Sprintf("%d-%d", r.HistoryOperationID, r.Order)
}
|
package db
import (
"database/sql"
"encoding/json"
"fmt"
sq "github.com/lann/squirrel"
)
var EffectRecordSelect sq.SelectBuilder = sq.
Select("heff.*").
From("history_effects heff")
type EffectRecord struct {
HistoryRecord
HistoryAccountID int64 `db:"history_account_id"`
HistoryOperationID int64 `db:"history_operation_id"`
Order int32 `db:"order"`
Type int32 `db:"type"`
DetailsString sql.NullString `db:"details"`
}
func (r EffectRecord) Details() (result map[string]interface{}, err error) {
if !r.DetailsString.Valid {
return
}
err = json.Unmarshal([]byte(r.DetailsString.String), &result)
return
}
// ID returns a lexically ordered id for this effect record
func (r EffectRecord) ID() string {
return fmt.Sprintf("%019d-%010d", r.HistoryOperationID, r.Order)
}
|
Change the Error show in command window.
|
# -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
try:
from core.info.info import show_info, Pyslvs_Splash
args = show_info()
from PyQt5.QtWidgets import QApplication
from core.main import MainWindow
if args.fusion: QApplication.setStyle('fusion')
app = QApplication(list(vars(args).values()))
splash = Pyslvs_Splash()
splash.show()
run = MainWindow(args)
run.show()
splash.finish(run)
exit(app.exec())
except Exception as e:
if e!=SystemExit:
import logging
logging.basicConfig(filename='PyslvsLogFile.log', filemode='w',
format='%(asctime)s | %(message)s', level=logging.INFO)
logging.exception("Exception Happened.")
print('{}\n{}'.format(type(e), e))
exit(1)
|
# -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
try:
from core.info.info import show_info, Pyslvs_Splash
args = show_info()
from PyQt5.QtWidgets import QApplication
from core.main import MainWindow
if args.fusion: QApplication.setStyle('fusion')
app = QApplication(list(vars(args).values()))
splash = Pyslvs_Splash()
splash.show()
run = MainWindow(args)
run.show()
splash.finish(run)
exit(app.exec())
except Exception as e:
if e!=SystemExit:
import logging
logging.basicConfig(filename='PyslvsLogFile.log', filemode='w',
format='%(asctime)s | %(message)s', level=logging.INFO)
logging.exception("Exception Happened.")
print("Exception Happened. Please check the log file.")
exit(1)
|
Tidy up info a little for the PluginModule popup edit form
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40394 b456876b-0849-0410-b77d-98878d47e9d5
|
<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
function module_register_info()
{
return array(
'name' => tra('New User Registration'),
'description' => tra('Permit anonymous visitors to create an account on the site.'),
'prefs' => array('allowRegister'),
'params' => array(),
);
}
function module_register($mod_reference, $module_params)
{
global $prefs, $smarty, $tikilib, $userlib;
$module = true;
include_once('tiki-register.php');
}
|
<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
function module_register_info()
{
return array(
'name' => tra('New user registration'),
'description' => tra('Permits anonymous visitors to create an account on the system.'),
'prefs' => array('allowRegister'),
'params' => array(),
);
}
function module_register($mod_reference, $module_params)
{
global $prefs, $smarty, $tikilib, $userlib;
$module = true;
include_once('tiki-register.php');
}
|
Use https for license link.
|
/*!
* docdown v0.3.0
* Copyright 2011-2016 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <https://mths.be/mit>
*/
'use strict';
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
generator = require('./lib/generator.js');
/**
* Generates Markdown documentation based on JSDoc comments.
*
* @name docdown
* @param options The options to use to generate documentation.
* @returns {string} The generated Markdown code.
*/
function docdown(options) {
options = _.defaults(options, {
'hash': 'default',
'lang': 'js',
'sort': true,
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
return generator(fs.readFileSync(options.path, 'utf8'), options);
}
module.exports = docdown;
|
/*!
* docdown v0.3.0
* Copyright 2011-2016 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
'use strict';
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
generator = require('./lib/generator.js');
/**
* Generates Markdown documentation based on JSDoc comments.
*
* @name docdown
* @param options The options to use to generate documentation.
* @returns {string} The generated Markdown code.
*/
function docdown(options) {
options = _.defaults(options, {
'hash': 'default',
'lang': 'js',
'sort': true,
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
return generator(fs.readFileSync(options.path, 'utf8'), options);
}
module.exports = docdown;
|
Replace the echo with return
|
<?php
namespace Pocs\View;
class ViewHelper
{
/**
* @param $bytes
* @return string
*/
public function sizeForHumans($bytes)
{
if ($bytes > 1048576) {
return sprintf('%.2f MB', $bytes / 1048576);
} else {
if ($bytes > 1024) {
return sprintf('%.2f kB', $bytes / 1024);
} else {
return sprintf('%d bytes', $bytes);
}
}
}
/**
* @param $number
* @return string
*/
public function formatNumber($number)
{
if (class_exists('NumberFormatter')) {
$a = new \NumberFormatter("en-US", \NumberFormatter::DECIMAL);
return $a->format($number);
}
return $number;
}
}
|
<?php
namespace Pocs\View;
class ViewHelper
{
/**
* @param $bytes
* @return string
*/
public function sizeForHumans($bytes)
{
if ($bytes > 1048576) {
return sprintf('%.2f MB', $bytes / 1048576);
} else {
if ($bytes > 1024) {
return sprintf('%.2f kB', $bytes / 1024);
} else {
return sprintf('%d bytes', $bytes);
}
}
}
/**
* @param $number
* @return string
*/
public function formatNumber($number)
{
if (class_exists('NumberFormatter')) {
$a = new \NumberFormatter("en-US", \NumberFormatter::DECIMAL);
echo $a->format($number);
}
return $number;
}
}
|
[Config] Set a basic config tree
|
<?php
namespace SalvoCanna\RedisNotificationBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('rnb');
$rootNode
->children()
->scalarNode('redis_connection')
->defaultValue('snc_redis.default')
->info('Redis connection to use')
->end();
return $treeBuilder;
}
}
|
<?php
namespace SalvoCanna\RedisNotificationBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sc_redis_notification_bundle');
/*$rootNode
->children()
->scalarNode('notification_class')
->cannotBeEmpty()
->defaultValue('AppBundle\\Entity\\Notification')
->info('Entity for a notification (default: AppBundle\\Entity\\Notification)')
->end();
*/
return $treeBuilder;
}
}
|
Update to support multiple default gateways
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
print(get_mac(default_gw))
|
Set branch version to MAJOR
|
import { fail, danger } from 'danger';
import { flatten, intersection, isEmpty } from 'lodash';
const pkg = require('./package.json'); // eslint-disable-line import/newline-after-import
const prLogConfig = pkg['pr-log'];
const Versions = {
PATCH: 'PATCH',
MINOR: 'MINOR',
MAJOR: 'MAJOR',
};
const branchVersion = Versions.MAJOR;
const checkRequiredLabels = labels => {
const forbiddenLabels = flatten([
'do not merge',
'in progress',
branchVersion !== Versions.MAJOR ? 'BREAKING CHANGE' : [],
branchVersion === Versions.PATCH ? 'feature request' : [],
]);
const requiredLabels = flatten([
prLogConfig.skipLabels || [],
Object.keys(prLogConfig.validLabels || {}),
]);
const blockingLabels = intersection(forbiddenLabels, labels);
if (!isEmpty(blockingLabels)) {
fail(
`PR is marked with ${blockingLabels.map(label => `"${label}"`).join(', ')} label${
blockingLabels.length > 1 ? 's' : ''
}.`
);
}
const foundLabels = intersection(requiredLabels, labels);
if (isEmpty(foundLabels)) {
fail(`PR is not labeled with one of: ${JSON.stringify(requiredLabels)}`);
}
};
if (prLogConfig) {
const { labels } = danger.github.issue;
checkRequiredLabels(labels.map(l => l.name));
}
|
import { fail, danger } from 'danger';
import { flatten, intersection, isEmpty } from 'lodash';
const pkg = require('./package.json'); // eslint-disable-line import/newline-after-import
const prLogConfig = pkg['pr-log'];
const Versions = {
PATCH: 'PATCH',
MINOR: 'MINOR',
MAJOR: 'MAJOR',
};
const branchVersion = Versions.PATCH;
const checkRequiredLabels = labels => {
const forbiddenLabels = flatten([
'do not merge',
'in progress',
branchVersion !== Versions.MAJOR ? 'BREAKING CHANGE' : [],
branchVersion === Versions.PATCH ? 'feature request' : [],
]);
const requiredLabels = flatten([
prLogConfig.skipLabels || [],
Object.keys(prLogConfig.validLabels || {}),
]);
const blockingLabels = intersection(forbiddenLabels, labels);
if (!isEmpty(blockingLabels)) {
fail(
`PR is marked with ${blockingLabels.map(label => `"${label}"`).join(', ')} label${
blockingLabels.length > 1 ? 's' : ''
}.`
);
}
const foundLabels = intersection(requiredLabels, labels);
if (isEmpty(foundLabels)) {
fail(`PR is not labeled with one of: ${JSON.stringify(requiredLabels)}`);
}
};
if (prLogConfig) {
const { labels } = danger.github.issue;
checkRequiredLabels(labels.map(l => l.name));
}
|
Use Correct Process Name for Swimming pool example
|
package swimmingpool.service;
import org.chtijbug.drools.platform.runtime.servlet.DroolsPlatformKnowledgeBaseJavaEE;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.example.swimmingpool.Abonnement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService(endpointInterface = "swimmingpool.service.IServiceCalculate")
public class ServiceCalculate implements IServiceCalculate {
private static Logger logger = LoggerFactory.getLogger(ServiceCalculate.class);
private DroolsPlatformKnowledgeBaseJavaEE platformKnowledgeBaseJavaEE;
public void setRuleBasePackage(DroolsPlatformKnowledgeBaseJavaEE ruleBasePackage) {
this.platformKnowledgeBaseJavaEE = ruleBasePackage;
}
@Override
public Abonnement calculate(@WebParam(name = "abonnement") Abonnement abonnement) {
RuleBaseSession sessionStatefull = null;
try {
sessionStatefull = platformKnowledgeBaseJavaEE.createRuleBaseSession();
sessionStatefull.fireAllRulesAndStartProcess(abonnement, "P001");
sessionStatefull.dispose();
} catch (DroolsChtijbugException e) {
logger.error("Error in fireallrules", e);
}
return abonnement;
}
}
|
package swimmingpool.service;
import org.chtijbug.drools.platform.runtime.servlet.DroolsPlatformKnowledgeBaseJavaEE;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.example.swimmingpool.Abonnement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService(endpointInterface = "swimmingpool.service.IServiceCalculate")
public class ServiceCalculate implements IServiceCalculate {
private static Logger logger = LoggerFactory.getLogger(ServiceCalculate.class);
private DroolsPlatformKnowledgeBaseJavaEE platformKnowledgeBaseJavaEE;
public void setRuleBasePackage(DroolsPlatformKnowledgeBaseJavaEE ruleBasePackage) {
this.platformKnowledgeBaseJavaEE = ruleBasePackage;
}
@Override
public Abonnement calculate(@WebParam(name = "abonnement") Abonnement abonnement) {
RuleBaseSession sessionStatefull = null;
try {
sessionStatefull = platformKnowledgeBaseJavaEE.createRuleBaseSession();
sessionStatefull.fireAllRulesAndStartProcess(abonnement, "P1.P1");
sessionStatefull.dispose();
} catch (DroolsChtijbugException e) {
logger.error("Error in fireallrules", e);
}
return abonnement;
}
}
|
Fix maxCount defaultting to 100
|
package fi.mml.portti.service.search;
import fi.nls.oskari.search.channel.SearchableChannel;
import fi.nls.oskari.service.OskariComponent;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.json.JSONObject;
import java.util.Map;
/**
* Interface to service that searches all the channels.
*/
public abstract class SearchService extends OskariComponent {
private int maxCount = -1;
@Override
public void init() {
super.init();
}
/**
* Makes a search with given criteria
*
* @param searchCriteria
* @return Query
*/
public abstract Query doSearch(SearchCriteria searchCriteria);
public abstract JSONObject doSearchAutocomplete(SearchCriteria searchCriteria);
public abstract void addChannel(String channelId, SearchableChannel searchableChannel);
public abstract Map<String, SearchableChannel> getAvailableChannels();
/**
* Returns a generic maximum results instruction for search functions.
* SearchChannels/implementations may opt to use this to
* @return maxCount - Search results max count
*/
public int getMaxResultsCount() {
if (maxCount == -1) {
maxCount = ConversionHelper.getInt(PropertyUtil.getOptional("search.max.results"), 100);
}
return maxCount;
}
}
|
package fi.mml.portti.service.search;
import fi.nls.oskari.search.channel.SearchableChannel;
import fi.nls.oskari.service.OskariComponent;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.json.JSONObject;
import java.util.Map;
/**
* Interface to service that searches all the channels.
*/
public abstract class SearchService extends OskariComponent {
private int maxCount = -1;
@Override
public void init() {
super.init();
}
/**
* Makes a search with given criteria
*
* @param searchCriteria
* @return Query
*/
public abstract Query doSearch(SearchCriteria searchCriteria);
public abstract JSONObject doSearchAutocomplete(SearchCriteria searchCriteria);
public abstract void addChannel(String channelId, SearchableChannel searchableChannel);
public abstract Map<String, SearchableChannel> getAvailableChannels();
/**
* Returns a generic maximum results instruction for search functions.
* SearchChannels/implementations may opt to use this to
* @return maxCount - Search results max count
*/
public int getMaxResultsCount() {
if (maxCount == -1) {
maxCount = ConversionHelper.getInt(PropertyUtil.getOptional("search.max.results"), maxCount);
}
return maxCount;
}
}
|
Add missing --gitignore --npmignore argument keys
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
var log = require('verbalize');
var argv = require('minimist')(process.argv.slice(2));
var parser = require('./');
log.runner = 'npmignore';
/**
* Find the local `ignore` files we need
*/
var gitignore = argv.g || argv.gitignore || '.gitignore';
var npmignore = argv.n || argv.npmignore || '.npmignore';
// optionally specify a different destination
var dest = argv.d || argv.dest || npmignore;
// patterns to ignore
var i = argv.i || argv.ignore;
// patterns to un-ignore
var u = argv.u || argv.unignore;
if (typeof i === 'string') i = i.split(',');
if (typeof u === 'string') u = u.split(',');
var git = read(gitignore);
var npm = read(npmignore);
// Parse the files and create a new `.npmignore` file
// based on the given arguments along with data that
// is already present in either or both files.
var res = parser(npm, git, {ignore: i, unignore: u});
// write the file.
fs.writeFileSync(dest, res);
console.log();
log.inform('updated', dest);
log.success(' Done.');
function read(fp) {
fp = path.join(process.cwd(), fp);
if (!fs.existsSync(fp)) {
return null;
}
return fs.readFileSync(fp, 'utf8');
}
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
var log = require('verbalize');
var argv = require('minimist')(process.argv.slice(2));
var parser = require('./');
log.runner = 'npmignore';
/**
* Find the local `ignore` files we need
*/
var gitignore = argv.g || '.gitignore';
var npmignore = argv.n || '.npmignore';
// optionally specify a different destination
var dest = argv.d || argv.dest || npmignore;
// patterns to ignore
var i = argv.i || argv.ignore;
// patterns to un-ignore
var u = argv.u || argv.unignore;
if (typeof i === 'string') i = i.split(',');
if (typeof u === 'string') u = u.split(',');
var git = read(gitignore);
var npm = read(npmignore);
// Parse the files and create a new `.npmignore` file
// based on the given arguments along with data that
// is already present in either or both files.
var res = parser(npm, git, {ignore: i, unignore: u});
// write the file.
fs.writeFileSync(dest, res);
console.log();
log.inform('updated', dest);
log.success(' Done.');
function read(fp) {
fp = path.join(process.cwd(), fp);
if (!fs.existsSync(fp)) {
return null;
}
return fs.readFileSync(fp, 'utf8');
}
|
Add regex for parsing password url parameter
|
# Sarah M. - 2017
import re
import sys
import datetime
from colors import farben
def request(flow):
now = datetime.datetime.now()
content = flow.request.get_text()
host = flow.request.pretty_host
method = flow.request.method
if method == "POST" and ("pass" in content) or ("password" in content):
with open("/home/pi/SpyPi/Code/proxy.txt", "a") as myfile:
myfile.write(farben.AUF + str(now) + " // " + farben.END)
myfile.write(farben.LD + host + farben.END)
myfile.write("\n")
passwords = re.findall(r"(?:pass|password)=([^&]*)", content)
myfile.write(farben.IN + passwords[0] + farben.END)
myfile.write("\n")
myfile.write("\n")
|
# Sarah M. - 2017
import sys
import datetime
from colors import farben
def request(flow):
now = datetime.datetime.now()
content = flow.request.get_text()
host = flow.request.pretty_host
method = flow.request.method
if method == "POST" and ("pass" in content) or ("password" in content) :
with open ("/home/pi/SpyPi/Code/proxy.txt", "a") as myfile:
myfile.write(farben.AUF + str(now) +" // " + farben.END)
myfile.write(farben.LD + host + farben.END)
myfile.write("\n")
myfile.write(farben.IN + content + farben.END)
myfile.write("\n")
myfile.write("\n")
|
Fix rendering big project names
|
// @flow
import React, { PureComponent } from 'react';
import { StyleSheet, Platform } from 'react-native';
import { connect } from 'react-redux';
import Text from '../Text';
import { currentProjectNameSelector } from '../../modules/projects/reducer';
import appStyle from '../../appStyle';
class ProjectHeaderTitle extends PureComponent<Props> {
render() {
return (
<Text style={styles.title} numberOfLines={1} allowFontScaling={false}>
{this.props.projectName}
</Text>
);
}
}
type Props = {
projectName: ?string,
};
const styles = StyleSheet.create({
title: {
fontSize: appStyle.font.size.big,
color: appStyle.colors.overPrimaryColor,
fontWeight: 'bold',
textAlign: Platform.OS === 'ios' ? 'center' : 'left',
marginLeft: Platform.OS === 'android' ? 16 : 0,
},
});
const mapStateToProps = state => ({
projectName: currentProjectNameSelector(state) || 'DailyScrum',
});
export default connect(mapStateToProps)(ProjectHeaderTitle);
|
// @flow
import React, { PureComponent } from 'react';
import { StyleSheet, Platform } from 'react-native';
import { connect } from 'react-redux';
import Text from '../Text';
import { currentProjectNameSelector } from '../../modules/projects/reducer';
import appStyle from '../../appStyle';
class ProjectHeaderTitle extends PureComponent<Props> {
render() {
return <Text style={styles.title}>{this.props.projectName}</Text>;
}
}
type Props = {
projectName: ?string,
};
const styles = StyleSheet.create({
title: {
fontSize: appStyle.font.size.big,
color: appStyle.colors.overPrimaryColor,
fontWeight: 'bold',
textAlign: Platform.OS === 'ios' ? 'center' : 'left',
marginHorizontal: 16,
},
});
const mapStateToProps = state => ({
projectName: currentProjectNameSelector(state) || 'DailyScrum',
});
export default connect(mapStateToProps)(ProjectHeaderTitle);
|
Use correct slug for Web backend.
|
from notification.backends.base import NotificationBackend
class WebBackend(NotificationBackend):
slug = u'web'
display_name = u'Web'
formats = ['short.txt', 'full.txt']
def send(self, sender, recipient, notice_type, context, on_site=False,
*args, **kwargs):
"""Always "sends" (i.e. stores to the database), setting on_site
accordingly.
"""
# TODO can't do this at the top or we get circular imports
from notification.models import Notice
Notice.objects.create(recipient=recipient,
message=self.format_message(notice_type.label,
'notice.html', context),
notice_type=notice_type,
on_site=on_site,
sender=sender)
return True
|
from notification.backends.base import NotificationBackend
class WebBackend(NotificationBackend):
slug = u'web'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def send(self, sender, recipient, notice_type, context, on_site=False,
*args, **kwargs):
"""Always "sends" (i.e. stores to the database), setting on_site
accordingly.
"""
# TODO can't do this at the top or we get circular imports
from notification.models import Notice
Notice.objects.create(recipient=recipient,
message=self.format_message(notice_type.label,
'notice.html', context),
notice_type=notice_type,
on_site=on_site,
sender=sender)
return True
|
Fix array handling, pass indentStr to xmlWrite
|
'use strict';
var xmlWrite = require('./xmlWrite');
var attributePrefix = '@';
function traverse(obj,parent) {
var result = [];
var array = Array.isArray(obj);
for (var key in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue;
var propArray = Array.isArray(obj[key]);
var output = array ? parent : key;
if (typeof obj[key] !== 'object'){
if (key.indexOf(attributePrefix)==0) {
xmlWrite.attribute(key.substring(1),obj[key]);
}
else {
xmlWrite.startElement(output);
xmlWrite.content(obj[key]);
xmlWrite.endElement(output);
}
}
else {
if (!propArray) {
xmlWrite.startElement(output);
}
traverse(obj[key],output);
if (!propArray) {
xmlWrite.endElement(output);
}
}
}
return result;
}
module.exports = {
getXml : function(obj,attrPrefix,standalone,indent,fragment,indentStr) {
if (attrPrefix) attributePrefix = attrPrefix;
if (fragment) {
xmlWrite.startFragment(indent,indentStr);
}
else {
xmlWrite.startDocument('UTF8',standalone,indent,indentStr);
}
traverse(obj,'');
return xmlWrite.endDocument();
}
};
|
'use strict';
var xmlWrite = require('./xmlWrite');
var attributePrefix = '@';
function traverse(obj,parent) {
var result = [];
for (var key in obj){
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue;
var array = Array.isArray(obj);
if (typeof obj[key] !== 'object'){
if (key.indexOf(attributePrefix)==0) {
xmlWrite.attribute(key.substring(1),obj[key]);
}
else {
xmlWrite.startElement(key);
xmlWrite.content(obj[key]);
xmlWrite.endElement(key);
}
}
else {
if (!array) {
xmlWrite.startElement(key);
}
else {
if (key!=0) xmlWrite.startElement(parent);
}
traverse(obj[key],key);
if (!array) {
xmlWrite.endElement(key);
}
else {
if (key!=(obj.length-1)) xmlWrite.endElement(parent);
}
}
}
return result;
}
module.exports = {
getXml : function(obj,attrPrefix,standalone,indent,fragment) {
if (attrPrefix) attributePrefix = attrPrefix;
if (fragment) {
xmlWrite.startFragment(indent);
}
else {
xmlWrite.startDocument('UTF8',standalone,indent);
}
traverse(obj,'');
return xmlWrite.endDocument();
}
};
|
FIX Only apply theme settings if theme == ssau-minimalist
|
<?php
/**
*
*
* @author <marcus@silverstripe.com.au>
* @license BSD License http://www.silverstripe.org/bsd-license
*/
class PageControllerThemeExtension extends Extension {
public function onAfterInit() {
if (Config::inst()->get('SSViewer', 'theme') == 'ssau-minimalist') {
Requirements::block(THIRDPARTY_DIR .'/jquery/jquery.js');
Requirements::javascript('frontend-dashboards/javascript/jquery-1.10.2.min.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-cookie/jquery.cookie.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery-ui.js');
//Requirements::javascript('frontend-dashboards/javascript/jquery-migrate-1.2.1.min.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js');
Requirements::block('frontend-dashboards/javascript/dashboards.js');
Requirements::javascript('themes/ssau-minimalist/js/modernizr.js');
Requirements::javascript('themes/ssau-minimalist/js/foundation.min.js');
}
}
}
|
<?php
/**
*
*
* @author <marcus@silverstripe.com.au>
* @license BSD License http://www.silverstripe.org/bsd-license
*/
class PageControllerThemeExtension extends Extension {
public function onAfterInit() {
Requirements::block(THIRDPARTY_DIR .'/jquery/jquery.js');
Requirements::javascript('frontend-dashboards/javascript/jquery-1.10.2.min.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-cookie/jquery.cookie.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery-ui.js');
//Requirements::javascript('frontend-dashboards/javascript/jquery-migrate-1.2.1.min.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js');
Requirements::block('frontend-dashboards/javascript/dashboards.js');
Requirements::javascript('themes/ssau-minimalist/js/modernizr.js');
Requirements::javascript('themes/ssau-minimalist/js/foundation.min.js');
}
}
|
Update name validation to meet steam criteria: 2 <= length <= 32
|
import validator from 'validator'
import Player from '../models/player'
const isValidIdForPlatform = (input, platform) => {
const platformId = Player.getPlatformIdFromString(platform)
return platformId !== -1 &&
((platformId === 0 && isValidSteamId(input)) ||
(platformId === 1 && isValidPSNId(input)) ||
(platformId === 2 && isValidXboxId(input)))
}
const isValidPlatform = (input) => Player.getPlatformIdFromString(input) !== -1
const isValidSteamId = (input) => validator.isNumeric(input) && input.length === 17
const isValidPSNId = (input) =>
validator.isAlpha(input[0])
&& input.length >= 3 && input.length <= 16
&& validator.isAlphanumeric(validator.blacklist(input, '_-'))
const isValidXboxId = (input) =>
validator.isAlphanumeric(input.trim()) && input.length >= 3 && input.length <= 15
const isValidName = (input) =>
validator.isLength(input, { min: 2, max: 32 })
export default { isValidIdForPlatform, isValidPlatform, isValidSteamId, isValidXboxId, isValidPSNId, isValidName }
|
import validator from 'validator'
import Player from '../models/player'
const isValidIdForPlatform = (input, platform) => {
const platformId = Player.getPlatformIdFromString(platform)
return platformId !== -1 &&
((platformId === 0 && isValidSteamId(input)) ||
(platformId === 1 && isValidPSNId(input)) ||
(platformId === 2 && isValidXboxId(input)))
}
const isValidPlatform = (input) => Player.getPlatformIdFromString(input) !== -1
const isValidSteamId = (input) => validator.isNumeric(input) && input.length === 17
const isValidPSNId = (input) =>
validator.isAlpha(input[0])
&& input.length >= 3 && input.length <= 16
&& validator.isAlphanumeric(validator.blacklist(input, '_-'))
const isValidXboxId = (input) =>
validator.isAlphanumeric(input.trim()) && input.length >= 3 && input.length <= 15
const isValidName = (input) =>
validator.isLength(input, { min: 1, max: 30 })
export default { isValidIdForPlatform, isValidPlatform, isValidSteamId, isValidXboxId, isValidPSNId, isValidName }
|
Remove unnecessary use of spread
|
export function createSelectorCreator(valueEquals) {
return (selectors, resultFunc) => {
if (!Array.isArray(selectors)) {
selectors = [selectors];
}
const memoizedResultFunc = memoize(resultFunc, valueEquals);
return state => {
const params = selectors.map(selector => selector(state));
return memoizedResultFunc(params);
}
};
}
export function createSelector(...args) {
return createSelectorCreator(defaultValueEquals)(...args);
}
export function defaultValueEquals(a, b) {
return a === b;
}
// the memoize function only caches one set of arguments. This
// actually good enough, rather surprisingly. This is because during
// calculation of a selector result the arguments won't
// change if called multiple times. If a new state comes in, we *want*
// recalculation if and only if the arguments are different.
function memoize(func, valueEquals) {
let lastArgs = null;
let lastResult = null;
return (args) => {
if (lastArgs !== null && argsEquals(args, lastArgs, valueEquals)) {
return lastResult;
}
lastArgs = args;
lastResult = func(...args);
return lastResult;
}
}
function argsEquals(a, b, valueEquals) {
return a.every((value, index) => valueEquals(value, b[index]));
}
|
export function createSelectorCreator(valueEquals) {
return (selectors, resultFunc) => {
if (!Array.isArray(selectors)) {
selectors = [selectors];
}
const memoizedResultFunc = memoize(resultFunc, valueEquals);
return state => {
const params = selectors.map(selector => selector(state));
return memoizedResultFunc(...params);
}
};
}
export function createSelector(...args) {
return createSelectorCreator(defaultValueEquals)(...args);
}
export function defaultValueEquals(a, b) {
return a === b;
}
// the memoize function only caches one set of arguments. This
// actually good enough, rather surprisingly. This is because during
// calculation of a selector result the arguments won't
// change if called multiple times. If a new state comes in, we *want*
// recalculation if and only if the arguments are different.
function memoize(func, valueEquals) {
let lastArgs = null;
let lastResult = null;
return (...args) => {
if (lastArgs !== null && argsEquals(args, lastArgs, valueEquals)) {
return lastResult;
}
lastArgs = args;
lastResult = func(...args);
return lastResult;
}
}
function argsEquals(a, b, valueEquals) {
return a.every((value, index) => valueEquals(value, b[index]));
}
|
Fix Spawn minionDown metric to correctly ignore failed hosts.
|
/*
* 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.addthis.hydra.job.spawn;
import com.addthis.hydra.job.mq.HostState;
import com.yammer.metrics.core.Gauge;
class DownMinionGauge extends Gauge<Integer> {
private Spawn spawn;
public DownMinionGauge(Spawn spawn) {
this.spawn = spawn;
}
@Override public Integer value() {
int down = 0;
for (HostState host : spawn.listHostStatus(null)) {
if (host != null && !host.isDead() && !host.isUp()) {
down++;
}
}
return down;
}
}
|
/*
* 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.addthis.hydra.job.spawn;
import com.yammer.metrics.core.Gauge;
class DownMinionGauge extends Gauge<Integer> {
private Spawn spawn;
public DownMinionGauge(Spawn spawn) {
this.spawn = spawn;
}
@Override public Integer value() {
int total = 0;
if (spawn.monitored != null) {
synchronized (spawn.monitored) {
total = spawn.monitored.size();
}
}
int up;
if (spawn.minionMembers == null) {
up = 0;
} else {
up = spawn.minionMembers.getMemberSetSize();
}
return total - up;
}
}
|
Use PHP 8 constructor property promotion
|
<?php
declare(strict_types = 1);
/**
* /src/Utils/HealthzService.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Utils;
use App\Entity\Healthz;
use App\Repository\HealthzRepository;
use Throwable;
/**
* Class HealthzService
*
* @package App\Utils
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
final class HealthzService
{
public function __construct(
private HealthzRepository $repository,
) {
}
/**
* Method to check that "all" is ok within our application. This will try
* to do following:
* 1) Remove data from database
* 2) Create data to database
* 3) Read data from database
*
* These steps should make sure that at least application database is
* working as expected.
*
* @throws Throwable
*/
public function check(): ?Healthz
{
$this->repository->cleanup();
$this->repository->create();
return $this->repository->read();
}
}
|
<?php
declare(strict_types = 1);
/**
* /src/Utils/HealthzService.php
*
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
namespace App\Utils;
use App\Entity\Healthz;
use App\Repository\HealthzRepository;
use Throwable;
/**
* Class HealthzService
*
* @package App\Utils
* @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
*/
final class HealthzService
{
private HealthzRepository $repository;
public function __construct(HealthzRepository $repository)
{
$this->repository = $repository;
}
/**
* Method to check that "all" is ok within our application. This will try
* to do following:
* 1) Remove data from database
* 2) Create data to database
* 3) Read data from database
*
* These steps should make sure that at least application database is
* working as expected.
*
* @throws Throwable
*/
public function check(): ?Healthz
{
$this->repository->cleanup();
$this->repository->create();
return $this->repository->read();
}
}
|
Add commandline input of ciphertext in 1/3
Altered code to allow for ciphertext to be entered on the
commandline for set 1 challange 3
|
<?php
require '../../functions/letterScore.php';
if ($argc > 1) {
$input = hex2bin($argv[1]);
} else {
$input = hex2bin("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
}
$inputLength = strlen($input);
$scores = [];
for ($kv=0; $kv < 256; $kv++) {
$charScore = 0;
$plainText = $input ^ str_repeat(chr($kv), $inputLength);
$charScore = englishLetterWeight($plainText, 5);
$scores[$kv] = $charScore;
}
arsort($scores);
$keyCount = 0;
foreach ($scores as $key => $value) {
if ($keyCount < 5) {
$decrypt = $input ^ str_repeat(chr($key), $inputLength);
echo chr($key) . " ($key) : " . $decrypt . "\n";
} else {
break;
}
$keyCount++;
}
?>
|
<?php
require '../../functions/letterScore.php';
$input = hex2bin("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
$inputLength = strlen($input);
$scores = [];
for ($kv=0; $kv < 256; $kv++) {
$charScore = 0;
$plainText = $input ^ str_repeat(chr($kv), $inputLength);
$charScore = englishLetterWeight($plainText, 5);
$scores[$kv] = $charScore;
}
arsort($scores);
$keyCount = 0;
foreach ($scores as $key => $value) {
if ($keyCount < 5) {
$decrypt = $input ^ str_repeat(chr($key), $inputLength);
echo chr($key) . " ($key) : " . $decrypt . "\n";
} else {
break;
}
$keyCount++;
}
?>
|
Set the soon-to-be URL on stevegrunwell.com for the plugin
|
<?php
/**
* Plugin Name: Revision Strike
* Plugin URI: https://stevegrunwell.com/blog/revision-strike
* Description: Periodically purge old post revisions via WP Cron.
* Version: 0.1
* Author: Steve Grunwell
* Author URI: https://stevegrunwell.com
*
* @package Revision Strike
* @author Steve Grunwell
*/
require_once dirname( __FILE__ ) . '/includes/class-revision-strike.php';
require_once dirname( __FILE__ ) . '/includes/class-revision-strike-cli.php';
require_once dirname( __FILE__ ) . '/includes/class-settings.php';
/**
* Bootstrap the plugin.
*/
function revisionstrike_init() {
new RevisionStrike;
}
add_action( 'init', 'revisionstrike_init' );
/**
* Register the cron job on plugin activation.
*/
function revisionstrike_register_cron() {
if ( false === wp_next_scheduled( RevisionStrike::STRIKE_ACTION ) ) {
wp_schedule_event( time(), 'daily', RevisionStrike::STRIKE_ACTION );
}
}
register_activation_hook( __FILE__, 'revisionstrike_register_cron' );
/**
* Cancel the cron job when the plugin is disabled.
*/
function revisionstrike_deregister_cron() {
wp_clear_scheduled_hook( RevisionStrike::STRIKE_ACTION );
}
register_deactivation_hook( __FILE__, 'revisionstrike_deregister_cron' );
|
<?php
/**
* Plugin Name: Revision Strike
* Plugin URI: https://stevegrunwell.com/revision-strike
* Description: Periodically purge old post revisions via WP Cron.
* Version: 0.1
* Author: Steve Grunwell
* Author URI: https://stevegrunwell.com
*
* @package Revision Strike
* @author Steve Grunwell
*/
require_once dirname( __FILE__ ) . '/includes/class-revision-strike.php';
require_once dirname( __FILE__ ) . '/includes/class-revision-strike-cli.php';
require_once dirname( __FILE__ ) . '/includes/class-settings.php';
/**
* Bootstrap the plugin.
*/
function revisionstrike_init() {
new RevisionStrike;
}
add_action( 'init', 'revisionstrike_init' );
/**
* Register the cron job on plugin activation.
*/
function revisionstrike_register_cron() {
if ( false === wp_next_scheduled( RevisionStrike::STRIKE_ACTION ) ) {
wp_schedule_event( time(), 'daily', RevisionStrike::STRIKE_ACTION );
}
}
register_activation_hook( __FILE__, 'revisionstrike_register_cron' );
/**
* Cancel the cron job when the plugin is disabled.
*/
function revisionstrike_deregister_cron() {
wp_clear_scheduled_hook( RevisionStrike::STRIKE_ACTION );
}
register_deactivation_hook( __FILE__, 'revisionstrike_deregister_cron' );
|
Fix username validation to allow periods and hyphens
|
package net.qldarch.service.rdf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
public class Validators {
public static Logger logger = LoggerFactory.getLogger(Validators.class);
public static final Pattern USERNAME_REGEX = Pattern.compile("[a-zA-Z0-9_.-]{3,}");
public static String username(String username) {
if (username == null) {
return "";
} else if (USERNAME_REGEX.matcher(username).matches()) {
return username;
} else {
logger.warn("Invalid username provided: {}", username);
throw new IllegalArgumentException("Invalid username");
}
}
}
|
package net.qldarch.service.rdf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
public class Validators {
public static Logger logger = LoggerFactory.getLogger(Validators.class);
public static final Pattern USERNAME_REGEX = Pattern.compile("[a-zA-Z0-9_]{3,}");
public static String username(String username) {
if (username == null) {
return "";
} else if (USERNAME_REGEX.matcher(username).matches()) {
return username;
} else {
logger.warn("Invalid username provided: {}", username);
throw new IllegalArgumentException("Invalid username");
}
}
}
|
Put module in method to enable calls from libraries.
Former-commit-id: e614cec07ee71723be5b114163fe835961f6811c
|
#!/usr/bin/env python3
from distutils.core import setup, Extension
MODULES_TO_BUILD = ["fasthash", "suc", "lemmatize"]
def main():
for module in MODULES_TO_BUILD:
setup(
name=module,
ext_modules=[
Extension(
name=module,
sources=['%s.c' % module],
libraries=[],
extra_compile_args=['-Wall', '-Wno-unused-function'],
extra_link_args=[]
)
],
script_args=['build_ext', '--inplace']
)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
from distutils.core import setup, Extension
MODULES_TO_BUILD = ["fasthash", "suc", "lemmatize"]
for module in MODULES_TO_BUILD:
setup(
name=module,
ext_modules=[
Extension(
name=module,
sources=['%s.c' % module],
libraries=[],
extra_compile_args=['-Wall', '-Wno-unused-function'],
extra_link_args=[]
)
],
script_args=['build_ext', '--inplace']
)
|
Fix "unused import". It was used, but only by Javadoc.
|
package com.github.therapi.core.interceptor;
import java.lang.annotation.Annotation;
import java.util.function.Predicate;
import com.github.therapi.core.MethodDefinition;
/**
* Factory methods for common method predicates, useful for registering method interceptors.
*
* @see com.github.therapi.core.MethodRegistry#intercept(Predicate, org.aopalliance.intercept.MethodInterceptor)
*/
public class MethodPredicates {
private MethodPredicates() {
}
public static Predicate<MethodDefinition> any() {
return methodDef -> true;
}
public static Predicate<MethodDefinition> methodAnnotatedWith(Class<? extends Annotation> annotationClass) {
return methodDef -> methodDef.getMethod().getAnnotation(annotationClass) != null;
}
public static Predicate<MethodDefinition> qualifiedName(String name) {
return methodDef -> methodDef.getQualifiedName(".").equals(name);
}
public static Predicate<MethodDefinition> namespace(String namespace) {
return methodDef -> methodDef.getNamespace().orElse("").equals(namespace);
}
}
|
package com.github.therapi.core.interceptor;
import java.lang.annotation.Annotation;
import java.util.function.Predicate;
import com.github.therapi.core.MethodDefinition;
import org.aopalliance.intercept.MethodInterceptor;
/**
* Factory methods for common method predicates, useful for registering method interceptors.
*
* @see com.github.therapi.core.MethodRegistry#intercept(Predicate, MethodInterceptor)
*/
public class MethodPredicates {
private MethodPredicates() {
}
public static Predicate<MethodDefinition> any() {
return methodDef -> true;
}
public static Predicate<MethodDefinition> methodAnnotatedWith(Class<? extends Annotation> annotationClass) {
return methodDef -> methodDef.getMethod().getAnnotation(annotationClass) != null;
}
public static Predicate<MethodDefinition> qualifiedName(String name) {
return methodDef -> methodDef.getQualifiedName(".").equals(name);
}
public static Predicate<MethodDefinition> namespace(String namespace) {
return methodDef -> methodDef.getNamespace().orElse("").equals(namespace);
}
}
|
Use yargs to parse the command line args
|
// Dependencies
var Fs = require("fs")
, ArcAssembler = require("../lib")
, Argv = require("yargs")
.alias("s", "source")
.alias("o", "output")
.argv
, Path = require("path")
;
// Constants
const INPUT_FILE = Path.resolve(process.cwd() + Argv.source)
, OUTPUT_FILE = Path.resolve(process.cwd() + Argv.output)
;
// Create the write stream
var outputStream = Fs.createWriteStream(OUTPUT_FILE);
// Read the input file content
Fs.readFile(INPUT_FILE, "utf-8", function (err, content) {
if (err) throw err;
// Compile the input
var result = ArcAssembler.compile(content);
// Show some output
result.raw.forEach(function (c) {
console.log(c.code.match(/.{1,4}/g).join(" ") + " << Line " + c.line);
});
// Write things in the output stream
outputStream.write("#!/usr/bin/env arc-int");
outputStream.write(new Buffer(result.mCode));
outputStream.end();
// Make the file executable
Fs.chmodSync(OUTPUT_FILE, 0755);
});
|
var Fs = require("fs")
, ArcAssembler = require("./lib")
;
const OUTPUT_FILE = __dirname + "/out"
, INPUT_FILE = __dirname + "/Test.asm"
;
var outputStream = Fs.createWriteStream(OUTPUT_FILE);
Fs.readFile(INPUT_FILE, "utf-8", function (err, lines) {
var result = ArcAssembler.compile(lines);
result.raw.forEach(function (c) {
console.log(c.code.match(/.{1,4}/g).join(" ") + " << Line " + c.line);
});
console.log("---- Full machine code ----");
for (var i = 0; i < result.mCode.length; i += 32) {
console.log(result.mCode.slice(i, i + 32).join("").match(/.{1,4}/g).join(" "));
}
outputStream.write("#!/usr/bin/env arc-int");
outputStream.write(new Buffer(result.mCode));
outputStream.end();
Fs.chmodSync(OUTPUT_FILE, 0755);
});
|
Fix running detection for master
|
import os
import subprocess
name = "gobuildmaster"
current_hash = ""
if os.path.isfile('hash'):
current_hash = open('hash').readlines()[0]
new_hash = os.popen('git rev-parse HEAD').readlines()[0]
open('hash','w').write(new_hash)
# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
print line.strip()
# Rebuild
for line in os.popen('go build').readlines():
print line.strip()
size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)
lines = os.popen('ps -ef | grep ' + name).readlines()
running = False
for line in lines:
if "./" + name in line:
running = True
if size_1 != size_2 or new_hash != current_hash or not running:
if not running:
for line in os.popen('cat out.txt | mail -s "Crash Report ' + name + '" brotherlogic@gmail.com').readlines():
pass
for line in os.popen('echo "" > out.txt').readlines():
pass
for line in os.popen('killall ' + name).readlines():
pass
subprocess.Popen(['./' + name, "--quiet=false"])
|
import os
import subprocess
name = "gobuildmaster"
current_hash = ""
if os.path.isfile('hash'):
current_hash = open('hash').readlines()[0]
new_hash = os.popen('git rev-parse HEAD').readlines()[0]
open('hash','w').write(new_hash)
# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
print line.strip()
# Rebuild
for line in os.popen('go build').readlines():
print line.strip()
size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)
running = len(os.popen('ps -ef | grep ' + name).readlines()) > 3
if size_1 != size_2 or new_hash != current_hash or not running:
if not running:
for line in os.popen('cat out.txt | mail -s "Crash Report ' + name + '" brotherlogic@gmail.com').readlines():
pass
for line in os.popen('echo "" > out.txt').readlines():
pass
for line in os.popen('killall ' + name).readlines():
pass
subprocess.Popen(['./' + name, "--quiet=false"])
|
Add 1500 to build number until next minor bump
|
const fs = require('fs-extra');
const path = require('path');
const yargs = require('yargs').argv;
const validEnvironments = ['beta', 'development'];
if (!validEnvironments.includes(yargs.env)) {
console.log(`Invalid ENVIRONMENT provided. Must be one of: [${validEnvironments.join('|')}]`);
process.exit(1);
}
const env = yargs.env;
const workspaceRoot = path.join(__dirname, '..');
const buildDirectory = path.join(workspaceRoot, 'dist', 'extension');
const manifestPath = path.join(buildDirectory, 'manifest.json');
const manifest = require(manifestPath);
const changes = require(path.join(workspaceRoot, 'src', `manifest.${env}.json`));
// Clobber any keys in the beta manifest across.
Object.assign(manifest, changes);
// If we're on Travis, we should append the build number to the version number.
if (process.env.TRAVIS_BUILD_NUMBER) {
// I goofed up and didn't realize Google complained about version numbers not
// going up so we're going to add 1500 to the build number until we're on the
// next minor version :P
manifest.version += `.${parseInt(process.env.TRAVIS_BUILD_NUMBER) + 1500}`;
}
// Delete the old one.
fs.unlinkSync(manifestPath);
// And write our new one.
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
console.log(`${env} manifest applied.`);
|
const fs = require('fs-extra');
const path = require('path');
const yargs = require('yargs').argv;
const validEnvironments = ['beta', 'development'];
if (!validEnvironments.includes(yargs.env)) {
console.log(`Invalid ENVIRONMENT provided. Must be one of: [${validEnvironments.join('|')}]`);
process.exit(1);
}
const env = yargs.env;
const workspaceRoot = path.join(__dirname, '..');
const buildDirectory = path.join(workspaceRoot, 'dist', 'extension');
const manifestPath = path.join(buildDirectory, 'manifest.json');
const manifest = require(manifestPath);
const changes = require(path.join(workspaceRoot, 'src', `manifest.${env}.json`));
// Clobber any keys in the beta manifest across.
Object.assign(manifest, changes);
// If we're on Travis, we should append the build number to the version number.
if (process.env.TRAVIS_BUILD_NUMBER) {
manifest.version += `.${process.env.TRAVIS_BUILD_NUMBER}`;
}
// Delete the old one.
fs.unlinkSync(manifestPath);
// And write our new one.
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
console.log(`${env} manifest applied.`);
|
Fix selector after Google change
|
(function() {
var element = null;
var nav_elements = document.querySelectorAll('.nav-item-container');
for (var i = 0; i < nav_elements.length; i++) {
var current = nav_elements[i];
if (current.innerHTML == 'My Library') {
element = current;
break;
}
}
if (element != null) {
chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) {
element.setAttribute('data-type', item.gpmDefaultLibraryView);
});
} else {
console.log('No element found; did Google change the page?');
}
})();
|
(function() {
var element = null;
var nav_elements = document.querySelectorAll('li.nav-item-container');
for (var i = 0; i < nav_elements.length; i++) {
var current = nav_elements[i];
if (current.innerHTML == 'My Library') {
element = current;
break;
}
}
if (element != null) {
chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) {
element.setAttribute('data-type', item.gpmDefaultLibraryView);
});
} else {
console.log('No element found; did Google change the page?');
}
})();
|
fix(): Remove conflict from plugin header comment
|
<?php
/*
Plugin Name: tonik/gin
Plugin URI: http://tonik.pl
Description: Foundation of the Tonik WordPress Starter Theme. Provides all custom functionalities which it offers.
Version: 3.1.0
Author: Tonik
Author URI: http://tonik.pl
License: GPL-2.0+
License URI: http://www.gnu.org/licenses/gpl-2.0.txt
Domain Path: /resources/lang
Text Domain: tonik.gin
*/
spl_autoload_register(function ($class) {
// Namespace prefix
$prefix = 'Tonik\\';
// Base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// Does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// No, move to the next registered autoloader
return;
}
// Get the relative class name
$relative_class = substr($class, $len);
// Replace the namespace prefix with the base
// directory, replace namespace separators with directory
// separators in the relative class name, append with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// If the file exists, require it
if (file_exists($file)) {
require $file;
}
});
|
<?php
/*
Plugin Name: tonik/gin
Plugin URI: http://tonik.pl
Description: Foundation of the Tonik WordPress Starter Theme. Provides all custom functionalities which it offers.
<<<<<<< HEAD
Version: 3.0.0
=======
Version: 3.1.0
>>>>>>> release-3.1.0
Author: Tonik
Author URI: http://tonik.pl
License: GPL-2.0+
License URI: http://www.gnu.org/licenses/gpl-2.0.txt
Domain Path: /resources/lang
Text Domain: tonik.gin
*/
spl_autoload_register(function ($class) {
// Namespace prefix
$prefix = 'Tonik\\';
// Base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// Does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// No, move to the next registered autoloader
return;
}
// Get the relative class name
$relative_class = substr($class, $len);
// Replace the namespace prefix with the base
// directory, replace namespace separators with directory
// separators in the relative class name, append with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// If the file exists, require it
if (file_exists($file)) {
require $file;
}
});
|
Use express for protractor tests.
|
const path = require('path')
const express = require('express')
const childprocess = require('child_process')
const wwwroot = path.join(__dirname, 'wwwroot')
const port = 3000
const app = express()
app.use('/', express.static(wwwroot))
app.listen(port, () => {
runProtractor()
})
let runProtractor = () => {
let winExt = /^win/.test(process.platform) ? '.cmd' : ''
let nodeBinDir = path.join('node_modules', '.bin')
let protractorBin = path.join(nodeBinDir, 'protractor' + winExt)
childprocess.spawn(protractorBin, [ 'protractor.conf.js' ], {stdio: 'inherit'})
.on('close', (code) => {
if (code !== 0) {
process.exit(code)
} else {
process.exit(0)
}
})
}
|
const path = require('path')
const httpServer = require('http-server')
const childprocess = require('child_process')
const server = httpServer.createServer({ root: path.join(__dirname, 'wwwroot') })
const port = 3000
server.listen(port, () => {
runProtractor()
})
let runProtractor = () => {
let winExt = /^win/.test(process.platform) ? '.cmd' : ''
let nodeBinDir = path.join('node_modules', '.bin')
let protractorBin = path.join(nodeBinDir, 'protractor' + winExt)
childprocess.spawn(protractorBin, [ 'protractor.conf.js' ], {stdio: 'inherit'})
.on('close', (code) => {
if (code !== 0) {
process.exit(code)
} else {
process.exit(0)
}
})
}
|
Migrate to Dropbox API v2
|
<?php
namespace Stevenmaguire\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
class DropboxResourceOwner implements ResourceOwnerInterface
{
/**
* Raw response
*
* @var array
*/
protected $response;
/**
* Creates new resource owner.
*
* @param array $response
*/
public function __construct(array $response = array())
{
$this->response = $response;
}
/**
* Get resource owner id
*
* @return string
*/
public function getId()
{
return $this->response['account_id'] ?: null;
}
/**
* Get resource owner name
*
* @return string
*/
public function getName()
{
return $this->response['name']['display_name'] ?: null;
}
/**
* Return all of the owner details available as an array.
*
* @return array
*/
public function toArray()
{
return $this->response;
}
}
|
<?php
namespace Stevenmaguire\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
class DropboxResourceOwner implements ResourceOwnerInterface
{
/**
* Raw response
*
* @var array
*/
protected $response;
/**
* Creates new resource owner.
*
* @param array $response
*/
public function __construct(array $response = array())
{
$this->response = $response;
}
/**
* Get resource owner id
*
* @return string
*/
public function getId()
{
return $this->response['uid'] ?: null;
}
/**
* Get resource owner name
*
* @return string
*/
public function getName()
{
return $this->response['display_name'] ?: null;
}
/**
* Return all of the owner details available as an array.
*
* @return array
*/
public function toArray()
{
return $this->response;
}
}
|
Update name registration success message, removed keep Blockstack online for 1 hour.
|
import PropTypes from 'prop-types'
import React from 'react'
import { Link } from 'react-router'
const RegistrationSubmittedView = (props) => {
const {
routeParams: {
name
}
} = props
const isSubdomain = name && name.split('.').length > 2
const bodyContent = <p>Your username will be ready in about an hour.</p>
return (
<div>
<h3 className="modal-heading">{name} registration submitted!</h3>
<div className="modal-body">
{bodyContent}
<img
role="presentation"
src="/images/blockstack-logo-vertical.svg"
className="m-b-20"
style={{ width: '210px', display: 'block', marginRight: 'auto', marginLeft: 'auto' }}
/>
<Link to="/profiles" className="btn btn-primary btn-block">I understand</Link>
</div>
</div>
)
}
RegistrationSubmittedView.propTypes = {
routeParams: PropTypes.object.isRequired
}
export default RegistrationSubmittedView
|
import PropTypes from 'prop-types'
import React from 'react'
import { Link } from 'react-router'
const RegistrationSubmittedView = (props) => {
const {
routeParams: {
name
}
} = props
const isSubdomain = name && name.split('.').length > 2
const bodyContent = isSubdomain ? (
<p>Your username will be ready in about an hour.</p>
) : (
<p>
Please <strong>keep</strong> Blockstack online for the next hour.
Your username will be available shortly after.
</p>
)
return (
<div>
<h3 className="modal-heading">{name} registration submitted!</h3>
<div className="modal-body">
{bodyContent}
<img
role="presentation"
src="/images/blockstack-logo-vertical.svg"
className="m-b-20"
style={{ width: '210px', display: 'block', marginRight: 'auto', marginLeft: 'auto' }}
/>
<Link to="/profiles" className="btn btn-primary btn-block">I understand</Link>
</div>
</div>
)
}
RegistrationSubmittedView.propTypes = {
routeParams: PropTypes.object.isRequired
}
export default RegistrationSubmittedView
|
Use == instead of .equals
|
package seedu.todo.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.todo.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : GetShitDone\n" +
"Current log level : INFO\n" +
"Local data file location : database.json";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig == null);
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
package seedu.todo.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.todo.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : GetShitDone\n" +
"Current log level : INFO\n" +
"Local data file location : database.json";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
Fix syntax in spatial layer
|
import lasagne
import numpy as np
from theano import tensor as T
WIDTH_INDEX = 3
HEIGHT_INDEX = 2
LAYER_INDEX = 1
class SpatialPoolingLayer(lasagne.layers.Layer):
# I assume that all bins has square shape for simplicity
# Maybe later I change this behaviour
def __init__(self, incoming, bin_sizes, **kwargs):
super(SpatialPoolingLayer, self).__init__(incoming, **kwargs)
self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes")
def get_output_shape_for(self, input_shape):
return T.sum(T.power(self.bin_sizes, 2))
def get_output_for(self, input, **kwargs):
layers = []
for bin_size in self.bin_sizes:
win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size))
stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size))
layers.append(lasagne.layers.flatten(
lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride)
))
return lasagne.layers.concat(layers)
|
import lasagne
import numpy as np
WIDTH_INDEX = 3
HEIGHT_INDEX = 2
LAYER_INDEX = 1
class SpatialPoolingLayer(lasagne.layers.Layer):
# I assume that all bins has square shape for simplicity
# Maybe later I change this behaviour
def __init__(self, incoming, bin_sizes, **kwargs):
super(SpatialPoolingLayer, self).__init__(incoming, **kwargs)
self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes")
def get_output_shape_for(self, input_shape):
return np.sum(np.power(self.bin_sizes, 2))
def get_output_for(self, input, **kwargs):
layers = []
for bin_size in self.bin_sizes:
win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size))
stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size))
layers.append(lasagne.layers.flatten(
lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride)
))
return lasagne.layers.concat(layers)
|
Allow case-insensitive email addresses when doing authentication
(imported from commit b52e39c7f706a2107b5d86e8e18293a46ed9e6ff)
|
from django.contrib.auth.models import User
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
if username is None or password is None:
# Return immediately. Otherwise we will look for a SQL row with
# NULL username. While that's probably harmless, it's needless
# exposure.
return None
try:
user = User.objects.get(email__iexact=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
""" Get a User object from the user_id. """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
|
from django.contrib.auth.models import User
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
if username is None or password is None:
# Return immediately. Otherwise we will look for a SQL row with
# NULL username. While that's probably harmless, it's needless
# exposure.
return None
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
""" Get a User object from the user_id. """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
|
helper/resource: Fix data race in resource.Retry
The implementation was attempting to capture the error using a scoped
variable reference, but the error value is already exposed via the
return value of `WaitForState()`. Using that instead fixes the data
race.
Fixes the following data race:
```
==================
WARNING: DATA RACE
Read by goroutine 74:
github.com/hashicorp/terraform/helper/resource.Retry()
/Users/phinze/go/src/github.com/hashicorp/terraform/helper/resource/wait.go:35 +0x284
github.com/hashicorp/terraform/helper/resource.TestRetry_timeout()
/Users/phinze/go/src/github.com/hashicorp/terraform/helper/resource/wait_test.go:35 +0x60
testing.tRunner()
/private/var/folders/vd/7l9ys5k57l91x63sh28wl_kc0000gn/T/workdir/go/src/testing/testing.go:456 +0xdc
Previous write by goroutine 90:
github.com/hashicorp/terraform/helper/resource.Retry.func1()
/Users/phinze/go/src/github.com/hashicorp/terraform/helper/resource/wait.go:20 +0x87
github.com/hashicorp/terraform/helper/resource.(*StateChangeConf).WaitForState.func1()
/Users/phinze/go/src/github.com/hashicorp/terraform/helper/resource/state.go:83 +0x284
Goroutine 74 (running) created at:
testing.RunTests()
/private/var/folders/vd/7l9ys5k57l91x63sh28wl_kc0000gn/T/workdir/go/src/testing/testing.go:561 +0xaa3
testing.(*M).Run()
/private/var/folders/vd/7l9ys5k57l91x63sh28wl_kc0000gn/T/workdir/go/src/testing/testing.go:494 +0xe4
main.main()
github.com/hashicorp/terraform/helper/resource/_test/_testmain.go:84 +0x20f
Goroutine 90 (running) created at:
github.com/hashicorp/terraform/helper/resource.(*StateChangeConf).WaitForState()
/Users/phinze/go/src/github.com/hashicorp/terraform/helper/resource/state.go:127 +0x283
github.com/hashicorp/terraform/helper/resource.Retry()
/Users/phinze/go/src/github.com/hashicorp/terraform/helper/resource/wait.go:34 +0x276
github.com/hashicorp/terraform/helper/resource.TestRetry_timeout()
/Users/phinze/go/src/github.com/hashicorp/terraform/helper/resource/wait_test.go:35 +0x60
testing.tRunner()
/private/var/folders/vd/7l9ys5k57l91x63sh28wl_kc0000gn/T/workdir/go/src/testing/testing.go:456 +0xdc
==================
```
|
package resource
import (
"time"
)
// RetryFunc is the function retried until it succeeds.
type RetryFunc func() error
// Retry is a basic wrapper around StateChangeConf that will just retry
// a function until it no longer returns an error.
func Retry(timeout time.Duration, f RetryFunc) error {
c := &StateChangeConf{
Pending: []string{"error"},
Target: "success",
Timeout: timeout,
MinTimeout: 500 * time.Millisecond,
Refresh: func() (interface{}, string, error) {
err := f()
if err == nil {
return 42, "success", nil
}
if rerr, ok := err.(RetryError); ok {
err = rerr.Err
return nil, "quit", err
}
return 42, "error", nil
},
}
_, err := c.WaitForState()
return err
}
// RetryError, if returned, will quit the retry immediately with the
// Err.
type RetryError struct {
Err error
}
func (e RetryError) Error() string {
return e.Err.Error()
}
|
package resource
import (
"time"
)
// RetryFunc is the function retried until it succeeds.
type RetryFunc func() error
// Retry is a basic wrapper around StateChangeConf that will just retry
// a function until it no longer returns an error.
func Retry(timeout time.Duration, f RetryFunc) error {
var err error
c := &StateChangeConf{
Pending: []string{"error"},
Target: "success",
Timeout: timeout,
MinTimeout: 500 * time.Millisecond,
Refresh: func() (interface{}, string, error) {
err = f()
if err == nil {
return 42, "success", nil
}
if rerr, ok := err.(RetryError); ok {
err = rerr.Err
return nil, "quit", err
}
return 42, "error", nil
},
}
c.WaitForState()
return err
}
// RetryError, if returned, will quit the retry immediately with the
// Err.
type RetryError struct {
Err error
}
func (e RetryError) Error() string {
return e.Err.Error()
}
|
Update version number to 1.0.
|
#!/usr/bin/env python
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='1.0',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "developers@topographica.org",
maintainer= "IOAM",
maintainer_email= "developers@topographica.org",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
|
#!/usr/bin/env python
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='0.05',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "developers@topographica.org",
maintainer= "IOAM",
maintainer_email= "developers@topographica.org",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
# (until packaging tested)
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
|
Add at least some criteria
--HG--
branch : jax-rs
|
package com.oreilly.com.rdf.tenuki.jaxrs.io;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import com.oreilly.rdf.tenuki.Changeset;
import com.oreilly.rdf.tenuki.InputStreamChangeset;
@Provider
@Consumes("application/vnd.talis.changeset+xml")
public class ChangesetReader implements MessageBodyReader<Changeset> {
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return Changeset.class.isAssignableFrom(type);
}
@Override
public Changeset readFrom(Class<Changeset> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
return new InputStreamChangeset(entityStream);
}
}
|
package com.oreilly.com.rdf.tenuki.jaxrs.io;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import com.oreilly.rdf.tenuki.Changeset;
import com.oreilly.rdf.tenuki.InputStreamChangeset;
@Provider
@Consumes("application/vnd.talis.changeset+xml")
public class ChangesetReader implements MessageBodyReader<Changeset> {
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
// TODO: Do something useful here?
return true;
}
@Override
public Changeset readFrom(Class<Changeset> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
return new InputStreamChangeset(entityStream);
}
}
|
Support COVERALLS_ENDPOINT for Enterprise usage
|
from __future__ import absolute_import
from __future__ import print_function
import requests
import json
import os
URL = os.getenv('COVERALLS_ENDPOINT', 'https://coveralls.io') + "/api/v1/jobs"
def post_report(coverage):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_file': json.dumps(coverage)})
try:
result = response.json()
except ValueError:
result = {'error': 'Failure to submit data. '
'Response [%(status)s]: %(text)s' % {
'status': response.status_code,
'text': response.text}}
print(result)
if 'error' in result:
return result['error']
return 0
|
from __future__ import absolute_import
from __future__ import print_function
import requests
import json
URL = 'https://coveralls.io/api/v1/jobs'
def post_report(coverage):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_file': json.dumps(coverage)})
try:
result = response.json()
except ValueError:
result = {'error': 'Failure to submit data. '
'Response [%(status)s]: %(text)s' % {
'status': response.status_code,
'text': response.text}}
print(result)
if 'error' in result:
return result['error']
return 0
|
Add delim support and trim
|
var assign = require('object-assign');
module.exports = function(converter, delim) {
delim = delim || '---';
return function (pages, done) {
try {
pages.forEach(function(page){
var content = page.content;
var frontmatter;
content = content.split(delim).map(function(v){
return v.trim();
});
if(content.length > 1) {
frontmatter = converter(content[1]);
page = assign(page, frontmatter);
content = content.slice(2);
}
page.content = content.join(delim);
});
done(null, pages);
}
catch(e) {
done(e);
}
};
};
|
var delim = "---\n";
var assign = require('object-assign');
module.exports = function(converter) {
return function (pages, done) {
try {
pages.forEach(function(page){
var content = page.content;
var frontmatter;
content = content.split(delim);
if(content.length > 1) {
frontmatter = converter(content[1]);
page = assign(page, frontmatter);
content = content.slice(2);
}
page.content = content.join(delim);
});
done(null, pages);
}
catch(e) {
done(e);
}
};
};
|
Correct implementation of the IResourceAware methods
|
package com.redhat.ceylon.eclipse.core.model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;
public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return getPhasedUnit().getSourceFileResource();
}
@Override
public IFolder getRootFolderResource() {
return getPhasedUnit().getSourceFolderResource();
}
}
|
package com.redhat.ceylon.eclipse.core.model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;
public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return (IFile)((ResourceVirtualFile) (getPhasedUnit().getUnitFile())).getResource();
}
@Override
public IFolder getRootFolderResource() {
return null;
}
}
|
Remove parallel as that makes goroutines deadlock
|
package suite
import (
"math/rand"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type CallOrderSuite struct {
Suite
callOrder []string
}
func (s *CallOrderSuite) call(method string) {
time.Sleep(time.Duration(rand.Intn(300)) * time.Millisecond)
s.callOrder = append(s.callOrder, method)
}
func TestSuiteCallOrder(t *testing.T) {
Run(t, new(CallOrderSuite))
}
func (s *CallOrderSuite) SetupSuite() {
s.call("SetupSuite")
}
func (s *CallOrderSuite) TearDownSuite() {
s.call("TearDownSuite")
assert.Equal(s.T(), "SetupSuite;SetupTest;Test A;TearDownTest;SetupTest;Test B;TearDownTest;TearDownSuite", strings.Join(s.callOrder, ";"))
}
func (s *CallOrderSuite) SetupTest() {
s.call("SetupTest")
}
func (s *CallOrderSuite) TearDownTest() {
s.call("TearDownTest")
}
func (s *CallOrderSuite) Test_A() {
s.call("Test A")
}
func (s *CallOrderSuite) Test_B() {
s.call("Test B")
}
|
package suite
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
type CallOrderSuite struct {
Suite
callOrder []string
}
func (s *CallOrderSuite) call(method string) {
// s.Mutex.Lock()
// defer s.Mutex.Unlock()
s.callOrder = append(s.callOrder, method)
}
func TestSuiteCallOrder(t *testing.T) {
Run(t, new(CallOrderSuite))
}
func (s *CallOrderSuite) SetupSuite() {
s.call("SetupSuite")
}
func (s *CallOrderSuite) TearDownSuite() {
s.call("TearDownSuite")
assert.Equal(s.T(), "SetupSuite;SetupTest;Test A;TearDownTest;TearDownSuite", strings.Join(s.callOrder, ";"))
}
func (s *CallOrderSuite) SetupTest() {
s.T().Parallel()
s.call("SetupTest")
}
func (s *CallOrderSuite) TearDownTest() {
s.call("TearDownTest")
}
func (s *CallOrderSuite) Test_A() {
s.call("Test A")
}
//func (s *CallOrderSuite) Test_B() {
// time.Sleep(time.Second)
// s.call("Test B")
//}
|
Fix display of tildes in PDF output.
|
# encoding: utf-8
import sys
lines = sys.stdin.readlines()
# Contact details are expected to begin on the fourth line, following the
# header and a blank line, and extend until the next blank line. Lines with
# bullets (•) will be split into separate lines.
contact_lines = []
for line in lines[3:]:
lines.remove(line)
parts = [x.strip() for x in line.split("•")]
if parts == ['']:
break
contact_lines.extend(parts)
if '--tex' in sys.argv:
lines.insert(0, "\\begin{nospace}\\begin{flushright}\n" +
"\n\n".join(contact_lines) +
"\n\\end{flushright}\\end{nospace}\n")
print "".join(lines).replace('~', '$\sim$')
if '--html' in sys.argv:
lines.insert(0, "<div id='container'><div id='contact'>%s</div>\n" %
"<br>".join(contact_lines))
lines.insert(1, "<div>")
lines.append("</div>")
print "".join(lines)
|
# encoding: utf-8
import sys
lines = sys.stdin.readlines()
# Contact details are expected to begin on the fourth line, following the
# header and a blank line, and extend until the next blank line. Lines with
# bullets (•) will be split into separate lines.
contact_lines = []
for line in lines[3:]:
lines.remove(line)
parts = [x.strip() for x in line.split("•")]
if parts == ['']:
break
contact_lines.extend(parts)
if '--tex' in sys.argv:
lines.insert(0, "\\begin{nospace}\\begin{flushright}\n" +
"\n\n".join(contact_lines) +
"\n\\end{flushright}\\end{nospace}\n")
print "".join(lines)
if '--html' in sys.argv:
lines.insert(0, "<div id='container'><div id='contact'>%s</div>\n" %
"<br>".join(contact_lines))
lines.insert(1, "<div>")
lines.append("</div>")
print "".join(lines)
|
fix(boot): Define variables that are used but not defined
|
var URL = require('url')
, redis = require('redis');
module.exports = function (config) {
var client, url, port, host, db, auth, options;
if (config = config || {}) {
try {
url = URL.parse(config && config.url || process.env.REDIS_PORT || 'redis://localhost:6379');
port = url.port;
host = url.hostname;
db = config.db;
auth = config && config.auth;
options = {
no_ready_check: true
};
client = redis.createClient(port, host, options);
if (auth) {
client.auth(auth, function () {});
}
if (db) {
client.select(db);
}
} catch (e) {
throw new Error(e);
}
}
return module.exports = client;
};
|
var URL = require('url')
, redis = require('redis');
module.exports = function (config) {
var client, url, port, host, db, pass;
if (config = config || {}) {
try {
url = URL.parse(config && config.url || process.env.REDIS_PORT || 'redis://localhost:6379');
port = url.port;
host = url.hostname;
db = config.db;
auth = config && config.auth;
options = {
no_ready_check: true
}
client = redis.createClient(port, host, options);
if (auth) {
client.auth(auth, function () {});
}
if (db) {
client.select(db);
}
} catch (e) {
throw new Error(e);
}
}
return module.exports = client;
};
|
Handle errors and fix code styling
|
var player = require('chromecast-player')()
player.attach(function (err, p) {
if (err) console.error('An error ocurred while attaching the player: ' + err)
var playButton = document.querySelector('.play')
var playButtonIcon = document.querySelector('.play i.fa')
playButton.addEventListener('click', function () {
p.getStatus(function (err, status) {
if (err) console.error('An error ocurred while getting status of player: ' + err)
if (status.playerState === 'PLAYING') {
p.pause(function () {
playButtonIcon.classList.remove('fa-play')
playButtonIcon.classList.add('fa-pause')
})
} else {
p.play(function () {
playButtonIcon.classList.remove('fa-pause')
playButtonIcon.classList.add('fa-play')
})
}
})
})
})
|
var player = require('chromecast-player')()
player.attach(function (err, p) {
if (err) console.error('An error ocurred while attaching the player: ' + err)
var playButton = document.querySelector('.play')
var playButtonIcon = document.querySelector('.play i.fa');
playButton.addEventListener('click', function () {
p.getStatus(function (err, status) {
if (status.playerState === 'PLAYING') {
p.pause(function () {
playButtonIcon.classList.remove('fa-play')
playButtonIcon.classList.add('fa-pause')
})
} else {
p.play(function () {
playButtonIcon.classList.remove('fa-pause')
playButtonIcon.classList.add('fa-play')
})
}
})
})
})
|
Include missing save method for Model class
|
<?php
require('kissmvc_core.php');
//===============================================================
// Engine
//===============================================================
class Engine extends KISS_Engine
{
function request_not_found( $msg='' )
{
header( "HTTP/1.0 404 Not Found" );
die( '<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p><p>Please go <a href="javascript: history.back( 1 )">back</a> and try again.</p><hr /><p>Powered By: <a href="http://kissmvc.com">KISSMVC</a></p></body></html>' );
}
}
//===============================================================
// Controller
//===============================================================
class Controller extends KISS_Controller
{
}
//===============================================================
// Model/ORM
//===============================================================
class Model extends KISS_Model
{
function save() {
// one function to either create or update!
if ($this->rs[$this->pkname] == '')
{
//primary key is empty, so create
$this->create();
}
else
{
//primary key exists, so update
$this->update();
}
}
}
//===============================================================
// View
//===============================================================
class View extends KISS_View
{
}
|
<?php
require('kissmvc_core.php');
//===============================================================
// Engine
//===============================================================
class Engine extends KISS_Engine
{
function request_not_found( $msg='' )
{
header( "HTTP/1.0 404 Not Found" );
die( '<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p><p>Please go <a href="javascript: history.back( 1 )">back</a> and try again.</p><hr /><p>Powered By: <a href="http://kissmvc.com">KISSMVC</a></p></body></html>' );
}
}
//===============================================================
// Controller
//===============================================================
class Controller extends KISS_Controller
{
}
//===============================================================
// Model/ORM
//===============================================================
class Model extends KISS_Model
{
}
//===============================================================
// View
//===============================================================
class View extends KISS_View
{
}
|
Add select business basic functions
|
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('root', [
'uses' => 'RootController@index',
'middleware' => ['auth', 'acl'],
'is' => 'root']);
Route::resource('businesses', 'BusinessesController');
Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']);
Route::get('/', 'WelcomeController@index');
Route::get('home', 'HomeController@index');
Route::get('select/{business_slug}', function ($business_slug) {
try {
$business_id = App\Business::where('slug', $business_slug)->first()->id;
} catch (Exception $e) {
return 'error';
}
Session::set('selected.business_id', $business_id);
return $business_id;
});
Route::get('selected', function () {
$business_id = Session::get('selected.business_id');
return $business_id;
});
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
|
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('root', [
'uses' => 'RootController@index',
'middleware' => ['auth', 'acl'],
'is' => 'root']);
Route::resource('businesses', 'BusinessesController');
Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']);
Route::get('/', 'WelcomeController@index');
Route::get('home', 'HomeController@index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
|
[CHORE] Update User.createEncrypted call to use new argument object syntax.
|
var User = require('../models/user'),
GatewayAccount = require("../models/gateway_account"),
utils = require('../../lib/utils'),
util = require('util');
module.exports = (function() {
function index(req, res) {
User.all().success(function(users) {
res.send(users);
});
}
function create(req, res) {
req.checkBody('name', 'Invalid name')
.notEmpty().isAlphanumeric();
req.checkBody('password', 'Invalid password')
.notEmpty().isAlphanumeric();
//req.checkBody('rippleAddress', 'Invalid rippleAddress')
// .notEmpty().isAlphanumeric();
var errors = req.validationErrors();
if (errors) {
res.send({ error: util.inspect(errors) }, 400)
return;
}
User.createEncrypted({ name: name, password: password }, function(err, user) {
console.log('user', user)
if (err) { utils.errorResponse(res)(err); return }
GatewayAccount.create({ userId: user.id.toString() }).complete(function(err, bankAccount){
if(err){ res.send({ success: false, error: err }) }
user.bankAccount = bankAccount;
res.send({ success: true, user: user, gatewayAccount: bankAccount })
})
})
}
return {
index: index,
create: create
}
})();
|
var User = require('../models/user'),
GatewayAccount = require("../models/gateway_account"),
utils = require('../../lib/utils'),
util = require('util');
module.exports = (function() {
function index(req, res) {
User.all().success(function(users) {
res.send(users);
});
}
function create(req, res) {
req.checkBody('name', 'Invalid name')
.notEmpty().isAlphanumeric();
req.checkBody('password', 'Invalid password')
.notEmpty().isAlphanumeric();
//req.checkBody('rippleAddress', 'Invalid rippleAddress')
// .notEmpty().isAlphanumeric();
var errors = req.validationErrors();
if (errors) {
res.send({ error: util.inspect(errors) }, 400)
return;
}
User.createEncrypted(req.body.name, req.body.password, function(err, user) {
console.log('user', user)
if (err) { utils.errorResponse(res)(err); return }
GatewayAccount.create({ userId: user.id.toString() }).complete(function(err, bankAccount){
if(err){ res.send({ success: false, error: err }) }
user.bankAccount = bankAccount;
res.send({ success: true, user: user, gatewayAccount: bankAccount })
})
})
}
return {
index: index,
create: create
}
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.