text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix comment and improve readability
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package heaps
// reverseInts reverse elements of an[i:j] in an.
func reverseInts(an []int, i, j int) {
for i < j {
an[i], an[j] = an[j], an[i]
i++
j--
}
}
// SortK sorts k-increasing-decreasing slice an and returns the result.
// The time complexity is O(n*log(k)). Beyond the space needed to write
// the final result, the O(k) additional space is needed.
// The an can be modified during the function execution.
func SortK(an []int) []int {
i, o := 0, 1 // o - Order: 1 - increasing, -1 - decreasing.
var ss [][]int
for j := 1; j <= len(an); j++ {
if j == len(an) || o > 0 && an[j-1] > an[j] || o < 0 && an[j-1] < an[j] {
if o < 0 {
reverseInts(an, i, j-1)
}
ss = append(ss, an[i:j])
i, o = j, -o
}
}
return MergeSorted(ss)
}
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package heaps
// reverseInts reverse elements of an[i:j] in an.
func reverseInts(an []int, i, j int) {
for i < j {
an[i], an[j] = an[j], an[i]
i++
j--
}
}
// SortK sorts k-increasing-decreasing slice an and returns the result.
// The time complexity is O(n*log(k)). Beyond the space needed to write
// the final result, the O(k) additional space is needed.
// The an can be modified during the function execution.
func SortK(an []int) []int {
i := 0
o := 1 // Order: 1 - increasing, -1 decreasing.
var ss [][]int
for j := 1; j <= len(an); j++ {
if j == len(an) || o > 0 && an[j-1] > an[j] || o < 0 && an[j-1] < an[j] {
if o < 0 {
reverseInts(an, i, j-1)
}
ss = append(ss, an[i:j])
i, o = j, -o
}
}
return MergeSorted(ss)
}
|
Fix for regression test, since we rely on the formatter for std::vector in the test we need a libc++ category.
See differential https://reviews.llvm.org/D59847 for initial change that this fixes
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@357210 91177308-0d34-0410-b5e6-96231b3b80d8
|
"""
Test Expression Parser regression test to ensure that we handle enums
correctly, in this case specifically std::vector of enums.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestVectorOfEnums(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories(["libc++"])
def test_vector_of_enums(self):
self.build()
lldbutil.run_to_source_breakpoint(self, '// break here',
lldb.SBFileSpec("main.cpp", False))
self.expect("expr v", substrs=[
'size=3',
'[0] = a',
'[1] = b',
'[2] = c',
'}'
])
|
"""
Test Expression Parser regression test to ensure that we handle enums
correctly, in this case specifically std::vector of enums.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestVectorOfEnums(TestBase):
mydir = TestBase.compute_mydir(__file__)
def test_vector_of_enums(self):
self.build()
lldbutil.run_to_source_breakpoint(self, '// break here',
lldb.SBFileSpec("main.cpp", False))
self.expect("expr v", substrs=[
'size=3',
'[0] = a',
'[1] = b',
'[2] = c',
'}'
])
|
Mark UIExamples as a prototype
Summary: Ref T9103. This application is only useful for developing Phabricator, and in general is not kept "production ready". Mark it as a prototype.
Test Plan: visit /applications/, see it marked as prototype.
Reviewers: epriestley
Reviewed By: epriestley
Subscribers: Korvin
Maniphest Tasks: T9103
Differential Revision: https://secure.phabricator.com/D13822
|
<?php
final class PhabricatorUIExamplesApplication extends PhabricatorApplication {
public function getBaseURI() {
return '/uiexample/';
}
public function getShortDescription() {
return pht('Developer UI Examples');
}
public function getName() {
return pht('UIExamples');
}
public function getFontIcon() {
return 'fa-magnet';
}
public function getTitleGlyph() {
return "\xE2\x8F\x9A";
}
public function getFlavorText() {
return pht('A gallery of modern art.');
}
public function getApplicationGroup() {
return self::GROUP_DEVELOPER;
}
public function isPrototype() {
return true;
}
public function getApplicationOrder() {
return 0.110;
}
public function getRoutes() {
return array(
'/uiexample/' => array(
'' => 'PhabricatorUIExampleRenderController',
'view/(?P<class>[^/]+)/' => 'PhabricatorUIExampleRenderController',
),
);
}
}
|
<?php
final class PhabricatorUIExamplesApplication extends PhabricatorApplication {
public function getBaseURI() {
return '/uiexample/';
}
public function getShortDescription() {
return pht('Developer UI Examples');
}
public function getName() {
return pht('UIExamples');
}
public function getFontIcon() {
return 'fa-magnet';
}
public function getTitleGlyph() {
return "\xE2\x8F\x9A";
}
public function getFlavorText() {
return pht('A gallery of modern art.');
}
public function getApplicationGroup() {
return self::GROUP_DEVELOPER;
}
public function getApplicationOrder() {
return 0.110;
}
public function getRoutes() {
return array(
'/uiexample/' => array(
'' => 'PhabricatorUIExampleRenderController',
'view/(?P<class>[^/]+)/' => 'PhabricatorUIExampleRenderController',
),
);
}
}
|
Convert to new bindShared method on container.
|
<?php namespace Illuminate\Validation;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerPresenceVerifier();
$this->app->bindShared('validator', function($app)
{
$validator = new Factory($app['translator'], $app);
// The validation presence verifier is responsible for determining the existence
// of values in a given data collection, typically a relational database or
// other persistent data stores. And it is used to check for uniqueness.
if (isset($app['validation.presence']))
{
$validator->setPresenceVerifier($app['validation.presence']);
}
return $validator;
});
}
/**
* Register the database presence verifier.
*
* @return void
*/
protected function registerPresenceVerifier()
{
$this->app->bindShared('validation.presence', function($app)
{
return new DatabasePresenceVerifier($app['db']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('validator', 'validation.presence');
}
}
|
<?php namespace Illuminate\Validation;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerPresenceVerifier();
$this->app['validator'] = $this->app->share(function($app)
{
$validator = new Factory($app['translator'], $app);
// The validation presence verifier is responsible for determining the existence
// of values in a given data collection, typically a relational database or
// other persistent data stores. And it is used to check for uniqueness.
if (isset($app['validation.presence']))
{
$validator->setPresenceVerifier($app['validation.presence']);
}
return $validator;
});
}
/**
* Register the database presence verifier.
*
* @return void
*/
protected function registerPresenceVerifier()
{
$this->app['validation.presence'] = $this->app->share(function($app)
{
return new DatabasePresenceVerifier($app['db']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('validator', 'validation.presence');
}
}
|
Implement shutdown command for Windows
|
// Initial timer length in seconds
var timerCount = 15,
remote = require('electron').remote,
arguments = remote.getGlobal('sharedObject').prop1;
// debug mode ensures that computer doesnt shut down while testing
// npm start --debug
if (arguments[2] == '--debug') {
console.log('Debug mode enabled');
var debug = true;
}
// Timer constructor
var TimerFunc = function() {
window.onload = function() {
this.timerID = document.getElementById('timer');
// Disply initial timer length, currently in seconds
this.timerID.innerHTML = timerCount;
if (debug) {
document.getElementById('titleHeader').innerHTML += '**DEBUG**';
};
};
};
// Function to start countdown, decrements timerCount in seconds
TimerFunc.prototype.startTimer = function() {
var self = this;
if (timerCount > 0) {
self.countdown = window.setInterval(function() {
timerCount--;
this.timerID.innerHTML = timerCount;
if (timerCount <= 0) {
self.endTimer();
shutdown();
}
}, 1000);
};
};
// Function to manually stop timer from counting
TimerFunc.prototype.endTimer = function() {
clearInterval(this.countdown);
};
var timer = new TimerFunc();
function shutdown() {
if (debug) {
alert('Debug: Shutting it down!');
} else {
var exec = require('child-process').exec;
var cmd = 'shutdown -t 15 -s';
exec(cmd, function(error, stdout, stderr) {});
};
};
|
// Initial timer length in seconds
var timerCount = 15,
remote = require('electron').remote,
arguments = remote.getGlobal('sharedObject').prop1;
// debug mode ensures that computer doesnt shut down while testing
// npm start --debug
if (arguments[2] == '--debug') {
console.log('Debug mode enabled');
var debug = true;
}
// Timer constructor
var TimerFunc = function() {
window.onload = function() {
this.timerID = document.getElementById('timer');
// Disply initial timer length, currently in seconds
this.timerID.innerHTML = timerCount;
if (debug) {
document.getElementById('titleHeader').innerHTML += '**DEBUG**';
};
};
};
// Function to start countdown, decrements timerCount in seconds
TimerFunc.prototype.startTimer = function() {
var self = this;
if (timerCount > 0) {
self.countdown = window.setInterval(function() {
timerCount--;
this.timerID.innerHTML = timerCount;
if (timerCount <= 0) {
self.endTimer();
shutdown();
}
}, 1000);
};
};
// Function to manually stop timer from counting
TimerFunc.prototype.endTimer = function() {
clearInterval(this.countdown);
};
var timer = new TimerFunc();
function shutdown() {
if (debug) {
alert('Debug: Shutting it down!');
} else {
};
};
|
Change nodelist.foreach to a normal for loop
This should bring much greater browser compatibility the the nodelist foreach allowing it to work on all the major browser vendors.
Fixes #95
|
/* Cached Variables *******************************************************************************/
var context = sessionStorage.getItem('context');
var rowThumbnails = document.querySelector('.row-thumbnails');
/* Initialization *********************************************************************************/
rowThumbnails.addEventListener("click", moeRedirect, false);
function moeRedirect(event) {
var target = event.target;
var notImage = target.className !== 'thumbnail-image';
if(notImage) return;
var pageId = target.getAttribute('data-page-id');
window.location.href = context + '/page/' + pageId;
}
var thumbnails = window.document.querySelectorAll('.thumbnail');
var tallestThumbnailSize = 0;
for (var i = 0; i < thumbnails.length; i++) {
var offsetHeight = thumbnails[i].offsetHeight;
if(offsetHeight > tallestThumbnailSize) tallestThumbnailSize = offsetHeight;
};
for (var i = 0; i < thumbnails.length; i++) {
thumbnails[i].setAttribute('style','min-height:' + tallestThumbnailSize + 'px');
};
//After thumbnail processing, remove the page-loading blocker
document.querySelector('body').classList.remove('content-loading');
|
/* Cached Variables *******************************************************************************/
var context = sessionStorage.getItem('context');
var rowThumbnails = document.querySelector('.row-thumbnails');
/* Initialization *********************************************************************************/
rowThumbnails.addEventListener("click", moeRedirect, false);
function moeRedirect(event) {
var target = event.target;
var notImage = target.className !== 'thumbnail-image';
if(notImage) return;
var pageId = target.getAttribute('data-page-id');
window.location.href = context + '/page/' + pageId;
}
var thumbnails = window.document.querySelectorAll('.thumbnail');
var tallestThumbnailSize = 0;
thumbnails.forEach(function(value, key, listObj, argument) {
var offsetHeight = listObj[key].offsetHeight;
if(offsetHeight > tallestThumbnailSize) tallestThumbnailSize = offsetHeight;
});
thumbnails.forEach(function(value, key, listObj, argument) {
listObj[key].setAttribute('style','min-height:' + tallestThumbnailSize + 'px');
});
//After thumbnail processing, remove the page-loading blocker
document.querySelector('body').classList.remove('content-loading');
|
Add //bindings_list = ['sidorares-nodejs-mysql-native'] for tests
|
#!/usr/bin/env node
/*
Copyright (C) 2010, Oleg Efimov <efimovov@gmail.com>
See license text in LICENSE file
*/
var
bindings_list = ['Sannis-node-mysql-libmysqlclient', 'felixge-node-mysql', /*'stevebest-node-mysql',*/ 'PHP-MySQL'],
//bindings_list = ['sidorares-nodejs-mysql-native'],
sys = require('sys'),
default_factor = 1,
factor = default_factor,
cfg;
if (process.argv[2] !== undefined) {
factor = Math.abs(process.argv[2]);
if (isNaN(factor)) {
factor = default_factor;
}
}
cfg = require("./src/config").getConfig(factor);
function runNextBenchmark() {
if (bindings_list.length > 0) {
var binding_name = bindings_list.shift();
sys.puts("\033[1mBenchmarking " + binding_name + ":\033[22m");
var benchmark = require("./src/" + binding_name);
benchmark.run(function () {
runNextBenchmark();
}, cfg);
} else {
sys.puts("\033[1mAll benchmarks finished\033[22m");
}
}
runNextBenchmark();
|
#!/usr/bin/env node
/*
Copyright (C) 2010, Oleg Efimov <efimovov@gmail.com>
See license text in LICENSE file
*/
var
bindings_list = ['Sannis-node-mysql-libmysqlclient', 'felixge-node-mysql', /*'stevebest-node-mysql',*/ 'PHP-MySQL'],
sys = require('sys'),
default_factor = 1,
factor = default_factor,
cfg;
if (process.argv[2] !== undefined) {
factor = Math.abs(process.argv[2]);
if (isNaN(factor)) {
factor = default_factor;
}
}
cfg = require("./src/config").getConfig(factor);
function runNextBenchmark() {
if (bindings_list.length > 0) {
var binding_name = bindings_list.shift();
sys.puts("\033[1mBenchmarking " + binding_name + ":\033[22m");
var benchmark = require("./src/" + binding_name);
benchmark.run(function () {
runNextBenchmark();
}, cfg);
} else {
sys.puts("\033[1mAll benchmarks finished\033[22m");
}
}
runNextBenchmark();
|
Update the startup command to use the new version of the rug
Change-Id: Ie014dcfb0974b048025aeff96b16a868f672b84a
Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
|
from setuptools import setup, find_packages
setup(
name='akanda-rug',
version='0.1.5',
description='Akanda Router Update Generator manages tenant routers',
author='DreamHost',
author_email='dev-community@dreamhost.com',
url='http://github.com/dreamhost/akanda-rug',
license='BSD',
install_requires=[
'netaddr>=0.7.5',
'httplib2>=0.7.2',
'python-quantumclient>=2.1',
'oslo.config',
'kombu==1.0.4'
],
namespace_packages=['akanda'],
packages=find_packages(exclude=['test']),
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'akanda-rug-service=akanda.rug.main:main',
]
},
)
|
from setuptools import setup, find_packages
setup(
name='akanda-rug',
version='0.1.5',
description='Akanda Router Update Generator manages tenant routers',
author='DreamHost',
author_email='dev-community@dreamhost.com',
url='http://github.com/dreamhost/akanda-rug',
license='BSD',
install_requires=[
'netaddr>=0.7.5',
'httplib2>=0.7.2',
'python-quantumclient>=2.1',
'oslo.config',
'kombu==1.0.4'
],
namespace_packages=['akanda'],
packages=find_packages(exclude=['test']),
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'akanda-rug-service=akanda.rug.service:main',
'akanda-rug-new=akanda.rug.main:main',
]
},
)
|
Switch in/out degree for neighbor rank
Edges point in the direction of time, or influence. That means we're
concerned with outdegree (amount of nodes influenced by the current
node), not indegree (amount of nodes that influence the current node).
|
import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest outdegree (most often cited).
nodes = util.top_n_from_dict(graph.out_degree(), n=n)
# Find neighborhood sizes.
nhood_sizes = {}
for root in nodes:
# Neighborhood begins with just the root.
nhood = set([root])
# Expand the neighborhood repeatedly until the depth is reached.
for i in range(neighborhood_depth):
prev_nhood = nhood.copy()
for node in prev_nhood:
nhood |= set(graph.predecessors(node))
# Update the results dict.
nhood_sizes[root] = len(nhood)
return nhood_sizes
|
import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest indegree (most often cited).
nodes = util.top_n_from_dict(graph.in_degree(), n=n)
# Find neighborhood sizes.
nhood_sizes = {}
for root in nodes:
# Neighborhood begins with just the root.
nhood = set([root])
# Expand the neighborhood repeatedly until the depth is reached.
for i in range(neighborhood_depth):
prev_nhood = nhood.copy()
for node in prev_nhood:
nhood |= set(graph.successors(node))
# Update the results dict.
nhood_sizes[root] = len(nhood)
return nhood_sizes
|
Rename angular-mocks path and shim
|
// requiring global requireJS config
require(['/base/config/require.conf.js'], function() {
'use strict';
// first require.config overload: Karma specific
require.config({
baseUrl: '/base/src',
paths: {
'angular-mocks': '../bower_components/angular-mocks/angular-mocks'
},
shim: {
'angular-mocks': {
deps: ['angular']
}
}
});
require(['angular-mocks'], function() {
var specFiles = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/\/base\/src\/.*_test\.js$/.test(file)) {
specFiles.push(file);
}
}
}
// second overload to include specFiles and start Karma
require.config({
deps: specFiles,
callback: window.__karma__.start
});
});
});
|
// requiring global requireJS config
require(['/base/config/require.conf.js'], function() {
'use strict';
// first require.config overload: Karma specific
require.config({
baseUrl: '/base/src',
paths: {
'angularMocks': '../bower_components/angular-mocks/angular-mocks'
},
shim: {
'angularMocks': {
deps: ['angular']
}
}
});
require(['angularMocks'], function() {
var specFiles = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/\/base\/src\/.*_test\.js$/.test(file)) {
specFiles.push(file);
}
}
}
// second overload to include specFiles and start Karma
require.config({
deps: specFiles,
callback: window.__karma__.start
});
});
});
|
Put timestamp first in output
|
//! dnajs-smart-update-websockets ~ MIT License
const app = {
wsUrl: 'ws://localhost:7777/',
ws: null, //instance of WebSocket
wsSend: (message) => {
message = { timestamp: Date.now(), ...message };
app.log({ outgoing: message });
app.ws.send(JSON.stringify(message));
},
wsHandleMessageEvent: (event) => {
app.log({ incoming: JSON.parse(event.data) });
},
wsHandleConnectEvent: (event) => {
app.log({ connected: event.target.url });
app.wsSend({ note: 'Client is connected' });
},
wsInit: () => {
app.ws = new WebSocket(app.wsUrl);
app.ws.onopen = app.wsHandleConnectEvent;
app.ws.onmessage = app.wsHandleMessageEvent;
},
actionSendMessage: (inputElem) => {
app.wsSend({ text: inputElem.val() });
},
actionDisconnect: () => {
app.ws.close();
app.log('*** End ***');
},
log: (value) => {
dna.clone('log', { value: JSON.stringify(value) }, { fade: true, top: true });
},
setup: () => {
app.log('*** Start ***');
app.wsInit();
}
};
|
//! dnajs-smart-update-websockets ~ MIT License
const app = {
wsUrl: 'ws://localhost:7777/',
ws: null, //instance of WebSocket
wsSend: (message) => {
message.timestamp = Date.now();
app.log({ outgoing: message });
app.ws.send(JSON.stringify(message));
},
wsHandleMessageEvent: (event) => {
app.log({ incoming: JSON.parse(event.data) });
},
wsHandleConnectEvent: (event) => {
app.log({ connected: event.target.url });
app.wsSend({ note: 'Client is connected' });
},
wsInit: () => {
app.ws = new WebSocket(app.wsUrl);
app.ws.onopen = app.wsHandleConnectEvent;
app.ws.onmessage = app.wsHandleMessageEvent;
},
actionSendMessage: (inputElem) => {
app.wsSend({ text: inputElem.val() });
},
actionDisconnect: () => {
app.ws.close();
app.log('*** End ***');
},
log: (value) => {
dna.clone('log', { value: JSON.stringify(value) }, { fade: true, top: true });
},
setup: () => {
app.log('*** Start ***');
app.wsInit();
}
};
|
Update TreeBuilder instantiation - fixing 4.3 deprecation
|
<?php
namespace AshleyDawson\GlideBundle\DependencyInjection;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
/**
* Class Configuration
*
* @package AshleyDawson\GlideBundle\DependencyInjection
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('ashley_dawson_glide');
$rootNode = $treeBuilder->getRootNode();
$rootNode
->children()
->integerNode('max_image_size')->defaultValue(4000000)->end()
->scalarNode('image_manager_driver')->defaultValue('gd')->end()
->end()
;
return $treeBuilder;
}
}
|
<?php
namespace AshleyDawson\GlideBundle\DependencyInjection;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
/**
* Class Configuration
*
* @package AshleyDawson\GlideBundle\DependencyInjection
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ashley_dawson_glide');
$rootNode
->children()
->integerNode('max_image_size')->defaultValue(4000000)->end()
->scalarNode('image_manager_driver')->defaultValue('gd')->end()
->end()
;
return $treeBuilder;
}
}
|
Remove languages from Pencil and update logo image
|
<div id="frame">
<header class="main">
<!--<div id="menu-idiomas">[ [COMPONENT name=MenuLanguages]]</div>-->
<div class="logo">[[COMPONENT name=Image id=logo style=height:60]]</div>
<h1><a href="/">[[COMPONENT name=Label text=Título id=title]]</a></h1>
<h2>[[COMPONENT name=Label text=Subtítulo id=subtitle]]</h2>
</header>
<div id="body">
<div id="marco_migas">
[[COMPONENT name=Breadcrumb]]
</div>
<div id="right">
[[COMPONENT name=Menu]]
</div>
<section class="main">
[[BODY]]
</section>
</div>
<footer class="main">
<span>© 2012</span>
<span>Powered By <a href="http://www.treeweb.es/">TreeWeb</a></span>
</footer>
</div>
|
<div id="frame">
<header class="main">
<div id="menu-idiomas">[ [COMPONENT name=MenuLanguages]]</div>
<div class="logo">[[COMPONENT name=Image style=height:60 id=1]]</div>
<h1><a href="/">[[COMPONENT name=Label text=Título id=title]]</a></h1>
<h2>[[COMPONENT name=Label text=Subtítulo id=subtitle]]</h2>
</header>
<div id="body">
<div id="marco_migas">
[[COMPONENT name=Breadcrumb]]
</div>
<div id="right">
[[COMPONENT name=Menu]]
</div>
<section class="main">
[[BODY]]
</section>
</div>
<footer class="main">
<span>© 2012</span>
<span>Powered By <a href="http://www.treeweb.es/">TreeWeb</a></span>
</footer>
</div>
|
Make sure Counter implementation expvar.Var
|
package metrics
import (
"strconv"
"sync/atomic"
)
type Counter interface {
Inc(delta int64)
Dec(delta int64)
Set(delta int64)
Count() int64
String() string
}
type atomicCounter int64
func NewCounter() Counter {
c := atomicCounter(int64(0))
return &c
}
func (c *atomicCounter) Inc(delta int64) {
atomic.AddInt64((*int64)(c), delta)
}
func (c *atomicCounter) Dec(delta int64) {
atomic.AddInt64((*int64)(c), -delta)
}
func (c *atomicCounter) Set(value int64) {
atomic.StoreInt64((*int64)(c), value)
}
func (c *atomicCounter) Count() int64 {
return atomic.LoadInt64((*int64)(c))
}
func (c *atomicCounter) String() string {
return strconv.FormatInt(c.Count(), 10)
}
|
package metrics
import (
"strconv"
"sync/atomic"
)
type Counter interface {
Inc(delta int64)
Dec(delta int64)
Set(delta int64)
Count() int64
}
type atomicCounter int64
func NewCounter() Counter {
c := atomicCounter(int64(0))
return &c
}
func (c *atomicCounter) Inc(delta int64) {
atomic.AddInt64((*int64)(c), delta)
}
func (c *atomicCounter) Dec(delta int64) {
atomic.AddInt64((*int64)(c), -delta)
}
func (c *atomicCounter) Set(value int64) {
atomic.StoreInt64((*int64)(c), value)
}
func (c *atomicCounter) Count() int64 {
return atomic.LoadInt64((*int64)(c))
}
func (c *atomicCounter) String() string {
return strconv.FormatInt(c.Count(), 10)
}
|
Add link to Code of Conduct in Menu
|
<?php
/*******************************************************************************
* Copyright (c) 2015 Eclipse Foundation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christopher Guindon (Eclipse Foundation) - Initial implementation
*******************************************************************************/
if (!defined('ABSPATH')) exit;
?>
<ul class="nav navbar-nav navbar-right">
<li><a href="./index.php#about">About</a></li>
<li><a href="./index.php#registration">Register</a></li>
<li><a href="./terms.php">Terms</a></li>
<li><a href="./conduct.php">Code of Conduct</a></li>
<li><a href="./index.php#schedule">Schedule</a></li>
<li><a href="./index.php#sponsorship">Sponsorship</a></li>
</ul>
|
<?php
/*******************************************************************************
* Copyright (c) 2015 Eclipse Foundation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christopher Guindon (Eclipse Foundation) - Initial implementation
*******************************************************************************/
if (!defined('ABSPATH')) exit;
?>
<ul class="nav navbar-nav navbar-right">
<li><a href="./index.php#about">About</a></li>
<li><a href="./index.php#registration">Register</a></li>
<li><a href="./terms.php">Terms</a></li>
<li><a href="./index.php#schedule">Schedule</a></li>
<li><a href="./index.php#sponsorship">Sponsorship</a></li>
</ul>
|
Increase number of results to choose from
|
#! /usr/bin/env node
var http = require('http');
// http://www.reddit.com/r/jokes
//
var request = http.get('http://www.reddit.com/r/oneliners/hot.json?limit=50', function (response) {
var responseBody = '';
// concatenate data chunks to responseBody
response.on('data', function (dataChunk) {
responseBody += dataChunk;
});
// on request end
response.on('end', function() {
if(response.statusCode == 200) {
try {
// parse data
var listing = JSON.parse(responseBody);
// get array of listings
var arrayListings = listing.data.children;
var random = Math.floor(Math.random() * 50) + 1;
console.log(arrayListings[random].data.title);
} catch(error) {
// Print parse error
console.error("Parse error: " + error.message);
}
} else {
// print status code error message
console.error('There was an error fetching the listings (' + http.STATUS_CODES[response.statusCode] + ')');
}
});
});
|
#! /usr/bin/env node
var http = require('http');
// http://www.reddit.com/r/jokes
//
var request = http.get('http://www.reddit.com/r/oneliners/hot.json?limit=10', function (response) {
var responseBody = '';
// concatenate data chunks to responseBody
response.on('data', function (dataChunk) {
responseBody += dataChunk;
});
// on request end
response.on('end', function() {
if(response.statusCode == 200) {
try {
// parse data
var listing = JSON.parse(responseBody);
// get array of listings
var arrayListings = listing.data.children;
var random = Math.floor(Math.random() * 10) + 1;
console.log(arrayListings[random].data.title);
} catch(error) {
// Print parse error
console.error("Parse error: " + error.message);
}
} else {
// print status code error message
console.error('There was an error fetching the listings (' + http.STATUS_CODES[response.statusCode] + ')');
}
});
});
|
Add player in the test data
|
package entities
import "time"
var (
timeStamp int64 = time.Date(2012, time.November, 10, 23, 0, 0, 0, time.UTC).UnixNano() / 1e6
mission Mission = Mission{
Color: Color{22, 22, 22},
Source: []int{100, 200},
Target: []int{800, 150},
Type: "Attack",
CurrentTime: timeStamp,
StartTime: timeStamp,
TravelTime: timeStamp,
Player: "gophie",
ShipCount: 5,
}
planet Planet = Planet{
Color: Color{22, 22, 22},
Coords: []int{271, 203},
IsHome: false,
Texture: 3,
Size: 1,
LastShipCountUpdate: timeStamp,
ShipCount: 0,
MaxShipCount: 0,
Owner: "gophie",
}
player Player = Player{
username: "gophie",
Color: Color{22, 22, 22},
TwitterID: "asdf",
HomePlanet: "planet.271_203",
ScreenSize: []int{1, 1},
ScreenPosition: []int{2, 2},
}
)
|
package entities
import "time"
var (
timeStamp int64 = time.Date(2012, time.November, 10, 23, 0, 0, 0, time.UTC).UnixNano() / 1e6
mission Mission = Mission{
Color: Color{22, 22, 22},
Source: []int{100, 200},
Target: []int{800, 150},
Type: "Attack",
CurrentTime: timeStamp,
StartTime: timeStamp,
TravelTime: timeStamp,
Player: "gophie",
ShipCount: 5,
}
planet Planet = Planet{
Color: Color{22, 22, 22},
Coords: []int{271, 203},
IsHome: false,
Texture: 3,
Size: 1,
LastShipCountUpdate: timeStamp,
ShipCount: 0,
MaxShipCount: 0,
Owner: "gophie",
}
)
|
Use proper fixtures in project tests
|
const path = require('path');
const expect = require('chai').expect;
const getProjectConfig = require('../../src/config/android').projectConfig;
const mockFs = require('mock-fs');
const projects = require('../fixtures/projects');
describe('Config::getProjectConfig', () => {
before(() => {
mockFs({ testDir: projects });
});
it('should return an object with android project configuration', () => {
const userConfig = {};
const folder = path.join('testDir', 'nested');
expect(getProjectConfig(folder, userConfig)).to.be.an('object');
});
it('should return `null` if android project was not found', () => {
const userConfig = {};
const folder = path.join('testDir', 'empty');
expect(getProjectConfig(folder, userConfig)).to.be.null;
});
after(() => {
mockFs.restore();
});
});
|
const path = require('path');
const expect = require('chai').expect;
const getProjectConfig = require('../../src/config/android').projectConfig;
const mockFs = require('mock-fs');
const dependencies = require('../fixtures/dependencies');
describe('Config::getProjectConfig', () => {
before(() => {
mockFs({ testDir: dependencies });
});
it('should return an object with android project configuration', () => {
const userConfig = {};
const folder = path.join('testDir', 'react-native-vector-icons');
expect(getProjectConfig(folder, userConfig)).to.be.an('object');
});
it('should return `null` if android project was not found', () => {
const userConfig = {};
const folder = path.join('testDir', 'empty');
expect(getProjectConfig(folder, userConfig)).to.be.null;
});
after(() => {
mockFs.restore();
});
});
|
Fix tunnel provider connection temporization
The mechanism to wait several seconds between connection attempts to
provide a tunnel to PersistentRelayTunnel was totally broken.
Fix it to wait 5 seconds only before creating a new tunnel, except the
very first time.
|
package com.genymobile.gnirehtet;
import android.net.VpnService;
import java.io.IOException;
/**
* Provide a valid {@link RelayTunnel}, creating a new one if necessary.
*/
public class RelayTunnelProvider {
private final VpnService vpnService;
private RelayTunnel tunnel;
private boolean first = true;
public RelayTunnelProvider(VpnService vpnService) {
this.vpnService = vpnService;
}
public synchronized RelayTunnel getCurrentTunnel() throws IOException, InterruptedException {
if (tunnel == null) {
if (!first) {
// add delay between attempts
Thread.sleep(5000);
} else {
first = false;
}
tunnel = RelayTunnel.open(vpnService);
}
return tunnel;
}
public synchronized void invalidateTunnel() {
if (tunnel != null) {
tunnel.close();
tunnel = null;
}
}
}
|
package com.genymobile.gnirehtet;
import android.net.VpnService;
import java.io.IOException;
/**
* Provide a valid {@link RelayTunnel}, creating a new one if necessary.
*/
public class RelayTunnelProvider {
private final VpnService vpnService;
private RelayTunnel tunnel;
private boolean first;
public RelayTunnelProvider(VpnService vpnService) {
this.vpnService = vpnService;
}
public synchronized RelayTunnel getCurrentTunnel() throws IOException, InterruptedException {
if (!first) {
// add delay between attempts
Thread.sleep(5000);
first = true;
}
if (tunnel == null) {
tunnel = RelayTunnel.open(vpnService);
}
return tunnel;
}
public synchronized void invalidateTunnel() {
if (tunnel != null) {
tunnel.close();
tunnel = null;
}
}
}
|
Fix crash on init of ap-npm
|
import commander from 'commander';
import containerInit from './init';
import fs from 'fs';
import path from 'path';
commander
.command('serve')
.alias('s')
.description('serve ap-npm')
.option('--config', "config file to use")
.action(function(config) {
let container;
if (fs.existsSync(config)) {
console.log("using config: " + config + '\n');
container = containerInit(config);
}
else if (typeof config === 'string') {
if (fs.existsSync(path.join(__dirname, '../', config))) {
let configLocation = path.join(__dirname, '../', config);
console.log("using config: " + configLocation + '\n');
container = containerInit(configLocation);
}
}
else {
console.log("using default config\n");
container = containerInit("../config.json");
}
let command = container.get('command-serve');
command.run();
});
commander.parse(process.argv);
if (!process.argv.length) {
commander.outputHelp();
}
|
import commander from 'commander';
import containerInit from './init';
import fs from 'fs';
import path from 'path';
commander
.command('serve')
.alias('s')
.description('serve ap-npm')
.option('--config', "config file to use")
.action(function(config) {
let container;
if (fs.existsSync(config)) {
console.log("using config: " + config + '\n');
container = containerInit(config);
}
else if (fs.existsSync(path.join(__dirname, '../', config))) {
let configLocation = path.join(__dirname, '../', config);
console.log("using config: " + configLocation + '\n');
container = containerInit(configLocation);
}
else {
console.log("using default config\n");
container = containerInit("../config.json");
}
let command = container.get('command-serve');
command.run();
});
commander.parse(process.argv);
if (!process.argv.length) {
commander.outputHelp();
}
|
Fix Loop dependency in OrbitControls
Former-commit-id: 8a856c3abacefad6dd5679baa714fe7bc24446ee
|
import {Vector3} from 'three';
import {Loop} from '../../core/Loop';
import {ThreeOrbitControls} from './lib/ThreeOrbitControls';
export class OrbitModule {
constructor(params = {}) {
this.params = Object.assign({
target: new Vector3(0, 0, 0),
follow: false
}, params);
}
manager(manager) {
this.controls = new ThreeOrbitControls(
manager.get('camera').native,
manager.get('renderer').domElement
);
manager.update({
camera: (camera) => {
this.controls.object = camera.native;
}
});
}
integrate(self) {
const {params, controls} = self;
const updateProcessor = params.follow ? (c) => {
controls.update(c.getDelta());
controls.target.copy(params.target);
} : (c) => {
controls.update(c.getDelta());
};
self.updateLoop = new Loop(updateProcessor).start(this);
controls.target.copy(params.target);
}
}
|
import {Vector3} from 'three';
import {ThreeOrbitControls} from './lib/ThreeOrbitControls';
export class OrbitModule {
constructor(params = {}) {
this.params = Object.assign({
target: new Vector3(0, 0, 0),
follow: false
}, params);
}
manager(manager) {
this.controls = new ThreeOrbitControls(
manager.get('camera').native,
manager.get('renderer').domElement
);
manager.update({
camera: (camera) => {
this.controls.object = camera.native;
}
});
}
integrate(self) {
const {params, controls} = self;
const updateProcessor = params.follow ? (c) => {
controls.update(c.getDelta());
controls.target.copy(params.target);
} : (c) => {
controls.update(c.getDelta());
};
self.updateLoop = new WHS.Loop(updateProcessor).start(this);
controls.target.copy(params.target);
}
}
|
Add sample configuration for normalizing ID
|
/**
* The root component that wraps the main app component with all
* data-related components such as `ApolloProvider`.
* This component works on all platforms.
* @flow
*/
import React, { Component } from 'react';
import {
} from 'react-native';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import ApolloClient, { createNetworkInterface, addTypename } from 'apollo-client';
import ApolloProvider from 'react-apollo/ApolloProvider';
import reducers from './reducers';
// App container that provides navigation props and viewer data.
import Spoors from './containers/Spoors';
const networkInterface = createNetworkInterface('/api');
const client = new ApolloClient({
networkInterface,
// Apollo transformer to automatically add `__typename` to all queries.
queryTransformer: addTypename,
// Normalize ID for different object types for Apollo caching.
dataIdFromObject: (result) => {
if (result.id && result.__typename) {
return result.__typename + result.id;
}
return null;
}
});
// We use our own Redux store, so we combine Apollo with it.
const store = createStore(
combineReducers({
apollo: client.reducer(),
...reducers
}),
{}, // initial state
compose(
applyMiddleware(client.middleware()),
// If you are using the devToolsExtension, you can add it here also
window.devToolsExtension ? window.devToolsExtension() : f => f,
)
);
class App extends Component {
render() {
return (
<ApolloProvider store={store} client={client}>
<Spoors />
</ApolloProvider>
);
}
}
export default App;
|
/**
* The root component that wraps the main app component with all
* data-related components such as `ApolloProvider`.
* This component works on all platforms.
* @flow
*/
import React, { Component } from 'react';
import {
} from 'react-native';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import ApolloProvider from 'react-apollo/ApolloProvider';
import reducers from './reducers';
// App container that provides navigation props and viewer data.
import Spoors from './containers/Spoors';
const networkInterface = createNetworkInterface('/api');
const client = new ApolloClient({
networkInterface
});
// We use our own Redux store, so we combine Apollo with it.
const store = createStore(
combineReducers({
apollo: client.reducer(),
...reducers
}),
{}, // initial state
compose(
applyMiddleware(client.middleware()),
// If you are using the devToolsExtension, you can add it here also
window.devToolsExtension ? window.devToolsExtension() : f => f,
)
);
class App extends Component {
render() {
return (
<ApolloProvider store={store} client={client}>
<Spoors />
</ApolloProvider>
);
}
}
export default App;
|
Fix ResolverIntercept to maintain full import path while still normalizing the path; fixes npm support in truffle since bug >4.1.3
|
const path = require("path");
function ResolverIntercept(resolver) {
this.resolver = resolver;
this.cache = {};
};
ResolverIntercept.prototype.require = function(import_path) {
// Modify import_path so the cache key is consistently the same irrespective
// of whether a user explicated .sol extension
import_path = import_path.replace(/\.sol$/i, '');
// TODO: Using the import path for relative files may result in multiple
// paths for the same file. This could return different objects since it won't be a cache hit.
if (this.cache[import_path]) {
return this.cache[import_path];
}
// Note, will error if nothing is found.
var resolved = this.resolver.require(import_path);
this.cache[import_path] = resolved;
// During migrations, we could be on a network that takes a long time to accept
// transactions (i.e., contract deployment close to block size). Because successful
// migration is more important than wait time in those cases, we'll synchronize "forever".
resolved.synchronization_timeout = 0;
return resolved;
};
ResolverIntercept.prototype.contracts = function() {
var self = this;
return Object.keys(this.cache).map(function(key) {
return self.cache[key];
});
};
module.exports = ResolverIntercept;
|
const path = require("path");
function ResolverIntercept(resolver) {
this.resolver = resolver;
this.cache = {};
};
ResolverIntercept.prototype.require = function(import_path) {
// Modify import_path so the cache key is consistently the same irrespective
// of whether a user explicated .sol extension
import_path = path.basename(import_path, ".sol");
// TODO: Using the import path for relative files may result in multiple
// paths for the same file. This could return different objects since it won't be a cache hit.
if (this.cache[import_path]) {
return this.cache[import_path];
}
// Note, will error if nothing is found.
var resolved = this.resolver.require(import_path);
this.cache[import_path] = resolved;
// During migrations, we could be on a network that takes a long time to accept
// transactions (i.e., contract deployment close to block size). Because successful
// migration is more important than wait time in those cases, we'll synchronize "forever".
resolved.synchronization_timeout = 0;
return resolved;
};
ResolverIntercept.prototype.contracts = function() {
var self = this;
return Object.keys(this.cache).map(function(key) {
return self.cache[key];
});
};
module.exports = ResolverIntercept;
|
Add complex queries support for boolean types in bill api (BRCD-1316)
|
<?php
/**
* @package Billing
* @copyright Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
* @license GNU Affero General Public License Version 3; see LICENSE.txt
*/
/**
* Boolean type translator
*
* @package Api
* @since 5.3
*/
class Api_Translator_BooleanModel extends Api_Translator_TypeModel {
/**
* Translate an array
* @param mixed $data - Input data
* @return mixed Translated value.
*/
public function internalTranslateField($data) {
try {
if (is_array($data)) {
$ret = array();
foreach ($data as $cond => $date) {
$ret[$cond] = boolval($date);
}
return $ret;
}
return boolval($data);
} catch (MongoException $ex) {
return null;
}
}
/**
* method to validate the trasnlated value.
*
* @param mixed $data the data to check
* @return boolean true if valid else false
*/
protected function valid($data) {
return !is_null($data);
}
}
|
<?php
/**
* @package Billing
* @copyright Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
* @license GNU Affero General Public License Version 3; see LICENSE.txt
*/
/**
* Boolean type translator
*
* @package Api
* @since 5.3
*/
class Api_Translator_BooleanModel extends Api_Translator_TypeModel {
/**
* Translate an array
* @param mixed $data - Input data
* @return mixed Translated value.
*/
public function internalTranslateField($data) {
try {
return boolval($data);
} catch (MongoException $ex) {
return null;
}
}
/**
* method to validate the trasnlated value.
*
* @param mixed $data the data to check
* @return boolean true if valid else false
*/
protected function valid($data) {
return !is_null($data);
}
}
|
Update POST route request to be JSON
|
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var port = process.env.PORT || 3000
app.use(bodyParser.json())
app.get('/api/days/:day', function(request, response, next){
var daysOfWeek = {
monday: 1,
tuesday:2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 7
}
var day = request.params.day.toLowerCase()
response.set('Content-Type', 'application/text')
if(!daysOfWeek.hasOwnProperty(day)) {
response.status(400)
response.send(`'${day}' is not a valid day!`)
} else {
response.status(200)
response.send(String(daysOfWeek[day]))
}
})
app.post('/api/array/concat', function(request, response, next){
response.set('Content-Type', 'application/json')
var result = []
var bodyObj = request.body
for (item in bodyObj){
if(!Array.isArray(bodyObj[item])){
response.status(400)
return response.json({"error": "Input data should be of type Array."})
} else {
result = result.concat(bodyObj[item])
}
}
response.json({"result": result})
})
app.listen(port, function(){
console.log(`Listening on port ${port}`)
})
|
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var port = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/api/days/:day', function(request, response, next){
var daysOfWeek = {
monday: 1,
tuesday:2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 7
}
var day = request.params.day.toLowerCase()
response.set('Content-Type', 'application/text')
if(!daysOfWeek.hasOwnProperty(day)) {
response.status(400)
response.send(`'${day}' is not a valid day!`)
} else {
response.status(200)
response.send(String(daysOfWeek[day]))
}
})
app.post('/api/array/concat', function(request, response, next){
response.set('Content-Type', 'application/json')
var bodyObj = request.body
var arrays = []
for(item in bodyObj){
try {
arrays.push(JSON.parse(bodyObj[item]))
} catch(error) {
if(error instanceof SyntaxError) {
response.status(400)
return response.json({"error": "Input data should be of type Array."})
}
}
}
var result = [].concat.apply([], arrays)
response.json({"result": result})
})
app.listen(port, function(){
console.log(`Listening on port ${port}`)
})
|
Exit with non-zero when error occurs
|
'use strict';
const path = require('path');
const binBuild = require('bin-build');
const log = require('logalot');
const bin = require('.');
const args = [
'-copy',
'none',
'-optimize',
'-outfile',
path.join(__dirname, '../test/fixtures/test-optimized.jpg'),
path.join(__dirname, '../test/fixtures/test.jpg')
];
bin.run(args).then(() => {
log.success('jpegtran pre-build test passed successfully');
}).catch(async error => {
log.warn(error.message);
log.warn('jpegtran pre-build test failed');
log.info('compiling from source');
const cfg = [
'./configure --disable-shared',
`--prefix="${bin.dest()}" --bindir="${bin.dest()}"`
].join(' ');
try {
await binBuild.file(path.resolve(__dirname, '../vendor/source/libjpeg-turbo-1.5.1.tar.gz'), [
'touch configure.ac aclocal.m4 configure Makefile.am Makefile.in',
cfg,
'make install'
]);
log.success('jpegtran built successfully');
} catch (error) {
log.error(error.stack);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
}
});
|
'use strict';
const path = require('path');
const binBuild = require('bin-build');
const log = require('logalot');
const bin = require('.');
const args = [
'-copy',
'none',
'-optimize',
'-outfile',
path.join(__dirname, '../test/fixtures/test-optimized.jpg'),
path.join(__dirname, '../test/fixtures/test.jpg')
];
bin.run(args).then(() => {
log.success('jpegtran pre-build test passed successfully');
}).catch(async error => {
log.warn(error.message);
log.warn('jpegtran pre-build test failed');
log.info('compiling from source');
const cfg = [
'./configure --disable-shared',
`--prefix="${bin.dest()}" --bindir="${bin.dest()}"`
].join(' ');
try {
await binBuild.file(path.resolve(__dirname, '../vendor/source/libjpeg-turbo-1.5.1.tar.gz'), [
'touch configure.ac aclocal.m4 configure Makefile.am Makefile.in',
cfg,
'make install'
]);
log.success('jpegtran built successfully');
} catch (error) {
log.error(error.stack);
}
});
|
Fix FieldsEnabled function & add 'enabled' argument
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \param field_list
# \b \e tuple|list : List of wx control to be checked
# \param enabled
# \b \e bool : Status to check for (True=enabled, False=disabled)
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list, enabled=True):
if not isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list, enabled)
for F in field_list:
if not FieldEnabled(F, enabled):
return False
return True
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
Add some fields to the topics model.
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTopicsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('topics', function(Blueprint $table)
{
$table->increments('id');
$table->string('title')->index();
$table->text('body');
$table->text('body_orginal');
$table->text('excerpt')->nullable();
$table->integer('user_id')->index();
$table->integer('node_id')->index();
$table->boolean('excellent')->default(false)->index();
$table->boolean('blocked')->default(false)->index();
$table->integer('reply_count')->default(0)->index();
$table->integer('view_count')->default(0)->index();
$table->integer('favorite_count')->default(0)->index();
$table->integer('vote_count')->default(0)->index();
$table->integer('last_reply_user_id')->default(0)->index();
$table->integer('order')->default(0)->index();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('topics');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTopicsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('topics', function(Blueprint $table)
{
$table->increments('id');
$table->string('title')->index();
$table->text('body');
$table->integer('user_id')->index();
$table->integer('node_id')->index();
$table->boolean('excellent')->default(false)->index();
$table->boolean('blocked')->default(false)->index();
$table->integer('reply_count')->default(0)->index();
$table->integer('view_count')->default(0)->index();
$table->integer('favorite_count')->default(0)->index();
$table->integer('vote_count')->default(0)->index();
$table->integer('last_reply_user_id')->default(0)->index();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('topics');
}
}
|
Add pytest markers for cassandra tests
|
import mock
import pytest
from scrapi import settings
from scrapi import database
database._manager = database.DatabaseManager(keyspace='test')
settings.DEBUG = True
settings.CELERY_ALWAYS_EAGER = True
settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
@pytest.fixture(autouse=True)
def harvester(monkeypatch):
import_mock = mock.MagicMock()
harvester_mock = mock.MagicMock()
import_mock.return_value = harvester_mock
monkeypatch.setattr('scrapi.util.import_harvester', import_mock)
monkeypatch.setattr('scrapi.tasks.import_harvester', import_mock)
return harvester_mock
@pytest.fixture(autouse=True)
def timestamp_patch(monkeypatch):
monkeypatch.setattr('scrapi.util.timestamp', lambda: 'TIME')
monkeypatch.setattr('scrapi.tasks.timestamp', lambda: 'TIME')
def pytest_configure(config):
config.addinivalue_line(
'markers',
'cassandra: Handles setup and teardown for tests using cassandra'
)
def pytest_runtest_setup(item):
marker = item.get_marker('cassandra')
if marker is not None:
if not database.setup():
pytest.skip('No connection to Cassandra')
def pytest_runtest_teardown(item, nextitem):
marker = item.get_marker('cassandra')
if marker is not None:
database.tear_down(force=True)
|
import mock
import pytest
from scrapi import settings
settings.DEBUG = True
settings.CELERY_ALWAYS_EAGER = True
settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
@pytest.fixture(autouse=True)
def harvester(monkeypatch):
import_mock = mock.MagicMock()
harvester_mock = mock.MagicMock()
import_mock.return_value = harvester_mock
monkeypatch.setattr('scrapi.tasks.import_harvester', import_mock)
monkeypatch.setattr('scrapi.util.import_harvester', import_mock)
return harvester_mock
@pytest.fixture(autouse=True)
def timestamp_patch(monkeypatch):
monkeypatch.setattr('scrapi.util.timestamp', lambda: 'TIME')
monkeypatch.setattr('scrapi.tasks.timestamp', lambda: 'TIME')
|
Stop is not called "move stop". Woops.
|
/**
* Load all external dependencies
* We use var so it's global available : ) ( not let,const)
*/
var fs = require('fs');
var _ = require('lodash');
/**
* Load all internal dependencies
*/
const cfg = require('../config.js');
var pkg = require('../package.json');
var piJS = require('./modules/pi-js-module');
let pi = new piJS(cfg);
var io = require('socket.io')(9090);
io.on('connection', function(socket) {
console.info('socket connected. (' + socket.id + ')');
socket.on('forward', function() {
pi.handleAnswer('move forward');
socket.emit('forward');
console.info('forward');
});
socket.on('backward', function() {
pi.handleAnswer('move backward');
socket.emit('backward');
console.info('backward');
});
socket.on('left', function() {
pi.handleAnswer('move left');
socket.emit('left');
console.info('left');
});
socket.on('right', function() {
pi.handleAnswer('move right');
socket.emit('right');
console.info('right');
});
socket.on('stop', function() {
pi.handleAnswer('stop');
socket.emit('stop');
console.info('stop');
});
});
|
/**
* Load all external dependencies
* We use var so it's global available : ) ( not let,const)
*/
var fs = require('fs');
var _ = require('lodash');
/**
* Load all internal dependencies
*/
const cfg = require('../config.js');
var pkg = require('../package.json');
var piJS = require('./modules/pi-js-module');
let pi = new piJS(cfg);
var io = require('socket.io')(9090);
io.on('connection', function(socket) {
console.info('socket connected. (' + socket.id + ')');
socket.on('forward', function() {
pi.handleAnswer('move forward');
socket.emit('forward');
console.info('forward');
});
socket.on('backward', function() {
pi.handleAnswer('move backward');
socket.emit('backward');
console.info('backward');
});
socket.on('left', function() {
pi.handleAnswer('move left');
socket.emit('left');
console.info('left');
});
socket.on('right', function() {
pi.handleAnswer('move right');
socket.emit('right');
console.info('right');
});
socket.on('stop', function() {
pi.handleAnswer('move stop');
socket.emit('stop');
console.info('stop');
});
});
|
Change jaro-winkler to cosine similarity
|
from pygraphc.preprocess.ParallelPreprocess import ParallelPreprocess
from pygraphc.similarity.CosineSimilarity import ParallelCosineSimilarity
from pygraphc.pruning.TrianglePruning import TrianglePruning
import networkx as nx
class CreateGraphModel(object):
def __init__(self, log_file):
self.log_file = log_file
self.unique_events = []
self.unique_events_length = 0
self.distances = []
self.graph = nx.MultiGraph()
def __get_nodes(self):
pp = ParallelPreprocess(self.log_file)
self.unique_events = pp.get_unique_events()
self.unique_events_length = pp.unique_events_length
self.event_attributes = pp.event_attributes
def __get_distances(self):
pcs = ParallelCosineSimilarity(self.event_attributes, self.unique_events_length)
self.distances = pcs.get_parallel_cosine_similarity()
def create_graph(self):
self.__get_nodes()
self.__get_distances()
self.graph.add_nodes_from(self.unique_events)
self.graph.add_weighted_edges_from(self.distances)
tp = TrianglePruning(self.graph)
tp.get_triangle()
self.graph = tp.graph
return self.graph
|
from pygraphc.preprocess.ParallelPreprocess import ParallelPreprocess
from pygraphc.similarity.JaroWinkler import JaroWinkler
from pygraphc.pruning.TrianglePruning import TrianglePruning
import networkx as nx
class CreateGraphModel(object):
def __init__(self, log_file):
self.log_file = log_file
self.unique_events = []
self.unique_events_length = 0
self.distances = []
self.graph = nx.MultiGraph()
def __get_nodes(self):
pp = ParallelPreprocess(self.log_file)
self.unique_events = pp.get_unique_events()
self.unique_events_length = pp.unique_events_length
self.event_attributes = pp.event_attributes
def __get_distances(self):
jw = JaroWinkler(self.event_attributes, self.unique_events_length)
self.distances = jw.get_jarowinkler()
def create_graph(self):
self.__get_nodes()
self.__get_distances()
self.graph.add_nodes_from(self.unique_events)
self.graph.add_weighted_edges_from(self.distances)
tp = TrianglePruning(self.graph)
tp.get_triangle()
self.graph = tp.graph
return self.graph
|
Add debugging to update LED paths
|
package com.gmail.alexellingsen.g2skintweaks;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import de.robv.android.xposed.XposedBridge;
public class UpdateLedPaths extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final SettingsHelper settings = new SettingsHelper(context);
boolean shouldCache = !settings.getBoolean(Prefs.TURN_ON_SCREEN_NEW_SMS, true) &&
settings.getBoolean(Prefs.ENABLE_POWER_LED, true);
if (shouldCache) {
// Cache the path to backlights so it wont have to search for it.
final Context finalContext = context;
new Thread(new Runnable() {
@Override
public void run() {
RootFunctions.updatePowerLedPaths(finalContext);
if (settings.getBoolean(Prefs.ENABLE_DEBUGGING, false)) {
XposedBridge.log("Updated LED paths.");
}
}
}).start();
}
}
}
|
package com.gmail.alexellingsen.g2skintweaks;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class UpdateLedPaths extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SettingsHelper settings = new SettingsHelper(context);
boolean shouldCache = !settings.getBoolean(Prefs.TURN_ON_SCREEN_NEW_SMS, true) &&
settings.getBoolean(Prefs.ENABLE_POWER_LED, true);
if (shouldCache) {
// Cache the path to backlights so it wont have to search for it.
final Context finalContext = context;
new Thread(new Runnable() {
@Override
public void run() {
RootFunctions.updatePowerLedPaths(finalContext);
}
}).start();
}
}
}
|
Revert local CDN location set by Jodok
|
# -*- coding: utf-8 -*-
# vim: set fileencodings=utf-8
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
CDN_URL = 'https://cdn.crate.io'
def media(context, media_url):
"""
Get the path for a media file.
"""
if media_url.startswith('http://') or media_url.startswith('https://'):
url = media_url
elif media_url.startswith('/'):
url = u'{0}{1}'.format(CDN_URL, media_url)
else:
url = u'{0}/media/{1}'.format(CDN_URL, media_url)
return url
register.simple_tag(takes_context=True)(media)
|
# -*- coding: utf-8 -*-
# vim: set fileencodings=utf-8
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
#CDN_URL = 'https://cdn.crate.io'
CDN_URL = 'http://localhost:8001'
def media(context, media_url):
"""
Get the path for a media file.
"""
if media_url.startswith('http://') or media_url.startswith('https://'):
url = media_url
elif media_url.startswith('/'):
url = u'{0}{1}'.format(CDN_URL, media_url)
else:
url = u'{0}/media/{1}'.format(CDN_URL, media_url)
return url
register.simple_tag(takes_context=True)(media)
|
Add timestamps column to database migration.
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use App\Realms\Server;
class CreateServersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('servers', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('address');
$table->string('state')->default(Server::STATE_OPEN);
$table->integer('days_left')->default(365);
$table->boolean('expired')->default(false);
$table->json('invited_players')->default('[]');
$table->json('operators')->default('[]');
$table->boolean('minigames_server')->default(false);
$table->string('motd')->default('A Minecraft Realm');
$table->string('owner');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('servers');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use App\Realms\Server;
class CreateServersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('servers', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('address');
$table->string('state')->default(Server::STATE_OPEN);
$table->integer('days_left')->default(365);
$table->boolean('expired')->default(false);
$table->json('invited_players')->default('[]');
$table->json('operators')->default('[]');
$table->boolean('minigames_server')->default(false);
$table->string('motd')->default('A Minecraft Realm');
$table->string('owner');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('servers');
}
}
|
Make sure that we are connected to the cluster
|
<?php
namespace ActiveCollab\Resistance\Test;
use ActiveCollab\Resistance;
/**
* @package ActiveCollab\Resistance\Test
*/
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* Switch to test database
*/
public function setUp()
{
if (getenv('TEST_REDIS_CLUSTER')) {
print "Resistance: Connecting to Redis Cluster...\n";
Resistance::connectToCluster([ '127.0.0.1:30001', '127.0.0.1:30002', '127.0.0.1:30003', '127.0.0.1:30004', '127.0.0.1:30005' ]);
} else {
print "Resistance: Connecting to Standalone Redis...\n";
Resistance::connect();
}
Resistance::reset();
}
/**
* Tear down test database
*/
public function tearDown()
{
Resistance::reset();
}
}
|
<?php
namespace ActiveCollab\Resistance\Test;
use ActiveCollab\Resistance;
/**
* @package ActiveCollab\Resistance\Test
*/
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* Switch to test database
*/
public function setUp()
{
if (getenv('TEST_REDIS_CLUSTER')) {
Resistance::connectToCluster([ '127.0.0.1:30001', '127.0.0.1:30002', '127.0.0.1:30003', '127.0.0.1:30004', '127.0.0.1:30005' ]);
} else {
Resistance::connect();
}
Resistance::reset();
}
/**
* Tear down test database
*/
public function tearDown()
{
Resistance::reset();
}
}
|
Set indexKey once per row, not per column.
The performance improvement depends on the number of columns, but on a
real data set of 5000 rows and 11 resolved columns this improves
performance by 8.7%.
This does not change the result since the order of keys in the spread is
unchanged.
|
function resolve({
columns,
method = () => rowData => rowData,
indexKey = '_index'
}) {
if (!columns) {
throw new Error('resolve - Missing columns!');
}
return (rows = []) => {
const methodsByColumnIndex = columns.map(column => method({ column }));
return rows.map((rowData, rowIndex) => {
let ret = {
[indexKey]: rowIndex,
...rowData
};
columns.forEach((column, columnIndex) => {
const result = methodsByColumnIndex[columnIndex](rowData);
delete result.undefined;
ret = {
...ret,
...result
};
});
return ret;
});
};
}
export default resolve;
|
function resolve({
columns,
method = () => rowData => rowData,
indexKey = '_index'
}) {
if (!columns) {
throw new Error('resolve - Missing columns!');
}
return (rows = []) => {
const methodsByColumnIndex = columns.map(column => method({ column }));
return rows.map((rowData, rowIndex) => {
let ret = {};
columns.forEach((column, columnIndex) => {
const result = methodsByColumnIndex[columnIndex](rowData);
delete result.undefined;
ret = {
[indexKey]: rowIndex,
...rowData,
...ret,
...result
};
});
return ret;
});
};
}
export default resolve;
|
Fix typo in table name
|
package org.ligoj.app.plugin.prov.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.ligoj.app.api.NodeScoped;
import org.ligoj.app.model.Node;
import org.ligoj.bootstrap.core.model.AbstractDescribedEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
/**
* An instance price configuration
*/
@Getter
@Setter
@Entity
@Table(name = "LIGOJ_PROV_INSTANCE_PRICE_TYPE", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "node" }))
public class ProvInstancePriceType extends AbstractDescribedEntity<Integer> implements NodeScoped {
/**
* SID
*/
private static final long serialVersionUID = 4795855466011388616L;
/**
* Billing period in minutes. Any started period is due.
*/
@NotNull
private Integer period;
/**
* The related node (VM provider) of this instance.
*/
@NotNull
@ManyToOne(fetch=FetchType.LAZY)
@JsonIgnore
private Node node;
}
|
package org.ligoj.app.plugin.prov.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.ligoj.app.api.NodeScoped;
import org.ligoj.app.model.Node;
import org.ligoj.bootstrap.core.model.AbstractDescribedEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
/**
* An instance price configuration
*/
@Getter
@Setter
@Entity
@Table(name = "LIGOJ_PROV_INSTACE_PRICE_TYPE", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "node" }))
public class ProvInstancePriceType extends AbstractDescribedEntity<Integer> implements NodeScoped {
/**
* SID
*/
private static final long serialVersionUID = 4795855466011388616L;
/**
* Billing period in minutes. Any started period is due.
*/
@NotNull
private Integer period;
/**
* The related node (VM provider) of this instance.
*/
@NotNull
@ManyToOne(fetch=FetchType.LAZY)
@JsonIgnore
private Node node;
}
|
Use six.moves to reference `reload`.
PiperOrigin-RevId: 253199825
Change-Id: Ifb9bf182572900a813ea1b0dbbda60f82495eac1
|
# Copyright 2019 The Sonnet Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for Sonnet's public API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import reload_module as reload
import sonnet as snt
from sonnet.src import test_utils
import tensorflow as tf
class PublicSymbolsTest(test_utils.TestCase):
def test_src_not_exported(self):
self.assertFalse(hasattr(snt, "src"))
def test_supports_reload(self):
mysnt = snt
for _ in range(2):
mysnt = reload(mysnt)
self.assertFalse(hasattr(mysnt, "src"))
if __name__ == "__main__":
# tf.enable_v2_behavior()
tf.test.main()
|
# Copyright 2019 The Sonnet Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for Sonnet's public API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import importlib
import six
import sonnet as snt
from sonnet.src import test_utils
import tensorflow as tf
class PublicSymbolsTest(test_utils.TestCase):
def test_src_not_exported(self):
self.assertFalse(hasattr(snt, "src"))
def test_supports_reload(self):
mysnt = snt
for _ in range(2):
if six.PY2:
mysnt = reload(mysnt)
else:
mysnt = importlib.reload(mysnt)
self.assertFalse(hasattr(mysnt, "src"))
if __name__ == "__main__":
# tf.enable_v2_behavior()
tf.test.main()
|
Swap from letters int to packages object
|
class Player extends Phaser.Sprite {
constructor (game, city, saved) {
super(game, city.x, city.y, 'city')
this.game.add.existing(this)
this.tint = 0x006600
this.name = 'Dumb Name'
this.city = city
this.stats = {
health: 50,
carryingCapacity: 20
}
this.health = 48
this.packages = [ new Package() ]
this.money = 500
if ( typeof saved !== 'undefined' ) { //we need to load saved player attrs
this.name = saved.name;
this.stats = saved.stats;
this.health = saved.health;
this.letters = saved.letters;
this.money = saved.letters;
}
}
dumps() {
return {
name: this.name,
stats: this.stats,
health: this.health,
letters: this.letters,
money: this.money
};
}
}
|
class Player extends Phaser.Sprite {
constructor (game, city, saved) {
super(game, city.x, city.y, 'city')
this.game.add.existing(this)
this.tint = 0x006600
this.name = 'Dumb Name'
this.city = city
this.stats = {
health: 50,
carryingCapacity: 20
}
this.health = 48
this.letters = 3
this.money = 500
if ( typeof saved !== 'undefined' ) { //we need to load saved player attrs
this.name = saved.name;
this.stats = saved.stats;
this.health = saved.health;
this.letters = saved.letters;
this.money = saved.letters;
}
}
dumps() {
return {
name: this.name,
stats: this.stats,
health: this.health,
letters: this.letters,
money: this.money
};
}
}
|
Use attrs<19.2.0 to avoid pytest error
|
import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
'attrs<19.2.0', # pytest does not run with attrs==19.2.0 (https://github.com/pytest-dev/pytest/issues/3280) # NOQA
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='fujita@preferred.jp',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
|
import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='fujita@preferred.jp',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
|
Reduce oauth api-delay to 1s.
|
import praw
from images_of import settings
class Reddit(praw.Reddit):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config.api_request_delay = 1.0
def oauth(self, **kwargs):
self.set_oauth_app_info(
client_id = kwargs.get('client_id') or settings.CLIENT_ID,
client_secret = kwargs.get('client_secret') or settings.CLIENT_SECRET,
redirect_uri = kwargs.get('redirect_uri') or settings.REDIRECT_URI
)
self.refresh_access_information(
kwargs.get('refresh_token') or settings.REFRESH_TOKEN
)
def login(self, username=None, password=None):
# this is depricated, just ignore the warning.
self.config.api_request_delay = 2.0
super().login(
username or settings.USERNAME,
password or settings.PASSWORD,
disable_warning=True
)
|
import praw
from images_of import settings
class Reddit(praw.Reddit):
def oauth(self, **kwargs):
self.set_oauth_app_info(
client_id = kwargs.get('client_id') or settings.CLIENT_ID,
client_secret = kwargs.get('client_secret') or settings.CLIENT_SECRET,
redirect_uri = kwargs.get('redirect_uri') or settings.REDIRECT_URI
)
self.refresh_access_information(
kwargs.get('refresh_token') or settings.REFRESH_TOKEN
)
def login(self, username=None, password=None):
# this is depricated, just ignore the warning.
super().login(
username or settings.USERNAME,
password or settings.PASSWORD,
disable_warning=True
)
|
Fix get tokenized card infos
|
<?php
namespace Zoop\Lib;
class ZoopTokens implements \Zoop\Contracts\ZoopTokens {
/**
* API Resource
*
* @var object
*/
protected $APIResource;
/**
* ZoopTokens constructor.
* @param APIResource $APIResource
*/
public function __construct(APIResource $APIResource){
$this->APIResource = $APIResource;
}
/**
* @param array $post
* @return mixed
*/
public function tokenizeCard($post){
$api = 'cards/tokens';
return $this->APIResource->createAPI($api, $post);
}
/**
* @param array $post
* @return mixed
*/
public function tokenizeBankAccount($post){
$api = 'bank_accounts/tokens';
return $this->APIResource->createAPI($api, $post);
}
/**
* @param string $token
*/
public function get($token){
$api = 'tokens/' . $token;
return $this->APIResource->searchAPI($api);
}
}
|
<?php
namespace Zoop\Lib;
class ZoopTokens implements \Zoop\Contracts\ZoopTokens {
/**
* API Resource
*
* @var object
*/
protected $APIResource;
/**
* ZoopTokens constructor.
* @param APIResource $APIResource
*/
public function __construct(APIResource $APIResource){
$this->APIResource = $APIResource;
}
/**
* @param array $post
* @return mixed
*/
public function tokenizeCard($post){
$api = 'cards/tokens';
return $this->APIResource->createAPI($api, $post);
}
/**
* @param array $post
* @return mixed
*/
public function tokenizeBankAccount($post){
$api = 'bank_accounts/tokens';
return $this->APIResource->createAPI($api, $post);
}
/**
* @param string $token
*/
public function get($token){
$api = 'tokens' . $token;
$this->APIResource->searchAPI($api);
}
}
|
test: Test data was not used
|
package mireka.maildata;
import static org.junit.Assert.*;
import java.text.ParseException;
import org.junit.Test;
public class QEncodingParserTest extends QEncodingParser {
private String in1 = "hi";
private byte[] out1 = { 'h', 'i' };
private String in2 = "h=69_jon";
private byte[] out2 = { 'h', 'i', ' ', 'j', 'o', 'n' };
@Test
public void testSimple() throws ParseException {
QEncodingParser parser = new QEncodingParser();
byte[] result = parser.decode(in1);
assertArrayEquals(out1, result);
}
@Test
public void testComplex() throws ParseException {
QEncodingParser parser = new QEncodingParser();
byte[] result = parser.decode(in2);
assertArrayEquals(out2, result);
}
}
|
package mireka.maildata;
import static org.junit.Assert.*;
import java.text.ParseException;
import org.junit.Test;
public class QEncodingParserTest extends QEncodingParser {
private String in1 = "hi";
private byte[] out1 = { 'h', 'i' };
private String in2 = "h=69_jon";
private byte[] out2 = { 'h', 'i', ' ', 'j', 'o', 'n' };
@Test
public void testSimple() throws ParseException {
QEncodingParser parser = new QEncodingParser();
byte[] result = parser.decode(in1);
assertArrayEquals(out1, result);
}
@Test
public void testComplex() throws ParseException {
QEncodingParser parser = new QEncodingParser();
byte[] result = parser.decode(in1);
assertArrayEquals(out1, result);
}
}
|
Fix versione nel Frame della gui
|
/*
Copyright 2011-2015 Stefano Cappa
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 gui.kcomponent;
import gui.image.ImageLoader;
import javax.swing.JFrame;
import update.Version;
/**
* Classe che crea un JFrame personalizzato con icona, dimensione preferita, titolo,
* posizione e soprattutto lo sfondo, richiamando il PanelPersonalizzato.
*/
public class KFrame extends JFrame{
private static final long serialVersionUID = 6729366260424934194L;
private static final String NOME = "BYAManager - " + "0.5.6" + " - by Stefano Cappa";
public KFrame() {
setTitle(NOME);
setIconImage(ImageLoader.getInstance().getIconaBya());
getLayeredPane().setOpaque(false);
getRootPane().setOpaque(false);
this.setContentPane(new KPanel());
}
}
|
/*
Copyright 2011-2015 Stefano Cappa
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 gui.kcomponent;
import gui.image.ImageLoader;
import javax.swing.JFrame;
import update.Version;
/**
* Classe che crea un JFrame personalizzato con icona, dimensione preferita, titolo,
* posizione e soprattutto lo sfondo, richiamando il PanelPersonalizzato.
*/
public class KFrame extends JFrame{
private static final long serialVersionUID = 6729366260424934194L;
private static final String NOME = "BYAManager - " + Version.VERSION + " - by Stefano Cappa";
public KFrame() {
setTitle(NOME);
setIconImage(ImageLoader.getInstance().getIconaBya());
getLayeredPane().setOpaque(false);
getRootPane().setOpaque(false);
this.setContentPane(new KPanel());
}
}
|
Improve efficiency to constant O(n)
|
package algorithms;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(Integer[] numbers) {
if (numbers.length == 1) {
return 0;
}
Integer maxIndex1 = null;
Integer maxIndex2 = null;
for (int i = 0; i < numbers.length; ++i) {
if (maxIndex1 == null || numbers[i] > numbers[maxIndex1]) {
maxIndex2 = maxIndex1;
maxIndex1 = i;
} else if (maxIndex2 == null || numbers[i] > numbers[maxIndex2]) {
maxIndex2 = i;
}
}
return ((long) (numbers[maxIndex1])) * numbers[maxIndex2];
}
public static void main(String[] args) {
System.out.println(
"Type number to calculate the maximum pairwise product. "
+ "The first number is a total count of numbers.");
FastScanner scanner = new FastScanner(System.in);
int numberOfNumbers = scanner.popNextInt();
if (numberOfNumbers > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
}
Integer[] numbers = new Integer[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; i++) {
numbers[i] = scanner.popNextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
}
}
|
package algorithms;
import java.util.Arrays;
public class MaxPairwiseProduct {
static long getMaxPairwiseProduct(Integer[] numbers) {
if (numbers.length == 1) {
return 0;
}
Arrays.sort(numbers, (x, y) -> x - y);
int lastIndex = numbers.length - 1;
long bigResult = (long) numbers[lastIndex] * numbers[lastIndex - 1];
return bigResult;
}
public static void main(String[] args) {
System.out.println(
"Type number to calculate the maximum pairwise product. "
+ "The first number is a total count of numbers.");
FastScanner scanner = new FastScanner(System.in);
int numberOfNumbers = scanner.popNextInt();
if (numberOfNumbers > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
}
Integer[] numbers = new Integer[numberOfNumbers];
for (int i = 0; i < numberOfNumbers; i++) {
numbers[i] = scanner.popNextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
}
}
|
Change pokeapi url to use https
|
var PokeApi = PokeApi || {};
PokeApi.apiUrl = "https://pokeapi.co/api/";
PokeApi.apiVersion = "v2";
PokeApi.getResource = function getResource(resource) {
return new Promise(function(resolve, reject) {
fetch(PokeApi.apiUrl + PokeApi.apiVersion + "/" + resource).then(function(response) {
// handle HTTP response
if(response.ok){
response.json().then(function(responseJson){resolve(responseJson)});
} else{
reject(response.status + " " + response.statusText)
}
}, function(error) {
// handle network error
reject(error.message);
})
})
}
PokeApi.getBerry = function getBerry(id) {
return new Promise(function(resolve, reject) {
PokeApi.getResource("berry/" + id).then(function(response) {
resolve(response);
}).catch(function(error){
reject(error);
})
})
}
|
var PokeApi = PokeApi || {};
PokeApi.apiUrl = "http://pokeapi.co/api/";
PokeApi.apiVersion = "v2";
PokeApi.getResource = function getResource(resource) {
return new Promise(function(resolve, reject) {
fetch(PokeApi.apiUrl + PokeApi.apiVersion + "/" + resource).then(function(response) {
// handle HTTP response
if(response.ok){
response.json().then(function(responseJson){resolve(responseJson)});
} else{
reject(response.status + " " + response.statusText)
}
}, function(error) {
// handle network error
reject(error.message);
})
})
}
PokeApi.getBerry = function getBerry(id) {
return new Promise(function(resolve, reject) {
PokeApi.getResource("berry/" + id).then(function(response) {
resolve(response);
}).catch(function(error){
reject(error);
})
})
}
|
Tests/RN-native-nav: Use promise instead of callback for starting Bugsnag
|
/**
* @format
*/
import {Navigation} from 'react-native-navigation';
import HomeScreen from './screens/Home';
import DetailsScreen from './screens/Details';
import {NativeModules} from 'react-native';
import Bugsnag from '@bugsnag/react-native';
import BugsnagReactNativeNavigation from '@bugsnag/plugin-react-native-navigation';
NativeModules.BugsnagTestInterface.startBugsnag({
apiKey: '12312312312312312312312312312312',
endpoint: 'http://bs-local.com:9339',
autoTrackSessions: false
}).then(() => {
Bugsnag.start({
plugins: [new BugsnagReactNativeNavigation(Navigation)],
})
})
Navigation.registerComponent('Home', () => HomeScreen);
Navigation.registerComponent('Details', () => DetailsScreen);
Navigation.events().registerAppLaunchedListener(async () => {
Navigation.setRoot({
root: {
stack: {
children: [
{
component: {
name: 'Home',
},
},
],
},
},
})
})
|
/**
* @format
*/
import {Navigation} from 'react-native-navigation';
import HomeScreen from './screens/Home';
import DetailsScreen from './screens/Details';
import {NativeModules} from 'react-native';
import Bugsnag from '@bugsnag/react-native';
import BugsnagReactNativeNavigation from '@bugsnag/plugin-react-native-navigation';
NativeModules.BugsnagTestInterface.startBugsnag({
apiKey: '12312312312312312312312312312312',
endpoint: 'http://bs-local.com:9339',
autoTrackSessions: false
}, () => {
Bugsnag.start({
plugins: [new BugsnagReactNativeNavigation(Navigation)],
})
})
Navigation.registerComponent('Home', () => HomeScreen);
Navigation.registerComponent('Details', () => DetailsScreen);
Navigation.events().registerAppLaunchedListener(async () => {
Navigation.setRoot({
root: {
stack: {
children: [
{
component: {
name: 'Home',
},
},
],
},
},
})
})
|
Use list comprehension instead of lambda function
|
try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
|
try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
|
Exclude test suite from jsdoc
|
include('helma/webapp/response');
include('helma/jsdoc');
require('core/array');
var log = require('helma/logging').getLogger(module.id);
exports.index = function index(req, module) {
var repo = new ScriptRepository(require.paths.peek());
if (module && module != "/") {
var res = repo.getScriptResource(module);
var jsdoc = parseResource(res);
// log.info("export()ed symbols: " + exported);
return new SkinnedResponse(getResource('./skins/module.html'), {
title: "Module " + res.moduleName,
jsdoc: jsdoc
});
} else {
var modules = repo.getScriptResources(true).filter(function(r) {
return r.relativePath.indexOf('test') != 0;
}).sort(function(a, b) {
return a.relativePath > b.relativePath ? 1 : -1;
});
return new SkinnedResponse(getResource('./skins/index.html'), {
title: "API Documentation",
modules: modules
});
}
}
|
include('helma/webapp/response');
include('helma/jsdoc');
require('core/array');
var log = require('helma/logging').getLogger(module.id);
exports.index = function index(req, module) {
var repo = new ScriptRepository(require.paths.peek());
if (module && module != "/") {
var res = repo.getScriptResource(module);
var jsdoc = parseResource(res);
// log.info("export()ed symbols: " + exported);
return new SkinnedResponse(getResource('./skins/module.html'), {
title: "Module " + res.moduleName,
jsdoc: jsdoc
});
} else {
var modules = repo.getScriptResources(true).sort(function(a, b) {
return a.relativePath > b.relativePath ? 1 : -1;
});
return new SkinnedResponse(getResource('./skins/index.html'), {
title: "API Documentation",
modules: modules
});
}
}
|
Modify one of the indexes on the appointments table.
|
<?php
class Create_Appointments_Table {
/**
* Make changes to the database.
*
* @return void
*/
public function up()
{
//
Schema::table('appointments', function($table)
{
$table->create();
$table->increments('id');
$table->string('name')->nullable();
$table->integer('place_id')->unsigned()->nullable();
$table->integer('a_date_ts')->unsigned();
$table->string('added_by', 50);
$table->string('tweet', 140);
$table->string('tweet_id', 64);
$table->text('link')->nullable();
$table->blob('votes')->nullable();
$table->tinyint('enabled')->default(1);
$table->timestamps();
$table->index(array('a_date_ts', 'name', 'enabled'));
$table->index(array('updated_at', 'enabled'));
$table->index('place_id');
$table->foreign('place_id')->references('id')->on('places');
$table->engine = 'InnoDB';
});
}
/**
* Revert the changes to the database.
*
* @return void
*/
public function down()
{
//
Schema::drop('appointments');
}
}
|
<?php
class Create_Appointments_Table {
/**
* Make changes to the database.
*
* @return void
*/
public function up()
{
//
Schema::table('appointments', function($table)
{
$table->create();
$table->increments('id');
$table->string('name')->nullable();
$table->integer('place_id')->unsigned()->nullable();
$table->integer('a_date_ts')->unsigned();
$table->string('added_by', 50);
$table->string('tweet', 140);
$table->string('tweet_id', 64);
$table->text('link')->nullable();
$table->blob('votes')->nullable();
$table->tinyint('enabled')->default(1);
$table->timestamps();
$table->index(array('a_date_ts', 'enabled'));
$table->index(array('updated_at', 'enabled'));
$table->index('place_id');
$table->foreign('place_id')->references('id')->on('places');
$table->engine = 'InnoDB';
});
}
/**
* Revert the changes to the database.
*
* @return void
*/
public function down()
{
//
Schema::drop('appointments');
}
}
|
Remove usage of deprecated class.
|
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
*/
package org.jenetics.util;
import io.jenetics.prngine.Random64;
/**
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
*/
public class ContinuousRandom extends Random64 {
private long _next;
public ContinuousRandom(final long start) {
_next = start;
}
@Override
public long nextLong() {
return _next++;
}
@Override
public int nextInt() {
return (int)nextLong();
}
}
|
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
*/
package org.jenetics.util;
/**
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
*/
public class ContinuousRandom extends Random64 {
private long _next;
public ContinuousRandom(final long start) {
_next = start;
}
@Override
public long nextLong() {
return _next++;
}
@Override
public int nextInt() {
return (int)nextLong();
}
}
|
Send alert ID to UI
This will allow alert detail page links on the alert list page to work again.
|
import { Paginator } from '../../utils';
import template from './alerts-list.html';
const stateClass = {
ok: 'label label-success',
triggered: 'label label-danger',
unknown: 'label label-warning',
};
class AlertsListCtrl {
constructor(Events, Alert) {
Events.record('view', 'page', 'alerts');
this.alerts = new Paginator([], { itemsPerPage: 20 });
Alert.query((alerts) => {
this.alerts.updateRows(alerts.map(alert => ({
id: alert.id,
name: alert.name,
state: alert.state,
class: stateClass[alert.state],
created_by: alert.user.name,
created_at: alert.created_at,
updated_at: alert.updated_at,
})));
});
}
}
export default function (ngModule) {
ngModule.component('alertsListPage', {
template,
controller: AlertsListCtrl,
});
return {
'/alerts': {
template: '<alerts-list-page></alerts-list-page>',
title: 'Alerts',
},
};
}
|
import { Paginator } from '../../utils';
import template from './alerts-list.html';
const stateClass = {
ok: 'label label-success',
triggered: 'label label-danger',
unknown: 'label label-warning',
};
class AlertsListCtrl {
constructor(Events, Alert) {
Events.record('view', 'page', 'alerts');
this.alerts = new Paginator([], { itemsPerPage: 20 });
Alert.query((alerts) => {
this.alerts.updateRows(alerts.map(alert => ({
name: alert.name,
state: alert.state,
class: stateClass[alert.state],
created_by: alert.user.name,
created_at: alert.created_at,
updated_at: alert.updated_at,
})));
});
}
}
export default function (ngModule) {
ngModule.component('alertsListPage', {
template,
controller: AlertsListCtrl,
});
return {
'/alerts': {
template: '<alerts-list-page></alerts-list-page>',
title: 'Alerts',
},
};
}
|
Check metalanguage applicability in getAllBaseLanguageIdsWithAny()
GitOrigin-RevId: f76645e6ba0672f74059aa8b4ec97855d6a5527c
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.completion;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageExtension;
import com.intellij.lang.MetaLanguage;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
class CompletionExtension<T> extends LanguageExtension<T> {
CompletionExtension(String epName) {
super(epName);
}
@NotNull
@Override
protected List<T> buildExtensions(@NotNull String stringKey, @NotNull Language key) {
return buildExtensions(getAllBaseLanguageIdsWithAny(key));
}
@NotNull
private Set<String> getAllBaseLanguageIdsWithAny(@NotNull Language key) {
Set<String> allowed = new THashSet<>();
while (key != null) {
allowed.add(keyToString(key));
for (MetaLanguage metaLanguage : MetaLanguage.all()) {
if (metaLanguage.matchesLanguage(key))
allowed.add(metaLanguage.getID());
}
key = key.getBaseLanguage();
}
allowed.add("any");
return allowed;
}
}
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.completion;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageExtension;
import com.intellij.lang.MetaLanguage;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
class CompletionExtension<T> extends LanguageExtension<T> {
CompletionExtension(String epName) {
super(epName);
}
@NotNull
@Override
protected List<T> buildExtensions(@NotNull String stringKey, @NotNull Language key) {
return buildExtensions(getAllBaseLanguageIdsWithAny(key));
}
@NotNull
private Set<String> getAllBaseLanguageIdsWithAny(@NotNull Language key) {
Set<String> allowed = new THashSet<>();
while (key != null) {
allowed.add(keyToString(key));
key = key.getBaseLanguage();
}
allowed.add("any");
for (MetaLanguage metaLanguage : MetaLanguage.all()) {
allowed.add(metaLanguage.getID());
}
return allowed;
}
}
|
Add dossier title to API
|
from rest_framework import serializers, viewsets
from document.models import Document, Kamerstuk, Dossier
class DossierSerializer(serializers.HyperlinkedModelSerializer):
documents = serializers.HyperlinkedRelatedField(read_only=True,
view_name='document-detail',
many=True)
class Meta:
model = Dossier
fields = ('id', 'dossier_id', 'title', 'documents')
class DossierViewSet(viewsets.ModelViewSet):
queryset = Dossier.objects.all()
serializer_class = DossierSerializer
class DocumentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Document
fields = ('id', 'dossier', 'raw_type', 'raw_title', 'publisher', 'date_published', 'document_url')
class DocumentViewSet(viewsets.ModelViewSet):
queryset = Document.objects.all()
serializer_class = DocumentSerializer
class KamerstukSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Kamerstuk
fields = ('id', 'document', 'id_main', 'id_sub', 'type_short', 'type_long')
class KamerstukViewSet(viewsets.ModelViewSet):
queryset = Kamerstuk.objects.all()
serializer_class = KamerstukSerializer
|
from rest_framework import serializers, viewsets
from document.models import Document, Kamerstuk, Dossier
class DossierSerializer(serializers.HyperlinkedModelSerializer):
documents = serializers.HyperlinkedRelatedField(read_only=True,
view_name='document-detail',
many=True)
class Meta:
model = Dossier
fields = ('id', 'dossier_id', 'documents')
class DossierViewSet(viewsets.ModelViewSet):
queryset = Dossier.objects.all()
serializer_class = DossierSerializer
class DocumentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Document
fields = ('id', 'dossier', 'raw_type', 'raw_title', 'publisher', 'date_published', 'document_url')
class DocumentViewSet(viewsets.ModelViewSet):
queryset = Document.objects.all()
serializer_class = DocumentSerializer
class KamerstukSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Kamerstuk
fields = ('id', 'document', 'id_main', 'id_sub', 'type_short', 'type_long')
class KamerstukViewSet(viewsets.ModelViewSet):
queryset = Kamerstuk.objects.all()
serializer_class = KamerstukSerializer
|
Add check for all states
|
const resources_template = require("./templates/resources-simple.hbs");
/* parallax on blog posts with cover image */
var parallaxImage = document.getElementById('ParallaxImage');
var windowScrolled;
window.addEventListener('scroll', function windowScroll() {
windowScrolled = window.pageYOffset || document.documentElement.scrollTop;
parallaxImage.style.transform = 'translate3d(0, ' + windowScrolled / 4 + 'px, 0)';
});
axios.get('/assets/json/get-involved.json')
.then(function (response) {
resources(response.data);
})
.catch(function (error) {
// call local file on 403
console.log(error);
});
function resources(data=[]) {
const resource_element = document.getElementById("resources");
const resource_list = data
.filter(resource => (resource.states.includes(resource_element.dataset.state) || resource.states.includes('All')) && (resource.types.includes(resource_element.dataset.type)))
.map(function(r) { return {'title': r.name, 'url': r.url, 'desc': r.desc.split(" ").slice(0,8).join(" ") }; });
resource_element.innerHTML = resources_template(resource_list);
}
|
const resources_template = require("./templates/resources-simple.hbs");
/* parallax on blog posts with cover image */
var parallaxImage = document.getElementById('ParallaxImage');
var windowScrolled;
window.addEventListener('scroll', function windowScroll() {
windowScrolled = window.pageYOffset || document.documentElement.scrollTop;
parallaxImage.style.transform = 'translate3d(0, ' + windowScrolled / 4 + 'px, 0)';
});
axios.get('/assets/json/get-involved.json')
.then(function (response) {
resources(response.data);
})
.catch(function (error) {
// call local file on 403
console.log(error);
});
function resources(data=[]) {
const resource_element = document.getElementById("resources");
const resource_list = data
.filter(resource => (resource.states.includes(resource_element.dataset.state)) && (resource.types.includes(resource_element.dataset.type)))
.map(function(r) { return {'title': r.name, 'url': r.url, 'desc': r.desc.split(" ").slice(0,8).join(" ") }; });
resource_element.innerHTML = resources_template(resource_list);
}
|
Fix default newtab; optimize process to make page active
|
function nt (newtab) {
function waitForURL(tabId, changeInfo, tab) {
if (changeInfo.title === '@NewTab') {
browser.storage.local.get('newtaburl').then(function (ntu) {
browser.tabs.onUpdated.removeListener(waitForURL);
if (ntu.newtaburl == null) {
browser.storage.local.set({
newtaburl: 'about:blank'
});
ntu.newtaburl = 'about:blank';
}
browser.storage.local.get('active').then(function (act) {
if (act.active) {
browser.tabs.create({
'url': ntu.newtaburl
});
browser.tabs.remove(newtab.id);
} else {
browser.tabs.update(tabId, {
'url': ntu.newtaburl
});
}
});
});
}
browser.tabs.onUpdated.removeListener(waitForURL);
}
browser.tabs.onUpdated.addListener(waitForURL);
}
browser.tabs.onCreated.addListener(nt);
|
function nt (newtab) {
function waitForURL(tabId, changeInfo, tab) {
console.log(changeInfo);
if (changeInfo.title === '@NewTab') {
browser.storage.local.get('newtaburl').then(function (ntu) {
browser.tabs.onUpdated.removeListener(waitForURL);
browser.storage.local.get('active').then(function (act) {
if (act.active) {
browser.tabs.remove(newtab.id);
browser.tabs.create({
'url': ntu.newtaburl
})
} else {
browser.tabs.update(tabId, {
'url': ntu.newtaburl
});
}
});
});
}
browser.tabs.onUpdated.removeListener(waitForURL);
}
browser.tabs.onUpdated.addListener(waitForURL);
}
browser.tabs.onCreated.addListener(nt);
|
Add python script for IPs discovery
|
#!/usr/bin/python
#
# Get private IPv4s for a given instance name.
#
import boto
import boto.ec2
import getopt
import sys
#
# Get the profile
#
def connect():
metadata = boto.utils.get_instance_metadata()
region = metadata['placement']['availability-zone'][:-1]
profile = metadata['iam']['info']['InstanceProfileArn']
profile = profile[profile.find('/') + 1:]
conn = boto.ec2.connection.EC2Connection(
region=boto.ec2.get_region(region),
aws_access_key_id=metadata['iam']['security-credentials'][profile]['AccessKeyId'],
aws_secret_access_key=metadata['iam']['security-credentials'][profile]['SecretAccessKey'],
security_token=metadata['iam']['security-credentials'][profile]['Token']
)
return conn
#
# Print out private IPv4
#
def print_ips(tag_name):
conn = connect()
reservations = conn.get_all_instances(filters={"tag:Name": tag_name})
print("%s" % (reservations[0]["Instances"][0]["PrivateIpAddress"]))
#
# Main
#
opts, args = getopt.getopt(sys.argv[1:], "Lt:r:", ["tag-name", "region"])
tag_name = ""
region = ""
for opt, arg in opts:
if opt in ("-t", "--tag-name"):
tag_name = arg
print_ips(tag_name)
|
#!/usr/bin/python
#
# Get private IPv4s for a given instance name.
#
import boto
import boto.ec2
import getopt
import sys
#
# Get the profile
#
def connect(region):
profile = metadata['iam']['info']['InstanceProfileArn']
profile = profile[profile.find('/') + 1:]
conn = boto.ec2.connection.EC2Connection(
region=boto.ec2.get_region(region),
aws_access_key_id=metadata['iam']['security-credentials'][profile]['AccessKeyId'],
aws_secret_access_key=metadata['iam']['security-credentials'][profile]['SecretAccessKey'],
security_token=metadata['iam']['security-credentials'][profile]['Token']
)
return conn
#
# Print out private IPv4
#
def print_ips(region, tag_name):
conn = connect(region)
reservations = conn.get_all_instances(filters={"tag:Name": tag_name})
print("%s" % (reservations[0]["Instances"][0]["PrivateIpAddress"]))
#
# Main
#
opts, args = getopt.getopt(sys.argv[1:], "Lt:r:", ["tag-name", "region"])
for opt, arg in opts:
if opt in ("-t", "--tag-name"):
tag_name = arg
elif opt in ("-r", "--region"):
region = arg
print_ips(region, tag_name)
|
Improve error message and use correct status
|
var basicAuth = require('basic-auth');
/**
* Simple basic auth middleware for use with Express 4.x.
*
* Based on template found at: http://www.danielstjules.com/2014/08/03/basic-auth-with-express-4/
*
* @example
* app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
*
* @param {string} username Expected username
* @param {string} password Expected password
* @returns {function} Express 4 middleware requiring the given credentials
*/
exports.basicAuth = function(username, password) {
return function(req, res, next) {
if (!username || !password) {
console.log('Username or password is not set.');
return res.send('<h1>Error:</h1><p>Username or password not set. <a href="https://github.com/alphagov/govuk_prototype_kit/blob/master/docs/deploying.md#3-set-a-username-and-password">See guidance for setting these</a>.</p>');
}
var user = basicAuth(req);
if (!user || user.name !== username || user.pass !== password) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
}
next();
};
};
|
var basicAuth = require('basic-auth');
/**
* Simple basic auth middleware for use with Express 4.x.
*
* Based on template found at: http://www.danielstjules.com/2014/08/03/basic-auth-with-express-4/
*
* @example
* app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
*
* @param {string} username Expected username
* @param {string} password Expected password
* @returns {function} Express 4 middleware requiring the given credentials
*/
exports.basicAuth = function(username, password) {
return function(req, res, next) {
if (!username || !password) {
console.log('Username or password is not set.');
return res.send('Error: username or password not set. <a href="https://github.com/alphagov/govuk_prototype_kit/blob/master/docs/deploying.md#3-set-a-username-and-password">See guidance for setting these</a>.');
}
var user = basicAuth(req);
if (!user || user.name !== username || user.pass !== password) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
}
next();
};
};
|
Add login to browsable API.
|
from django.conf.urls import include, url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^notes/$', views.NoteList.as_view()),
url(r'^notes/(?P<pk>[0-9]+)/$', views.NoteDetail.as_view()),
url(r'^traits/$', views.TraitList.as_view()),
url(r'^traits/(?P<pk>[0-9]+)/$', views.TraitDetail.as_view()),
url(r'^wines/$', views.WineList.as_view()),
url(r'^wines/(?P<pk>[0-9]+)/$', views.WineDetail.as_view()),
url(r'^wineries/$', views.WineryList.as_view()),
url(r'^wineries/(?P<pk>[0-9]+)/$', views.WineryDetail.as_view()),
url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
|
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
url(r'^notes/$', views.NoteList.as_view()),
url(r'^notes/(?P<pk>[0-9]+)/$', views.NoteDetail.as_view()),
url(r'^traits/$', views.TraitList.as_view()),
url(r'^traits/(?P<pk>[0-9]+)/$', views.TraitDetail.as_view()),
url(r'^wines/$', views.WineList.as_view()),
url(r'^wines/(?P<pk>[0-9]+)/$', views.WineDetail.as_view()),
url(r'^wineries/$', views.WineryList.as_view()),
url(r'^wineries/(?P<pk>[0-9]+)/$', views.WineryDetail.as_view()),
url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
|
Handle undefined sails.config.globals by using defaults.
|
/**
* Module dependencies.
*/
var _ = require('lodash');
var async = require('async');
/**
* exposeGlobals()
*
* Expose certain global variables
* (if config says so)
*
* @api private
*/
module.exports = function exposeGlobals() {
var sails = this;
sails.log.verbose('Exposing global variables... (you can disable this by modifying the properties in `sails.config.globals`)');
// Globals explicitly disabled
if (sails.config.globals === false) {
return;
}
sails.config.globals = sails.config.globals || {};
// Provide global access (if allowed in config)
if (sails.config.globals._) {
global['_'] = _;
}
if (sails.config.globals.async !== false) {
global['async'] = async;
}
if (sails.config.globals.sails !== false) {
global['sails'] = sails;
}
// `services` hook takes care of globalizing services (if enabled)
// `orm` hook takes care of globalizing models and adapters (if enabled)
};
|
/**
* Module dependencies.
*/
var _ = require('lodash');
var async = require('async');
/**
* exposeGlobals()
*
* Expose certain global variables
* (if config says so)
*
* @api private
*/
module.exports = function exposeGlobals() {
var sails = this;
sails.log.verbose('Exposing global variables... (you can disable this by modifying the properties in `sails.config.globals`)');
// Globals explicitly disabled
if (!sails.config.globals) {
return;
}
// Provide global access (if allowed in config)
if (sails.config.globals._) {
global['_'] = _;
}
if (sails.config.globals.async !== false) {
global['async'] = async;
}
if (sails.config.globals.sails !== false) {
global['sails'] = sails;
}
// `services` hook takes care of globalizing services (if enabled)
// `orm` hook takes care of globalizing models and adapters (if enabled)
};
|
Hide facet if no filters are still inactive inside
|
import React, { Component } from 'react'
import Facet from './Facet'
import { isActive } from '../../helpers/manageFilters'
const styles = {
type: {
textTransform: 'capitalize',
fontSize: '1em',
fontWeight: 400,
marginBottom: '1em',
},
group: {
marginBottom: '1em',
}
}
class FacetsGroup extends Component {
render() {
const { type, facets, filters, addFilter } = this.props
const activeMap = facets.map(facet => isActive(filters, {name: type, value: facet.value}))
if (activeMap.indexOf(false) === -1) {
return null;
}
return (
<div style={styles.group}>
<h4 style={styles.type}>{type}</h4>
{facets.map((facet, idx) => <Facet
key={idx}
name={type}
value={facet.value}
count={facet.count}
isActive={activeMap[idx]}
addFilter={addFilter} />)}
</div>
)
}
}
export default FacetsGroup
|
import React, { Component } from 'react'
import Facet from './Facet'
import { isActive } from '../../helpers/manageFilters'
const styles = {
type: {
textTransform: 'capitalize',
fontSize: '1em',
fontWeight: 400,
marginBottom: '1em',
},
group: {
marginBottom: '1em',
}
}
class FacetsGroup extends Component {
render() {
const { type, facets, filters, addFilter } = this.props
return (
<div style={styles.group}>
<h4 style={styles.type}>{type}</h4>
{facets.map((facet, idx) => <Facet
key={idx}
name={type}
value={facet.value}
count={facet.count}
isActive={isActive(filters, {name: type, value: facet.value})}
addFilter={addFilter} />)}
</div>
)
}
}
export default FacetsGroup
|
Support colours for rendering the layer view
|
from UM.View.View import View
from UM.View.Renderer import Renderer
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
from UM.Resources import Resources
class LayerView(View):
def __init__(self):
super().__init__()
self._material = None
def beginRendering(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
if not self._material:
self._material = renderer.createMaterial(Resources.getPath(Resources.ShadersLocation, 'basic.vert'), Resources.getPath(Resources.ShadersLocation, 'vertexcolor.frag'))
self._material.setUniformValue("u_color", [1.0, 0.0, 0.0, 1.0])
for node in DepthFirstIterator(scene.getRoot()):
if not node.render(renderer):
if node.getMeshData() and node.isVisible():
try:
layerData = node.getMeshData().layerData
except AttributeError:
continue
renderer.queueNode(node, mesh = layerData, material = self._material, mode = Renderer.RenderLines)
def endRendering(self):
pass
|
from UM.View.View import View
from UM.View.Renderer import Renderer
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
from UM.Resources import Resources
class LayerView(View):
def __init__(self):
super().__init__()
self._material = None
def beginRendering(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
if not self._material:
self._material = renderer.createMaterial(Resources.getPath(Resources.ShadersLocation, 'basic.vert'), Resources.getPath(Resources.ShadersLocation, 'color.frag'))
self._material.setUniformValue("u_color", [1.0, 0.0, 0.0, 1.0])
for node in DepthFirstIterator(scene.getRoot()):
if not node.render(renderer):
if node.getMeshData() and node.isVisible():
try:
layerData = node.getMeshData().layerData
except AttributeError:
continue
renderer.queueNode(node, mesh = layerData, material = self._material, mode = Renderer.RenderLineLoop)
def endRendering(self):
pass
|
Add trailing newline since PyCharm stripped it
|
#!/usr/bin/env python
import setuptools
import os
setuptools.setup(
name='endpoints-proto-datastore',
version='0.9.0',
description='Google Cloud Endpoints Proto Datastore Library',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
url='https://github.com/GoogleCloudPlatform/endpoints-proto-datastore',
license='Apache',
author='Danny Hermes',
author_email='daniel.j.hermes@gmail.com',
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python'
],
packages=setuptools.find_packages(exclude=['examples*', 'docs*']),
)
|
#!/usr/bin/env python
import setuptools
import os
setuptools.setup(
name='endpoints-proto-datastore',
version='0.9.0',
description='Google Cloud Endpoints Proto Datastore Library',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
url='https://github.com/GoogleCloudPlatform/endpoints-proto-datastore',
license='Apache',
author='Danny Hermes',
author_email='daniel.j.hermes@gmail.com',
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python'
],
packages=setuptools.find_packages(exclude=['examples*', 'docs*']),
)
|
Include credentials when entity search request is sent
|
import fetch from 'isomorphic-fetch'
export const REQUEST_ENTITIES = 'REQUEST_ENTITIES'
export const RECEIVE_ENTITIES = 'RECEIVE_ENTITIES'
function requestEntities() {
return {
type: REQUEST_ENTITIES
}
}
function receiveEntities(json) {
return {
type: RECEIVE_ENTITIES,
data: json.data,
receivedAt: Date.now()
}
}
export function fetchEntities(model, searchTerm, delay = 0) {
return (dispatch, getState) => {
const request = () => {
dispatch(requestEntities())
fetch(`http://localhost:8080/nice2/rest/entities/${model}?_search=${searchTerm}`, {
credentials: 'include'
})
.then(response => response.json())
.then(json => dispatch(receiveEntities(json)))
}
if (delay > 0) {
setTimeout(() => {
if (getState().list.searchTerm === searchTerm) {
request()
}
}, delay)
} else {
request()
}
}
}
const ACTION_HANDLERS = {
[RECEIVE_ENTITIES]: (state, { data }) => {
return [].concat(data);
}
}
const initialState = []
export default function listReducer(state = initialState, action: Action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
import fetch from 'isomorphic-fetch'
export const REQUEST_ENTITIES = 'REQUEST_ENTITIES'
export const RECEIVE_ENTITIES = 'RECEIVE_ENTITIES'
function requestEntities() {
return {
type: REQUEST_ENTITIES
}
}
function receiveEntities(json) {
return {
type: RECEIVE_ENTITIES,
data: json.data,
receivedAt: Date.now()
}
}
export function fetchEntities(model, searchTerm, delay = 0) {
return (dispatch, getState) => {
const request = () => {
dispatch(requestEntities())
fetch(`http://localhost:8080/nice2/rest/entities/${model}?_search=${searchTerm}`)
.then(response => response.json())
.then(json => dispatch(receiveEntities(json)))
}
if (delay > 0) {
setTimeout(() => {
if (getState().list.searchTerm === searchTerm) {
request()
}
}, delay)
} else {
request()
}
}
}
const ACTION_HANDLERS = {
[RECEIVE_ENTITIES]: (state, { data }) => {
return [].concat(data);
}
}
const initialState = []
export default function listReducer(state = initialState, action: Action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
Fix sidebar start position considering navbar margin-bottom
|
window.onload = function() {
var headHeight = $("nav").height();
var mainHeight = $("main").height();
var sideHeight = $("#sidebar").height();
var footHeight = $("footer").height();
var totalHeight = headHeight + mainHeight + footHeight;
var w = $(window);
if ( w.width() > $("main").width() + $("#sidebar").width()
&& sideHeight > 0
&& sideHeight < mainHeight ) {
$(".doc-sidebar").css("height", mainHeight);
var sideNode = $("#sidebar");
sideNode.css({"position": "fixed"});
var scrollStart = 0;
var scrollStop = headHeight + mainHeight - sideHeight;
w.scroll(function() {
if (w.scrollTop() <= scrollStart) {
sideNode.css({"position": "fixed"});
} else if (scrollStart < w.scrollTop() && w.scrollTop() < scrollStop) {
sideNode.css({"position": "fixed", "top": headHeight + 20 + "px"});
} else if (w.scrollTop() >= scrollStop) {
var topNext
= headHeight - (headHeight + sideHeight)
* (w.scrollTop() - scrollStop) / (totalHeight - scrollStop);
sideNode.css({
"position": "fixed", "top": topNext + "px", "bottom": footHeight + "px"
});
}
});
}
}
|
window.onload = function() {
var headHeight = $("nav").height();
var mainHeight = $("main").height();
var sideHeight = $("#sidebar").height();
var footHeight = $("footer").height();
var totalHeight = headHeight + mainHeight + footHeight;
var w = $(window);
if ( w.width() > $("main").width() + $("#sidebar").width()
&& sideHeight > 0
&& sideHeight < mainHeight ) {
$(".doc-sidebar").css("height", mainHeight);
var sideNode = $("#sidebar");
sideNode.css({"position": "fixed"});
var scrollStart = 0;
var scrollStop = headHeight + mainHeight - sideHeight;
w.scroll(function() {
if (w.scrollTop() <= scrollStart) {
sideNode.css({"position": "fixed"});
} else if (scrollStart < w.scrollTop() && w.scrollTop() < scrollStop) {
sideNode.css({"position": "fixed", "top": headHeight + "px"});
} else if (w.scrollTop() >= scrollStop) {
var topNext
= headHeight - (headHeight + sideHeight)
* (w.scrollTop() - scrollStop) / (totalHeight - scrollStop);
sideNode.css({
"position": "fixed", "top": topNext + "px", "bottom": footHeight + "px"
});
}
});
}
}
|
Revert "Ignore security token for guests"
Due to the age of this commit it's a bit unclear why exactly it was necessary
at that time, but records indicate that it was related to the URL based session
system (`?s=…`) in combination with with virtual sessions effectively changing
the session ID during login, the `SID` constants being constant and the CSRF
token being stored in the session.
As none of this applies any longer, this workaround should no longer be
necessary and thus reverted. It certainly violates the principle of least
astonishment, because it only applies to AbstractSecureAction, but not forms
and it's questionable from a security perspective.
This reverts commit e5c2467f717632b47f935a0e59a310de2e2867f3.
|
<?php
namespace wcf\action;
use wcf\system\exception\InvalidSecurityTokenException;
use wcf\system\WCF;
/**
* Extends AbstractAction by a function to validate a given security token.
* A missing or invalid token will be result in a throw of a IllegalLinkException.
*
* @author Marcel Werk
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Action
*/
abstract class AbstractSecureAction extends AbstractAction
{
/**
* @inheritDoc
*/
public function readParameters()
{
parent::readParameters();
$this->checkSecurityToken();
}
/**
* Validates the security token.
*/
protected function checkSecurityToken()
{
if (!isset($_REQUEST['t']) || !WCF::getSession()->checkSecurityToken($_REQUEST['t'])) {
throw new InvalidSecurityTokenException();
}
}
}
|
<?php
namespace wcf\action;
use wcf\system\exception\InvalidSecurityTokenException;
use wcf\system\WCF;
/**
* Extends AbstractAction by a function to validate a given security token.
* A missing or invalid token will be result in a throw of a IllegalLinkException.
*
* @author Marcel Werk
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Action
*/
abstract class AbstractSecureAction extends AbstractAction
{
/**
* @inheritDoc
*/
public function readParameters()
{
parent::readParameters();
// check security token (unless it is a guest)
if (WCF::getSession()->userID) {
$this->checkSecurityToken();
}
}
/**
* Validates the security token.
*/
protected function checkSecurityToken()
{
if (!isset($_REQUEST['t']) || !WCF::getSession()->checkSecurityToken($_REQUEST['t'])) {
throw new InvalidSecurityTokenException();
}
}
}
|
Disable moving after the game is over
|
const socket = require('socket.io-client')();
class Client {
constructor(board, boardElement) {
this.board = board;
this.boardElement = boardElement;
socket.on('login', ({id}) => {
this.board.selfNumber = id;
this.boardElement.update();
});
socket.on('update', (data) => {
this.board.fromData(data);
this.boardElement.update();
});
socket.on('move', (data) => {
if (this.board.selfNumber !== data.player) {
this.board.moveTo(data.direction);
}
});
board.on('moving', (direction) => {
if (this.board.isActive()) {
socket.emit('move', {direction});
}
});
board.on('win', () => {
this.board.selfNumber = 2;
});
}
}
module.exports = Client;
|
const socket = require('socket.io-client')();
class Client {
constructor(board, boardElement) {
this.board = board;
this.boardElement = boardElement;
socket.on('login', ({id}) => {
this.board.selfNumber = id;
this.boardElement.update();
});
socket.on('update', (data) => {
this.board.fromData(data);
this.boardElement.update();
});
socket.on('move', (data) => {
if (this.board.selfNumber !== data.player) {
this.board.moveTo(data.direction);
}
});
board.on('moving', (direction) => {
if (this.board.isActive()) {
socket.emit('move', {direction});
}
});
}
}
module.exports = Client;
|
[feat]: Create second view linking to homepage
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import goHomeActions from 'actions/goHome';
import RaisedButton from 'material-ui/lib/raised-button';
const mapStateToProps = (state) => ({
goHome : state.goHome,
routerState : state.router
});
const mapDispatchToProps = (dispatch) => ({
actions : bindActionCreators(goHomeActions, dispatch)
});
export class ResumeView extends React.Component {
static propTypes = {
actions : React.PropTypes.object
}
render () {
return (
<div className='container'>
<h1>is this thing on?</h1>
<RaisedButton label='This button does nothing' onClick={this.props.actions.goHome} />
<br/>
<br/>
<Link to='/'>but this link will take you back to the counter</Link>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ResumeView);
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import goHomeActions from 'actions/goHome';
import RaisedButton from 'material-ui/lib/raised-button';
const mapStateToProps = (state) => ({
goHome : state.goHome,
routerState : state.router
});
const mapDispatchToProps = (dispatch) => ({
actions : bindActionCreators(goHomeActions, dispatch)
});
export class ResumeView extends React.Component {
static propTypes = {
actions : React.PropTypes.object
}
render () {
return (
<div className='container'>
<h1>is this thing on?</h1>
<RaisedButton secondary={true} label='This button does nothing' onClick={this.props.actions.goHome} />
<br/>
<br/>
<Link to='/'>but this link will take you back to the counter</Link>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ResumeView);
|
Refactor redirectUrl logic of page language selector
|
const toArray = nodelist => Array.prototype.slice.call(nodelist);
const things = ['method', 'case', 'organization'];
const languageSelect = {
redirectUrl: null,
isThingDetailsPageWithLanguageParam: false,
init(tracking) {
this.tracking = tracking;
this.generateRedirectPath();
const selectEls = document.querySelectorAll(".js-language-select");
if (!selectEls) return;
toArray(selectEls).forEach(select => {
select.addEventListener("change", e => {
this.tracking.sendWithCallback("language", "language_dropdown", e.target.value, () => {
this.handleSelectChange(e);
});
});
});
},
handleSelectChange(e) {
let redirectUrl = this.isThingDetailsPageWithLanguageParam ? `${this.redirectUrl}/${e.target.value}` : this.redirectUrl;
location.href =
`/set-locale?locale=${e.target.value}` +
`&redirectTo=${redirectUrl}`;
},
generateRedirectPath() {
this.redirectUrl = window.location.pathname;
let urlPathMeta = window.location.pathname.split('/');
if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3] && urlPathMeta[3] !== 'edit') {
this.redirectUrl = `/${urlPathMeta[1]}/${urlPathMeta[2]}`;
this.isThingDetailsPageWithLanguageParam = true;
}
}
};
export default languageSelect;
|
const toArray = nodelist => Array.prototype.slice.call(nodelist);
const things = ['method', 'case', 'organization'];
const languageSelect = {
redirectUrl: null,
isThingDetailsPageWithLanguageParam: false,
init(tracking) {
this.tracking = tracking;
this.generateRedirectPath();
const selectEls = document.querySelectorAll(".js-language-select");
if (!selectEls) return;
toArray(selectEls).forEach(select => {
select.addEventListener("change", e => {
this.tracking.sendWithCallback("language", "language_dropdown", e.target.value, () => {
this.handleSelectChange(e);
});
});
});
},
handleSelectChange(e) {
let redirectUrl = this.isThingDetailsPageWithLanguageParam ? `${this.redirectUrl}/${e.target.value}` : this.redirectUrl;
location.href =
`/set-locale?locale=${e.target.value}` +
`&redirectTo=${redirectUrl}`;
},
generateRedirectPath() {
this.redirectUrl = window.location.pathname;
let urlPathMeta = window.location.pathname.split('/');
if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3]) {
this.redirectUrl = `/${urlPathMeta[1]}/${urlPathMeta[2]}`;
this.isThingDetailsPageWithLanguageParam = true;
}
}
};
export default languageSelect;
|
Add hash parameter to forge decrypt.
|
var Algorithm = require("./abstract")("RSA-OAEP")
, RSA = require("./shared/RSA")
, forge = require("node-forge")
, types = Algorithm.types
, public = types.public.usage
, private = types.private.usage;
//attached shared RSA
RSA(Algorithm);
Algorithm.checkParams = checkParams;
public.encrypt = createEncrypt;
private.decrypt = createDecrypt;
module.exports = Algorithm;
function createEncrypt(Key){
return function RSA_OAEP_ENCRYPT(alg,buf){
return new Buffer(Key.publicKey.encrypt(buf.toString("binary"), "RSA-OAEP"),"binary");
};
}
function createDecrypt(Key){
return function RSA_OAEP_DECRYPT(alg,buf){
return new Buffer(Key.privateKey.decrypt(buf.toString("binary"), "RSA-OAEP", {
md: forge.md[alg.hash.name.toLowerCase().replace('-','')].create()
}),"binary");
};
}
function checkParams(format, algorithm, usages){
const ALLOWED_HASH_ALGORITHMS = ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'];
if (!algorithm.hash) {
algorith.hash = {name: 'SHA-1'}
} else if(!ALLOWED_HASH_ALGORITHMS.indexOf(algorithm.hash.name)){
throw new Error("Unsupported or missing hash name");
}
if (!Buffer.isBuffer(algorithm.publicExponent))
throw new Error("algorithm.publicExponent not a Buffer source");
}
|
var Algorithm = require("./abstract")("RSA-OAEP")
, RSA = require("./shared/RSA")
, forge = require("node-forge")
, types = Algorithm.types
, public = types.public.usage
, private = types.private.usage;
//attached shared RSA
RSA(Algorithm);
Algorithm.checkParams = checkParams;
public.encrypt = createEncrypt;
private.decrypt = createDecrypt;
module.exports = Algorithm;
function createEncrypt(Key){
return function RSA_OAEP_ENCRYPT(alg,buf){
return new Buffer(Key.publicKey.encrypt(buf.toString("binary"), "RSA-OAEP"),"binary");
};
}
function createDecrypt(Key){
return function RSA_OAEP_DECRYPT(alg,buf){
return new Buffer(Key.privateKey.decrypt(buf.toString("binary"), "RSA-OAEP"),"binary");
};
}
function checkParams(format, algorithm, usages){
//if (!(algorithm.hash && (algorithm.hash.name === "SHA-256")))
//throw new Error("Unsupported or missing hash name");
//if (!Buffer.isBuffer(algorithm.publicExponent))
//throw new Error("algorithm.publicExponent not a Buffer source");
}
|
Remove hard coded 'engine' and 'lib' in coverage testing
|
#!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s tests/%s/%s_test.py')
print subprocess.check_output(
command % (package, module, package, module),
stderr=subprocess.STDOUT,
shell=True)
print subprocess.check_output(
'coverage report --fail-under=100 -m',
stderr=subprocess.STDOUT,
shell=True)
subprocess.check_output(
'coverage erase',
shell=True)
def coverage_test_package(package):
def path_to_name(name):
return os.path.split(name)[1].split('.')[0]
for module in functional.removed(
map(path_to_name, find_all(
os.path.join('src', package), '.py')), '__init__'):
print package, module
coverage_module(package, module)
def coverage_test_all():
os.chdir(os.environ['PORTER'])
for package in os.listdir('src/'):
coverage_test_package(package)
if __name__ == '__main__':
coverage_test_all()
|
#!/usr/bin/env python
import os
import subprocess
from lib import functional
from util import find_all
def coverage_module(package, module):
command = (
'coverage run --branch'
' --source=%s.%s tests/%s/%s_test.py')
print subprocess.check_output(
command % (package, module, package, module),
stderr=subprocess.STDOUT,
shell=True)
print subprocess.check_output(
'coverage report --fail-under=100 -m',
stderr=subprocess.STDOUT,
shell=True)
subprocess.check_output(
'coverage erase',
shell=True)
def coverage_test_package(package):
def path_to_name(name):
return os.path.split(name)[1].split('.')[0]
for module in functional.removed(
map(path_to_name, find_all(
os.path.join('src', package), '.py')), '__init__'):
print package, module
coverage_module(package, module)
def coverage_test_all():
os.chdir(os.environ['PORTER'])
for package in ['lib', 'engine']:
coverage_test_package(package)
if __name__ == '__main__':
coverage_test_all()
|
Drop down the fire rate
|
import AbstractTower from '../AbstractTower';
/**
* MasterChef class
* Master tower
*/
export default class MasterChef extends AbstractTower {
constructor() {
console.log('MasterChef -> constructor');
super({
stats: {
attack: 32,
precision: 0.7,
cost: 26,
distAttack: 3,
radius: 1,
maxTarget: -1,
fireRate: 2000,
},
id: 'master-chef',
textures: {
up: 'masterChef_back',
down: 'masterChef_front',
left: 'masterChef_left',
right: 'masterChef_right',
ammo: 'masterChef_seed',
},
});
this.anchor.set(0, 0.2);
}
}
|
import AbstractTower from '../AbstractTower';
/**
* MasterChef class
* Master tower
*/
export default class MasterChef extends AbstractTower {
constructor() {
console.log('MasterChef -> constructor');
super({
stats: {
attack: 32,
precision: 0.7,
cost: 26,
distAttack: 3,
radius: 1,
maxTarget: -1,
fireRate: 1000,
},
id: 'master-chef',
textures: {
up: 'masterChef_back',
down: 'masterChef_front',
left: 'masterChef_left',
right: 'masterChef_right',
ammo: 'masterChef_seed',
},
});
this.anchor.set(0, 0.2);
}
}
|
Clean up file patterns in PIPELINE_CSS setting.
|
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from os.path import join
from .roots import PROJECT_ROOT
PIPELINE_COMPILERS = (
'huxley.utils.pipeline.PySCSSCompiler',
'pipeline_browserify.compiler.BrowserifyCompiler',
)
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor'
PIPELINE_JS_COMPRESSOR = None
PIPELINE_CSS = {
'huxley': {
'source_filenames': (
'scss/core/*.scss',
'scss/accounts/*.scss',
),
'output_filename': 'css/huxley.css'
},
}
PIPELINE_JS = {
'huxley': {
'source_filenames': (
'js/huxley.browserify.js',
),
'output_filename': 'js/huxley.js'
}
}
PIPELINE_BROWSERIFY_BINARY = join(PROJECT_ROOT, 'node_modules/.bin/browserify')
PIPELINE_BROWSERIFY_ARGUMENTS = '-t reactify'
|
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from os.path import join
from .roots import PROJECT_ROOT
PIPELINE_COMPILERS = (
'huxley.utils.pipeline.PySCSSCompiler',
'pipeline_browserify.compiler.BrowserifyCompiler',
)
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor'
PIPELINE_JS_COMPRESSOR = None
PIPELINE_CSS = {
'huxley': {
'source_filenames': (
'css/*.css',
'scss/core/*.scss',
'scss/accounts/*.scss',
'scss/advisors/*.scss',
'scss/chairs/*.scss',
),
'output_filename': 'css/huxley.css'
},
}
PIPELINE_JS = {
'huxley': {
'source_filenames': (
'js/huxley.browserify.js',
),
'output_filename': 'js/huxley.js'
}
}
PIPELINE_BROWSERIFY_BINARY = join(PROJECT_ROOT, 'node_modules/.bin/browserify')
PIPELINE_BROWSERIFY_ARGUMENTS = '-t reactify'
|
[Bundle] Make getPath() less error prone by allowing both backward and forward slashes
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SwiftmailerBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class SwiftmailerBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
protected function getPath()
{
return __DIR__;
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SwiftmailerBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class SwiftmailerBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
public function getPath()
{
return strtr(__DIR__, '\\', '/');
}
}
|
Remove --harmony_collections & --harmony_iteration, their features are now on by default
|
'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
'--harmony_symbols', // `Symbol('s')` throws
// '--harmony_proxies', // `new Proxy({}, {})` throws
'--harmony_generators',
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
'--harmony_maths',
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
|
'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
'--harmony_symbols', // `Symbol('s')` throws
// '--harmony_proxies', // `new Proxy({}, {})` throws
// '--harmony_collections', // `new Set([2]).size` should be `1`
'--harmony_generators',
// '--harmony_iteration', // no `for-of`, the description must be wrong
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
'--harmony_maths',
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
|
Disable profile complete check for user tags
|
preloadSubscriptions.push('usertags');
// Add our template to user profile viewing.
userProfileDisplay.push({template: "listUserTags", order: 2});
// Add our template to user profile editing.
userProfileEdit.push({template: "editUserTags", order: 2});
// Add our template to the finish-signup view.
userProfileFinishSignup.push({template: "editUserTags", order: 2});
// Callback for processing user properties when editing a profile.
userEditClientCallbacks.push(function(properties) {
if ($("[name=usertag]").length) {
var tags = [];
$("[name=usertag]:checked").each(function(i, el) {
tags.push($(el).val());
})
properties["profile.tags"] = tags;
}
return properties;
});
// Callback to determine whether or not a user profile is complete.
//userProfileCompleteChecks.push(function(user) {
// return user && user.profile && typeof user.profile.tags !== "undefined";
//});
// Add tags to the post info byline display
postAuthor.push({template: "userTagsForPost", order: 2})
// Add our admin view to nav.
adminNav.push({route: 'usertags', label: "User Tags"});
Meteor.startup(function() {
Router.onBeforeAction(Router._filters.isAdmin, {only: ['usertags']});
// User tags administration view
Router.map(function() {
this.route('usertags');
});
});
|
preloadSubscriptions.push('usertags');
// Add our template to user profile viewing.
userProfileDisplay.push({template: "listUserTags", order: 2});
// Add our template to user profile editing.
userProfileEdit.push({template: "editUserTags", order: 2});
// Add our template to the finish-signup view.
userProfileFinishSignup.push({template: "editUserTags", order: 2});
// Callback for processing user properties when editing a profile.
userEditClientCallbacks.push(function(properties) {
if ($("[name=usertag]").length) {
var tags = [];
$("[name=usertag]:checked").each(function(i, el) {
tags.push($(el).val());
})
properties["profile.tags"] = tags;
}
return properties;
});
// Callback to determine whether or not a user profile is complete.
userProfileCompleteChecks.push(function(user) {
return user && user.profile && typeof user.profile.tags !== "undefined";
});
// Add tags to the post info byline display
postAuthor.push({template: "userTagsForPost", order: 2})
// Add our admin view to nav.
adminNav.push({route: 'usertags', label: "User Tags"});
Meteor.startup(function() {
Router.onBeforeAction(Router._filters.isAdmin, {only: ['usertags']});
// User tags administration view
Router.map(function() {
this.route('usertags');
});
});
|
Add CorsService to service provider
|
<?php
/**
* CORS service provider
*
* @package phpnexus/cors-laravel
* @copyright Copyright (c) 2016 Mark Prosser
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://github.com/phpnexus/cors-laravel
*/
namespace PhpNexus\CorsLaravel;
use Illuminate\Support\ServiceProvider;
use PhpNexus\Cors\CorsService;
use PhpNexus\CorsLaravel\Middleware as CorsMiddleware;
/**
* CORS service provider class
*/
class CorsServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container
*
* @return void
*/
public function register()
{
// CORS service
$this->app->singleton(CorsService::class, function ($app) {
// Load cors configuration
$app->configure('cors');
return new CorsService($app['config']['cors']);
});
// CORS middleware
$this->app->singleton(CorsMiddleware::class, function ($app) {
// Create new CorsMiddleware, with CorsService
return new CorsMiddleware($app->make(CorsService::class));
});
}
}
|
<?php
/**
* CORS middleware service provider
*
* @package phpnexus/cors-laravel
* @copyright Copyright (c) 2016 Mark Prosser
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://github.com/phpnexus/cors-laravel
*/
namespace PhpNexus\CorsLaravel;
use Illuminate\Support\ServiceProvider;
use PhpNexus\CorsLaravel\Middleware as CorsMiddleware;
/**
* CORS service provider class
*/
class CorsServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container
*
* @return void
*/
public function register()
{
$this->app->singleton(CorsMiddleware::class, function ($app) {
// Load cors configuration
$app->configure('cors');
// Create new CORS middleware, with config
return new CorsMiddleware($app['config']['cors']);
});
}
}
|
Remove unnecessary IIFE from Y class
|
const http = require('http');
const jsdom = require('jsdom');
const jQuery = require('jquery');
const Router = require('./router/index');
const body = require('./body/index');
/**
* The jQuerate Class
*
* Patches the emitter and listen handler
* to allow max jQuery gainz
*/
class Yttrium {
constructor(options) {
this.dom = new jsdom.JSDOM('<!DOCTYPE html>');
this.$ = jQuery(this.dom.window);
this.$ = this.$.bind(this);
const r = new Router(options);
const router = r.router;
this.server = http.createServer();
const oldEmit = this.server.emit;
const emit = (type, ...data) => {
this.$(this.server).trigger(type, data);
oldEmit.apply(this.server, [type, ...data]);
};
this.server.emit = emit.bind(this);
this.$.listen = (s, ...args) => s.listen(...args);
this.$.route = r.$;
this.$.body = body;
this.router = router;
}
}
module.exports = options => new Yttrium(options);
|
const http = require('http');
const jsdom = require('jsdom');
const jQuery = require('jquery');
const Router = require('./router/index');
const body = require('./body/index');
/**
* The jQuerate Class
*
* Patches the emitter and listen handler
* to allow max jQuery gainz
*/
class Yttrium {
constructor(options) {
this.dom = new jsdom.JSDOM('<!DOCTYPE html>');
this.$ = jQuery(this.dom.window);
const r = new Router(options);
const router = r.router;
this.server = ((httpServer, jQueryInstance) => {
const ser = httpServer;
const jq = jQueryInstance;
const oldEmit = ser.emit;
ser.emit = function emit(type, ...data) {
jq(ser).trigger(type, data);
oldEmit.apply(ser, [type, ...data]);
};
jq.listen = (s, ...args) => s.listen(...args);
return ser;
})(http.createServer(), this.$);
this.$.route = r.$;
this.$.body = body;
this.router = router;
}
}
module.exports = options => new Yttrium(options);
|
Fix code style for pm2 module
|
import express from 'express'
import session from 'express-session'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import passport from 'passport'
import routes from './api/routes'
import dotenv from 'dotenv'
import container from './dependency-container/container'
// Load environment variables from .env file
dotenv.load()
let port = process.env.PORT || 3000
let host = process.env.HOST || 'localhost'
let app = express()
app.use(morgan('dev'))
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(session({
resave: false,
secret: 'TEST'
}))
app.use(passport.initialize())
app.use(passport.session())
routes(app, passport)
app.listen(port, () => {
console.log('Mission Control listening at http://%s:%s', host, port)
})
|
import express from 'express'
import session from 'express-session'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import passport from 'passport'
import routes from './api/routes'
import dotenv from 'dotenv'
import container from './dependency-container/container'
// Load environment variables from .env file
dotenv.load()
let port = process.env.PORT || 3000
let host = process.env.HOST || 'localhost'
let app = express()
app.use(morgan('dev'))
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(session({
resave: false,
secret: 'TEST'
}))
app.use(passport.initialize())
app.use(passport.session())
routes(app, passport)
// app.all('*', (req, res) => res.send('Hello World'))
app.listen(port, () => {
console.log('Mission Control listening at http://%s:%s', host, port)
})
|
Fix bug: list of all subs did not work.
Bug introduced in commit 08c68b5a85bc9ab42391c6b3bb65942d4c9dce6b.
|
package herd
import (
"fmt"
"net"
"net/http"
)
var httpdHerd *Herd
func (herd *Herd) startServer(portNum uint, daemon bool) error {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
if err != nil {
return err
}
httpdHerd = herd
http.HandleFunc("/", statusHandler)
http.HandleFunc("/listSubs", listSubsHandler)
http.HandleFunc("/showAllSubs", showAllSubsHandler)
http.HandleFunc("/showDeviantSubs", showDeviantSubsHandler)
http.HandleFunc("/showCompliantSubs", showCompliantSubsHandler)
if daemon {
go http.Serve(listener, nil)
} else {
http.Serve(listener, nil)
}
return nil
}
func (herd *Herd) addHtmlWriter(htmlWriter HtmlWriter) {
herd.htmlWriters = append(herd.htmlWriters, htmlWriter)
}
|
package herd
import (
"fmt"
"net"
"net/http"
)
var httpdHerd *Herd
func (herd *Herd) startServer(portNum uint, daemon bool) error {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
if err != nil {
return err
}
httpdHerd = herd
http.HandleFunc("/", statusHandler)
http.HandleFunc("/listSubs", listSubsHandler)
http.HandleFunc("/showSubs", showAllSubsHandler)
http.HandleFunc("/showDeviantSubs", showDeviantSubsHandler)
http.HandleFunc("/showCompliantSubs", showCompliantSubsHandler)
if daemon {
go http.Serve(listener, nil)
} else {
http.Serve(listener, nil)
}
return nil
}
func (herd *Herd) addHtmlWriter(htmlWriter HtmlWriter) {
herd.htmlWriters = append(herd.htmlWriters, htmlWriter)
}
|
Add sleep, and prox_ground, prox_horizontal.
|
import os
import Pyro4
import subprocess
import signal
from pythymiodw import ThymioSimMR
import time
from pythymiodw.io import ProxGround
class ThymioMR():
def __init__(self):
self.pyro4daemon_proc=subprocess.Popen(['python -m pythymiodw.pyro.__main__'], stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
time.sleep(2)
self.robot = Pyro4.Proxy('PYRONAME:pythymiodw.thymiosimmr')
def quit(self):
self.robot.quit()
os.killpg(os.getpgid(self.pyro4daemon_proc.pid), signal.SIGTERM)
def wheels(self, lv, rv):
self.robot.wheels(lv, rv)
def get_wheels(self):
return self.robot.leftv, self.robot.rightv
def sleep(self, sec):
time.sleep(sec)
@property
def prox_horizontal(self):
return self.robot.prox_horizontal
@property
def prox_ground(self):
delta, ambiant, reflected = self.robot.prox_ground
return ProxGround(delta, ambiant, reflected)
|
import os
import Pyro4
import subprocess
import signal
from pythymiodw import ThymioSimMR
class ThymioMR():
def __init__(self):
self.pyro4daemon_proc=subprocess.Popen(['python -m pythymiodw.pyro.__main__'], stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
self.robot = Pyro4.Proxy('PYRONAME:pythymiodw.thymiosimmr')
def quit(self):
self.robot.quit()
os.killpg(os.getpgid(self.pyro4daemon_proc.pid), signal.SIGTERM)
def wheels(self, lv, rv):
self.robot.wheels(lv, rv)
def get_wheels(self):
return self.robot.leftv, self.robot.rightv
|
Enforce minimum PO value for supplier.
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Set minimum order on suppliers
# Copyright (C) 2016 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import (
res_partner,
purchase,
)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Set minimum order on suppliers
# Copyright (C) 2016 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import (
res_partner,
)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Make sure that connection is timed out
|
package name.webdizz.jeeconf.fault.tolerance.timeout;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
public class HttpOperationTimeoutTest {
public static final int MS = 40;
@Test(expected = ConnectTimeoutException.class)
public void shouldMakeSureTimeOutCaughtUsingApacheHttpClient() throws Exception {
int timeout = 1;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * MS)
.setConnectionRequestTimeout(timeout * MS)
.setSocketTimeout(timeout * MS).build();
CloseableHttpClient client =
HttpClientBuilder.create().setDefaultRequestConfig(config).build();
client.execute(new HttpGet("http://yahoo.com"));
}
}
|
package name.webdizz.jeeconf.fault.tolerance.timeout;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
public class HttpOperationTimeoutTest {
public static final int MS = 100;
@Test(expected = ConnectTimeoutException.class)
public void shouldMakeSureTimeOutCaughtUsingApacheHttpClient() throws Exception {
int timeout = 1;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * MS)
.setConnectionRequestTimeout(timeout * MS)
.setSocketTimeout(timeout * MS).build();
CloseableHttpClient client =
HttpClientBuilder.create().setDefaultRequestConfig(config).build();
client.execute(new HttpGet("http://yahoo.com"));
}
}
|
Add a set width function
|
var Controls = require('./controls');
function StompScreen(options) {
if(typeof options.el === 'string') {
options.el = document.querySelector(options.el);
}
this.el = options.el;
this.src = options.src;
this.width = options.width;
this.autoplay = options.autoplay;
this.setupScreen(this.el);
this.controls = new Controls({
controlsEl: this.controlsEl,
videoEl: this.videoEl,
autoplay: this.autoplay
});
this.paint();
}
StompScreen.prototype.setupScreen = function(el) {
this.containerEl = document.createElement('div');
this.videoEl = document.createElement('video');
this.controlsEl = document.createElement('div');
this.containerEl.style.width = this.width + 'px';
this.controlsEl.classList.add('controls');
this.videoEl.width = this.width;
this.videoEl.style.height = 'auto';
this.videoEl.setAttribute('src', this.src);
this.containerEl.classList.add('stompscreen-container');
this.videoEl.classList.add('stompscreen-video');
this.containerEl.appendChild(this.videoEl);
this.containerEl.appendChild(this.controlsEl);
return this.containerEl;
};
StompScreen.prototype.paint = function() {
this.el.appendChild(this.containerEl);
return this.el;
};
StompScreen.prototype.setWidth = function(width) {
this.width = width;
this.containerEl.style.width = this.width + 'px';
};
module.exports = StompScreen;
|
var Controls = require('./controls');
function StompScreen(options) {
if(typeof options.el === 'string') {
options.el = document.querySelector(options.el);
}
this.el = options.el;
this.src = options.src;
this.width = options.width;
this.autoplay = options.autoplay;
this.setupScreen(this.el);
this.controls = new Controls({
controlsEl: this.controlsEl,
videoEl: this.videoEl,
autoplay: this.autoplay
});
this.paint();
}
StompScreen.prototype.setupScreen = function(el) {
this.containerEl = document.createElement('div');
this.videoEl = document.createElement('video');
this.controlsEl = document.createElement('div');
this.containerEl.style.width = this.width + 'px';
this.controlsEl.classList.add('controls');
this.videoEl.width = this.width;
this.videoEl.style.height = 'auto';
this.videoEl.setAttribute('src', this.src);
this.containerEl.classList.add('stompscreen-container');
this.videoEl.classList.add('stompscreen-video');
this.containerEl.appendChild(this.videoEl);
this.containerEl.appendChild(this.controlsEl);
return this.containerEl;
};
StompScreen.prototype.paint = function() {
this.el.appendChild(this.containerEl);
return this.el;
};
module.exports = StompScreen;
|
Make analytics work with require.js
|
define(['json!/api/v1/client-config'], function (config) {
if (!(config && config.ga_token)
|| (typeof window === 'undefined')
|| ("localhost" === window.location.hostname)) {
console.debug("Skipping analytics");
return function () {}; // NO-OP function.
}
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', config.ga_token, 'auto');
return function () {
// Need to wrap as we cannot return a reference to the analytics.
ga.apply(null, arguments);
};
});
|
define(['json!/api/v1/client-config'], function (config) {
if (!(config && config.ga_token)
|| "localhost" == window.location.hostname) {
console.debug("Skipping analytics");
return function () {}; // NO-OP function.
}
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', config.ga_token, 'auto');
return ga;
});
|
Add support for new data structure
|
import _ from 'underscore';
import Levenshtein from 'levenshtein';
export function getStatusForResponse(response = {}) {
if (!response.feedback) {
return 4;
} else if (response.parent_id) {
return (response.optimal ? 2 : 3);
}
return (response.optimal ? 0 : 1);
}
export default function responsesWithStatus(responses = {}) {
return _.mapObject(responses, (value, key) => {
const statusCode = getStatusForResponse(value);
return Object.assign({}, value, { statusCode, });
});
}
export function sortByLevenshteinAndOptimal(userString, responses) {
responses.forEach((res) => { res.levenshtein = new Levenshtein(res.text, userString).distance; });
return responses.sort((a, b) => {
if ((a.levenshtein - b.levenshtein) != 0) {
return a.levenshtein - b.levenshtein;
}
// sorts by boolean
// from http://stackoverflow.com/questions/17387435/javascript-sort-array-of-objects-by-a-boolean-property
return (a.optimal === b.optimal) ? 0 : a.optimal ? -1 : 1;
});
}
|
import _ from 'underscore';
import Levenshtein from 'levenshtein'
export function getStatusForResponse(response = {}) {
if (!response.feedback) {
return 4;
} else if (response.parentID) {
return (response.optimal ? 2 : 3);
}
return (response.optimal ? 0 : 1);
}
export default function responsesWithStatus(responses = {}) {
return _.mapObject(responses, (value, key) => {
const statusCode = getStatusForResponse(value);
return Object.assign({}, value, { statusCode, });
});
}
export function sortByLevenshteinAndOptimal(userString, responses){
responses.forEach((res)=> {res.levenshtein = new Levenshtein(res.text, userString).distance});
return responses.sort((a,b)=> {
if ((a.levenshtein - b.levenshtein) != 0) {
return a.levenshtein - b.levenshtein
}
// sorts by boolean
// from http://stackoverflow.com/questions/17387435/javascript-sort-array-of-objects-by-a-boolean-property
return (a.optimal === b.optimal) ? 0 : a.optimal ? -1 : 1;
})
}
|
Clone the element without using addons
|
let findApp = require('../core/findApp');
let { isArray, extend } = require('../mindash');
module.exports = function (React) {
let ApplicationContainer = React.createClass({
childContextTypes: {
app: React.PropTypes.object
},
getChildContext() {
return { app: findApp(this) };
},
render() {
let { app, children } = this.props;
if (children) {
if (isArray(children)) {
return <span>{React.Children.map(children, cloneWithApp)}</span>;
} else {
return cloneWithApp(children);
}
}
function cloneWithApp(element) {
return React.createElement(element.type, extend({
app: app
}, element.props));
}
}
});
return ApplicationContainer;
};
|
let { isArray } = require('../mindash');
let findApp = require('../core/findApp');
module.exports = function (React) {
let ApplicationContainer = React.createClass({
childContextTypes: {
app: React.PropTypes.object
},
getChildContext() {
return { app: findApp(this) };
},
render() {
let { app, children } = this.props;
if (children) {
if (isArray(children)) {
return <span>{React.Children.map(children, cloneElementWithApp)}</span>;
} else {
return cloneElementWithApp(children);
}
}
function cloneElementWithApp(element) {
return React.addons.cloneWithProps(element, {
app: app
});
}
}
});
return ApplicationContainer;
};
|
Change version convention to conform to PEP428
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.20.dev",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py",
"scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py",
"scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py",
"scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py",
"scripts/bentoo-confreader.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo")
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.20.0_dev",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py",
"scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py",
"scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py",
"scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py",
"scripts/bentoo-confreader.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo")
|
Change github url in WebView
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.tb.sundtektvinput;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Fragment that shows a web page for Sample TV Input introduction.
*/
public class MainFragment extends Fragment {
private static final String URL =
"https://github.com/tam1m/androidtv-sample-inputs";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
WebView webView = (WebView) getView();
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(URL);
}
}
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.tb.sundtektvinput;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Fragment that shows a web page for Sample TV Input introduction.
*/
public class MainFragment extends Fragment {
private static final String URL =
"http://github.com/googlesamples/androidtv-sample-inputs/blob/master/README.md";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
WebView webView = (WebView) getView();
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(URL);
}
}
|
Bump version to 0.3.3 & update mosca version to 2.1.0
|
Package.describe({
name: 'metemq:metemq',
version: '0.3.3',
// Brief, one-line summary of the package.
summary: 'MeteMQ',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Npm.depends({
'mqtt': '1.12.0',
'mqtt-emitter': '1.2.4',
'mosca': '2.1.0', // For testing
'portfinder': '1.0.3',
'metemq-broker': '0.0.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.1');
api.use('underscore@1.0.8');
api.use('accounts-password'); // For checking password
api.use('barbatus:typescript@0.4.0');
api.mainModule('client/index.ts', 'client');
api.mainModule('server/index.ts', 'server');
});
Package.onTest(function(api) {
api.use('metemq:metemq');
api.use('barbatus:typescript@0.4.0');
api.use(['practicalmeteor:mocha', 'practicalmeteor:chai']);
api.mainModule('test/index.ts');
});
|
Package.describe({
name: 'metemq:metemq',
version: '0.3.2',
// Brief, one-line summary of the package.
summary: 'MeteMQ',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Npm.depends({
'mqtt': '1.12.0',
'mqtt-emitter': '1.2.4',
'mosca': '2.0.2', // For testing
'portfinder': '1.0.3',
'metemq-broker': '0.0.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.1');
api.use('underscore@1.0.8');
api.use('accounts-password'); // For checking password
api.use('barbatus:typescript@0.4.0');
api.mainModule('client/index.ts', 'client');
api.mainModule('server/index.ts', 'server');
});
Package.onTest(function(api) {
api.use('metemq:metemq');
api.use('barbatus:typescript@0.4.0');
api.use(['practicalmeteor:mocha', 'practicalmeteor:chai']);
api.mainModule('test/index.ts');
});
|
Add reminder timer to the default mod list.
|
var rModsList = [];
/* start ui_mod_list */
var global_mod_list = [
];
var scene_mod_list = {'connect_to_game': [
],'game_over': [
],
'icon_atlas': [
],
'live_game': [
//In game timer
'../../mods/dTimer/dTimer.css',
'../../mods/dTimer/dTimer.js',
//Mex/Energy Count
'../../mods/dMexCount/dMexCount.css',
'../../mods/dMexCount/dMexCount.js',
//Better System view (show system view at all times)
'../../mods/dBetterSystemView/dBetterSystemView.css',
'../../mods/dBetterSystemView/dBetterSystemView.js',
//Reminders
'../../mods/dReminderTimer/dReminderTimer.css',
'../../mods/dReminderTimer/dReminderTimer.js',
],
'load_planet': [
],
'lobby': [
],
'matchmaking': [
],
'new_game': [
],
'server_browser': [
],
'settings': [
],
'special_icon_atlas': [
],
'start': [
],
'system_editor': [
],
'transit': [
]
}
/* end ui_mod_list */
|
var rModsList = [];
/* start ui_mod_list */
var global_mod_list = [
];
var scene_mod_list = {'connect_to_game': [
],'game_over': [
],
'icon_atlas': [
],
'live_game': [
//In game timer
'../../mods/dTimer/dTimer.css',
'../../mods/dTimer/dTimer.js',
//Mex/Energy Count
'../../mods/dMexCount/dMexCount.css',
'../../mods/dMexCount/dMexCount.js',
//Better System view (show system view at all times)
'../../mods/dBetterSystemView/dBetterSystemView.css',
'../../mods/dBetterSystemView/dBetterSystemView.js',
],
'load_planet': [
],
'lobby': [
],
'matchmaking': [
],
'new_game': [
],
'server_browser': [
],
'settings': [
],
'special_icon_atlas': [
],
'start': [
],
'system_editor': [
],
'transit': [
]
}
/* end ui_mod_list */
|
Use old resource ID, so it's backward compatible with existing tokens.
|
/*
* Copyright 2014 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.dsu.configuration;
/**
* An interface containing shared properties for OAuth2 configurations.
*
* @author Emerson Farrugia
*/
public interface OAuth2Properties {
String CLIENT_ROLE = "ROLE_CLIENT";
String END_USER_ROLE = "ROLE_END_USER";
String DATA_POINT_RESOURCE_ID = "dataPoint";
String DATA_POINT_READ_SCOPE = "read_data_points";
String DATA_POINT_WRITE_SCOPE = "write_data_points";
String DATA_POINT_DELETE_SCOPE = "delete_data_points";
}
|
/*
* Copyright 2014 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.dsu.configuration;
/**
* An interface containing shared properties for OAuth2 configurations.
*
* @author Emerson Farrugia
*/
public interface OAuth2Properties {
String CLIENT_ROLE = "ROLE_CLIENT";
String END_USER_ROLE = "ROLE_END_USER";
String DATA_POINT_RESOURCE_ID = "dataPoints";
String DATA_POINT_READ_SCOPE = "read_data_points";
String DATA_POINT_WRITE_SCOPE = "write_data_points";
String DATA_POINT_DELETE_SCOPE = "delete_data_points";
}
|
Adjust receiver class in connector module
|
import _ from 'lodash';
import errorer from '../../../errorer/errorer';
export default class {
constructor(instance, receiver, receiverConfigs, params) {
let {events = {}} = instance;
let method = events[receiver] || receiver;
_.extend(this, {data: {}, instance, method, receiverConfigs, params});
return this.handler.bind(this);
}
handler(result, storeAs) {
let {data, receiverConfigs, params, instance, method} = this;
let {complete, reset} = receiverConfigs;
let previous = Promise.resolve(data[storeAs]);
let current = Promise.resolve(result);
data[storeAs] = previous.then(() => current).then(result => {
data[storeAs] = result;
if(complete) {
if(_.keys(data).length < params.length) {
return;
}
if(reset) {
setTimeout(() => this.data = {});
}
}
instance[method](_.clone(data));
}).catch(e => errorer({type: e})).catch(_.noop);
}
}
|
import _ from 'lodash';
import errorer from '../../../errorer/errorer';
export default class {
constructor(instance, receiver, receiverConfigs, params) {
let {events = {}} = instance;
let method = events[receiver] || receiver;
_.extend(this, {data: {}, instance, method, receiverConfigs, params});
return this.handler.bind(this);
}
handler(result, storeAs) {
let {data, receiverConfigs, params, instance, method} = this;
let {complete, reset} = receiverConfigs;
let previous = Promise.resolve(data[storeAs]);
let current = Promise.resolve(result);
previous.then(() => current).then(result => {
data[storeAs] = result;
if(complete) {
if(_.keys(data).length < params.length) {
return;
}
if(reset) {
setTimeout(() => this.data = {});
}
}
instance[method](_.clone(data));
}).catch(e => errorer({type: e})).catch(_.noop);
}
}
|
Update the url patterns to be compliant with Django 1.9 new formatting
so need to support Django < 1.8 because it is now deprecated for
security reasons
|
"""URLs module"""
from django import VERSION
from django.conf import settings
from django.conf.urls import url
from social.apps.django_app import views
from social.utils import setting_name
extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''
urlpatterns = (
# authentication / association
url(r'^login/(?P<backend>[^/]+){0}$'.format(extra),
views.auth,
name='begin'),
url(r'^complete/(?P<backend>[^/]+){0}$'.format(extra),
views.complete,
name='complete'),
# disconnection
url(r'^disconnect/(?P<backend>[^/]+){0}$'.format(extra),
views.disconnect,
name='disconnect'),
url(r'^disconnect/(?P<backend>[^/]+)/(?P<association_id>[^/]+){0}$'
.format(extra),
views.disconnect,
name='disconnect_individual'),
)
|
"""URLs module"""
from django.conf import settings
try:
from django.conf.urls import patterns, url
except ImportError:
# Django < 1.4
from django.conf.urls.defaults import patterns, url
from social.utils import setting_name
extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''
urlpatterns = patterns('social.apps.django_app.views',
# authentication / association
url(r'^login/(?P<backend>[^/]+){0}$'.format(extra), 'auth',
name='begin'),
url(r'^complete/(?P<backend>[^/]+){0}$'.format(extra), 'complete',
name='complete'),
# disconnection
url(r'^disconnect/(?P<backend>[^/]+){0}$'.format(extra), 'disconnect',
name='disconnect'),
url(r'^disconnect/(?P<backend>[^/]+)/(?P<association_id>[^/]+){0}$'
.format(extra), 'disconnect', name='disconnect_individual'),
)
|
Fix compilation error after core shifted
Core is slowly removing raw types. Slowly. And one such removal broke shield.
Original commit: elastic/x-pack-elasticsearch@aa1b668c63fba5c8af9e2dd984a456953b100a19
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.marvel.shield;
import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.FilterClient;
import org.elasticsearch.common.inject.Inject;
/**
*
*/
public class SecuredClient extends FilterClient {
private MarvelShieldIntegration shieldIntegration;
@Inject
public SecuredClient(Client in, MarvelShieldIntegration shieldIntegration) {
super(in);
this.shieldIntegration = shieldIntegration;
}
@Override
protected <Request extends ActionRequest<Request>, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(
Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
this.shieldIntegration.bindInternalMarvelUser(request);
super.doExecute(action, request, listener);
}
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.marvel.shield;
import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.FilterClient;
import org.elasticsearch.common.inject.Inject;
/**
*
*/
public class SecuredClient extends FilterClient {
private MarvelShieldIntegration shieldIntegration;
@Inject
public SecuredClient(Client in, MarvelShieldIntegration shieldIntegration) {
super(in);
this.shieldIntegration = shieldIntegration;
}
@Override
protected <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
this.shieldIntegration.bindInternalMarvelUser(request);
super.doExecute(action, request, listener);
}
}
|
Add __str__ to Preprocessor class
|
import json
class Preprocessor:
def __init__(self):
self.reset()
def __str__(self):
return json.dumps(self.__dict__, indent=2, separators=(',', ': '))
def reset(self):
self.number_elements = 0
self.length_elements = []
self.E_elements = []
self.I_elements = []
self.loads = []
self.supports = []
def load_json(self, infile):
self.reset()
with open(infile) as json_model:
model = json.load(json_model)
self.number_elements = len(model['elements'])
self.length_elements = [element['length'] for element in model['elements']]
self.E_elements = [element['youngs_mod'] for element in model['elements']]
self.I_elements = [element['moment_of_inertia'] for element in model['elements']]
# for element in model['elements']:
# for load in element['loads']:
# load["element"] = element["element"]
# self.loads.append(load)
self.loads = [element['loads'] for element in model['elements']]
self.supports = model['supports']
|
import json
class Preprocessor:
def __init__(self):
self.reset()
def reset(self):
self.number_elements = 0
self.length_elements = []
self.E_elements = []
self.I_elements = []
self.loads = []
self.supports = []
def load_json(self, infile):
self.reset()
with open(infile) as json_model:
model = json.load(json_model)
self.number_elements = len(model['elements'])
self.length_elements = [element['length'] for element in model['elements']]
self.E_elements = [element['youngs_mod'] for element in model['elements']]
self.I_elements = [element['moment_of_inertia'] for element in model['elements']]
# for element in model['elements']:
# for load in element['loads']:
# load["element"] = element["element"]
# self.loads.append(load)
self.loads = [element['loads'] for element in model['elements']]
self.supports = model['supports']
|
Use traits and MBID value in the model of an area.
|
<?php
namespace MusicBrainz\Value;
/**
* An area
*/
class Area
{
use Accessor\GetMBIDTrait;
use Accessor\GetNameTrait;
use Accessor\GetSortNameTrait;
/**
* Constructs an area.
*
* @param array $area Array of values
*/
public function __construct(array $area = [])
{
$this->MBID = new MBID(isset($area['id']) ? (string) $area['id'] : '');
$this->name = new Name(isset($area['name']) ? (string) $area['name'] : '');
$this->sortName = isset($area['sort-name']) ? (string) $area['sort-name'] : '';
}
/**
* Returns the area name.
*
* @return string
*/
public function __toString(): string
{
return (string) $this->name;
}
}
|
<?php
namespace MusicBrainz\Value;
/**
* An area
*/
class Area
{
/**
* The MusikBrainz Identifier for the area
*
* @var string
*/
private $id;
/**
* The area name
*
* @var Name
*/
private $name;
/**
* Sort index
*
* @var string
*/
private $sortName;
/**
* Constructs an area.
*
* @param array $area Array of values
*/
public function __construct(array $area = [])
{
$this->id = isset($area['id']) ? (string) $area['id'] : '';
$this->name = new Name(isset($area['name']) ? (string) $area['name'] : '');
$this->sortName = isset($area['sort-name']) ? (string) $area['sort-name'] : '';
}
/**
* Returns the area name.
*
* @return string
*/
public function __toString(): string
{
return (string) $this->name;
}
}
|
Handle one or more folders being inaccessible while listing
|
const path = require('path')
const stat = require('./stat')
const readdir = require('./readdir')
// based on http://stackoverflow.com/a/38314404/2533525
const getFolders = function (dir, filterFn) {
// default filter function accepts all folders
filterFn = filterFn || function () { return true }
return readdir(dir).then(list => {
return Promise.all(list.map(file => {
file = path.resolve(dir, file)
return stat(file).then(stat => {
if (stat.isDirectory()) {
return filterFn(file) ? file : ''
}
}).catch(err => {
// stat failed for this folder
console.error(err.message)
})
})).then(results => {
return results.filter(f => {
return !!f
})
})
}).then(results => {
// flatten the array of arrays
return Array.prototype.concat.apply([], results)
})
}
module.exports = getFolders
|
const path = require('path')
const stat = require('./stat')
const readdir = require('./readdir')
// based on http://stackoverflow.com/a/38314404/2533525
const getFolders = function (dir, filterFn) {
// default filter function accepts all folders
filterFn = filterFn || function () { return true }
return readdir(dir).then(list => {
return Promise.all(list.map(file => {
file = path.resolve(dir, file)
return stat(file).then(stat => {
if (stat.isDirectory()) {
return filterFn(file) ? file : ''
}
})
})).then(results => {
return results.filter(f => {
return !!f
})
})
}).then(results => {
// flatten the array of arrays
return Array.prototype.concat.apply([], results)
})
}
module.exports = getFolders
|
Update cmd to pass context to request
|
package main
import (
"context"
"fmt"
"os"
"time"
"strings"
"github.com/hackebrot/go-librariesio/librariesio"
)
func loadFromEnv(keys ...string) (map[string]string, error) {
env := make(map[string]string)
for _, key := range keys {
v := os.Getenv(key)
if v == "" {
return nil, fmt.Errorf("environment variable %q is required", key)
}
env[key] = v
}
return env, nil
}
func main() {
env, err := loadFromEnv("LIBRARIESIO_API_KEY")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
project, _, err := c.GetProject(ctx, "pypi", "cookiecutter")
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%+v\n", project)
}
|
package main
import (
"fmt"
"os"
"strings"
"github.com/hackebrot/go-librariesio/librariesio"
)
func loadFromEnv(keys ...string) (map[string]string, error) {
env := make(map[string]string)
for _, key := range keys {
v := os.Getenv(key)
if v == "" {
return nil, fmt.Errorf("environment variable %q is required", key)
}
env[key] = v
}
return env, nil
}
func main() {
env, err := loadFromEnv("LIBRARIESIO_API_KEY")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
project, _, err := c.GetProject("pypi", "cookiecutter")
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%+v\n", project)
}
|
Align buffer_with_time_or_count signature with doc
According to docs, `buffer_with_time_or_count` has an optional scheduler
parameter but in reality it's mandatory. Let's make it optional for real
as passing `None` as third argument all the time is a bit inconvenient.
|
from rx import Observable
from rx.concurrency import timeout_scheduler
from rx.internal import extensionmethod
@extensionmethod(Observable)
def buffer_with_time_or_count(self, timespan, count, scheduler=None):
"""Projects each element of an observable sequence into a buffer that
is completed when either it's full or a given amount of time has
elapsed.
# 5s or 50 items in an array
1 - res = source.buffer_with_time_or_count(5000, 50)
# 5s or 50 items in an array
2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout)
Keyword arguments:
timespan -- Maximum time length of a buffer.
count -- Maximum element count of a buffer.
scheduler -- [Optional] Scheduler to run bufferin timers on. If not
specified, the timeout scheduler is used.
Returns an observable sequence of buffers.
"""
scheduler = scheduler or timeout_scheduler
return self.window_with_time_or_count(timespan, count, scheduler) \
.flat_map(lambda x: x.to_iterable())
|
from rx import Observable
from rx.concurrency import timeout_scheduler
from rx.internal import extensionmethod
@extensionmethod(Observable)
def buffer_with_time_or_count(self, timespan, count, scheduler):
"""Projects each element of an observable sequence into a buffer that
is completed when either it's full or a given amount of time has
elapsed.
# 5s or 50 items in an array
1 - res = source.buffer_with_time_or_count(5000, 50)
# 5s or 50 items in an array
2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout)
Keyword arguments:
timespan -- Maximum time length of a buffer.
count -- Maximum element count of a buffer.
scheduler -- [Optional] Scheduler to run bufferin timers on. If not
specified, the timeout scheduler is used.
Returns an observable sequence of buffers.
"""
scheduler = scheduler or timeout_scheduler
return self.window_with_time_or_count(timespan, count, scheduler) \
.flat_map(lambda x: x.to_iterable())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.