text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add init process as default
|
import sys
import RPi.GPIO as GPIO
# Register Pin number
enable1 = 22
input1a = 18
input1b = 16
def control(arg):
if arg == 'init':
GPIO.setmode(GPIO.BOARD)
GPIO.setup(enable1, GPIO.OUT)
GPIO.setup(input1a, GPIO.OUT)
GPIO.setup(input1b, GPIO.OUT)
elif arg == 'forward':
GPIO.output(enable1, True)
GPIO.output(input1a, True)
GPIO.output(input1b, False)
elif arg == 'backward':
GPIO.output(enable1, True)
GPIO.output(input1a, False)
GPIO.output(input1b, True)
elif arg == 'stop':
GPIO.output(enable1, False)
elif arg == 'quit':
GPIO.cleanup()
else:
print 'No such command: ' + arg
if __name__ == '__main__':
control('init')
control(sys.argv[1])
|
import sys
import RPi.GPIO as GPIO
# Register Pin number
enable1 = 22
input1a = 18
input1b = 16
def control(arg):
if arg == 'init':
GPIO.setmode(GPIO.BOARD)
GPIO.setup(enable1, GPIO.OUT)
GPIO.setup(input1a, GPIO.OUT)
GPIO.setup(input1b, GPIO.OUT)
elif arg == 'forward':
GPIO.output(enable1, True)
GPIO.output(input1a, True)
GPIO.output(input1b, False)
elif arg == 'backward':
GPIO.output(enable1, True)
GPIO.output(input1a, False)
GPIO.output(input1b, True)
elif arg == 'stop':
GPIO.output(enable1, False)
elif arg == 'quit':
GPIO.cleanup()
else:
print 'No such command: ' + arg
if __name__ == '__main__':
control(sys.argv[1])
|
Test if const CLIENT is valid
|
<?php
namespace Moip\Tests;
use Moip\Tests\MoipTestCase;
/**
* class MoipTest
*/
class MoipTest extends MoipTestCase
{
/**
* Test if endpoint production is valid.
*/
public function testShouldReceiveEndpointProductionIsValid()
{
$endpoint_production = 'api.moip.com.br';
$const_endpoint_production = constant('\Moip\Moip::ENDPOINT_PRODUCTION');
$this->assertEquals($endpoint_production, $const_endpoint_production);
}
/**
* Test if endpoint sandbox is valid.
*/
public function testShouldReceiveSandboxProductionIsValid()
{
$endpoint_sandbox = 'sandbox.moip.com.br';
$const_endpoint_sandbox = constant('\Moip\Moip::ENDPOINT_SANDBOX');
$this->assertEquals($endpoint_sandbox, $const_endpoint_sandbox);
}
/**
* Test if const CLIENT is valid.
*/
public function testShouldReceiveClientIsValid()
{
$client = 'Moip SDK';
$const_client = constant('\Moip\Moip::CLIENT');
$this->assertEquals($client, $const_client);
}
}
|
<?php
namespace Moip\Tests;
use Moip\Tests\MoipTestCase;
/**
* class MoipTest
*/
class MoipTest extends MoipTestCase
{
/**
* Test if endpoint production is valid.
*/
public function testShouldReceiveEndpointProductionIsValid()
{
$endpoint_production = 'api.moip.com.br';
$const_endpoint_production = constant('\Moip\Moip::ENDPOINT_PRODUCTION');
$this->assertEquals($endpoint_production, $const_endpoint_production);
}
/**
* Test if endpoint sandbox is valid.
*/
public function testShouldReceiveSandboxProductionIsValid()
{
$endpoint_sandbox = 'sandbox.moip.com.br';
$const_endpoint_sandbox = constant('\Moip\Moip::ENDPOINT_SANDBOX');
$this->assertEquals($endpoint_sandbox, $const_endpoint_sandbox);
}
}
|
Add source maps to tests
|
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'browserify'],
files: [
'test/*'
],
reporters: ['progress', 'coverage'],
port: 9876,
runnerPort: 9100,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: ['PhantomJS'],
captureTimeout: 60000,
singleRun: false,
browserify: {
watch: true,
debug: true,
transform: ['browserify-shim', 'browserify-istanbul']
},
preprocessors: {
'test/*': ['browserify'],
'lib/*': ['coverage']
},
coverageReporter: {
type : 'html',
dir : 'coverage/'
}
});
};
|
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'browserify'],
files: [
'test/*'
],
reporters: ['progress', 'coverage'],
port: 9876,
runnerPort: 9100,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: ['PhantomJS'],
captureTimeout: 60000,
singleRun: false,
browserify: {
watch: true,
transform: ['browserify-shim', 'browserify-istanbul']
},
preprocessors: {
'test/*': ['browserify'],
'lib/*': ['coverage']
},
coverageReporter: {
type : 'html',
dir : 'coverage/'
}
});
};
|
Update dsub version to 0.3.11.dev0
PiperOrigin-RevId: 324910070
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.11.dev0'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10'
|
Add temporary limit to Cover view to stop rebuilding artwork
TODO: Implement lazy loading of images to that they aren't
all fetched initially!
|
/** @jsx React.DOM */
'use strict';
var React = require('react/addons');
var CollectionStore = require('../stores/CollectionStore.js');
var CollectionActions = require('../actions/CollectionActions.js');
var Covers = React.createClass({
getInitialState: function() {
return {
list: [],
};
},
componentDidMount: function() {
CollectionStore.addChangeListener(this._onChange);
CollectionActions.fetch(["Root"]);
},
componentWillUnmount: function() {
CollectionStore.removeChangeListener(this._onChange);
},
render: function() {
var covers = this.state.list.map(function(item) {
return <Cover path={["Root"].concat(item.Key)} key={item.Key} item={item} />;
});
return (
<div className="covers">
{covers}
</div>
);
},
_onChange: function(path) {
if (path === CollectionStore.pathToKey(["Root"])) {
this.setState({
list: CollectionStore.getCollection(["Root"]).Groups.slice(0, 30),
});
}
},
});
var Cover = React.createClass({
getInitialState: function() {
return {
expanded: false,
};
},
render: function() {
return (
<div className="cover">
<img src={"/artwork/"+this.props.item.TrackID} />
</div>
);
},
});
module.exports = Covers;
|
/** @jsx React.DOM */
'use strict';
var React = require('react/addons');
var CollectionStore = require('../stores/CollectionStore.js');
var CollectionActions = require('../actions/CollectionActions.js');
var Covers = React.createClass({
getInitialState: function() {
return {
list: [],
};
},
componentDidMount: function() {
CollectionStore.addChangeListener(this._onChange);
CollectionActions.fetch(["Root"]);
},
componentWillUnmount: function() {
CollectionStore.removeChangeListener(this._onChange);
},
render: function() {
var covers = this.state.list.map(function(item) {
return <Cover path={["Root"].concat(item.Key)} key={item.Key} item={item} />;
});
return (
<div className="covers">
{covers}
</div>
);
},
_onChange: function(path) {
if (path === CollectionStore.pathToKey(["Root"])) {
this.setState({
list: CollectionStore.getCollection(["Root"]).Groups,
});
}
},
});
var Cover = React.createClass({
getInitialState: function() {
return {
expanded: false,
};
},
render: function() {
return (
<div className="cover">
<img src={"/artwork/"+this.props.item.TrackID} />
</div>
);
},
});
module.exports = Covers;
|
Add the utils module to the uncompiled whitelist.
PiperOrigin-RevId: 185733139
|
# Copyright 2016 The TensorFlow 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.
# ==============================================================================
"""Global configuration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.py2tf import utils
PYTHON_LITERALS = {
'None': None,
'False': False,
'True': True,
'float': float,
}
DEFAULT_UNCOMPILED_MODULES = set((
('tensorflow',),
(utils.__name__,),
))
NO_SIDE_EFFECT_CONSTRUCTORS = set(('tensorflow',))
# TODO(mdan): Also allow controlling the generated names (for testability).
# TODO(mdan): Verify that these names are not hidden by generated code.
# TODO(mdan): Make sure copybara renames the reference below.
COMPILED_IMPORT_STATEMENTS = (
'from __future__ import print_function',
'import tensorflow as tf',
'from tensorflow.contrib.py2tf import utils as '
'py2tf_utils')
|
# Copyright 2016 The TensorFlow 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.
# ==============================================================================
"""Global configuration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
PYTHON_LITERALS = {
'None': None,
'False': False,
'True': True,
'float': float,
}
DEFAULT_UNCOMPILED_MODULES = set((
('tensorflow',),
))
NO_SIDE_EFFECT_CONSTRUCTORS = set(('tensorflow',))
# TODO(mdan): Also allow controlling the generated names (for testability).
# TODO(mdan): Verify that these names are not hidden by generated code.
# TODO(mdan): Make sure copybara renames the reference below.
COMPILED_IMPORT_STATEMENTS = (
'from __future__ import print_function',
'import tensorflow as tf',
'from tensorflow.contrib.py2tf import utils as '
'py2tf_utils')
|
Refactor dependant-selector further and (conditionally) update TomSelect if present
I'm also introducing a convention here of adding a `private` comment to visually demarcate which methods are meant to be part of the public interface of the class and which aren't. The methods aren't *actually* private in any technical sense, it's just a bit of syntactic sugar to allow the intention to be communicated more clearly in the code's structure.
|
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["source", "select"];
static values = { options: Array };
handleSelectChange() {
this.populateSelect(parseInt(this.sourceTarget.value));
}
// private
populateSelect(sourceId) {
this.removeCurrentOptions()
this.populateNewOptions(sourceId)
}
removeCurrentOptions() {
this.selectTarget.innerHTML = ""
this.selectTarget.tomselect?.clear()
this.selectTarget.tomselect?.clearOptions()
}
populateNewOptions(sourceId) {
const options = this.dependantOptionsFor(sourceId)
options.forEach((item) => {
this.addOption(item[0], item[1])
});
this.selectTarget.tomselect?.sync()
this.selectTarget.tomselect?.addItem(options[0]?.[1])
}
addOption(label, value) {
const newOption = document.createElement("option")
newOption.innerHTML = label
newOption.value = value
this.selectTarget.appendChild(newOption)
}
dependantOptionsFor(sourceId) {
return this.optionsValue.find((option) => option[0] === sourceId)[1]
}
}
|
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["source", "select"];
static values = { options: Array };
handleSelectChange() {
this.populateSelect(parseInt(this.sourceTarget.value));
}
populateSelect(sourceId) {
this.removeCurrentOptions()
this.dependantOptionsFor(sourceId).forEach((item) => {
this.addOption(item[0], item[1])
});
}
removeCurrentOptions() {
this.selectTarget.innerHTML = ""
}
addOption(label, value) {
const newOption = document.createElement("option")
newOption.innerHTML = label
newOption.value = value
this.selectTarget.appendChild(newOption)
}
dependantOptionsFor(sourceId) {
return this.optionsValue.find((option) => option[0] === sourceId)[1]
}
}
|
Migrate from Form to FlaskForm
|
from flask_wtf import FlaskForm
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(FlaskForm):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(FlaskForm):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(Form):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(Form):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
Add support for ZStandard compression.
This is landing in Kafka 2.1.0, due for release 29th October, 2018.
References -
1. https://cwiki.apache.org/confluence/display/KAFKA/KIP-110%3A+Add+Codec+for+ZStandard+Compression
2. https://issues.apache.org/jira/browse/KAFKA-4514
3. https://github.com/apache/kafka/pull/2267
4. https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=91554044
|
const { KafkaJSNotImplemented } = require('../../../errors')
const MESSAGE_CODEC_MASK = 0x3
const RECORD_BATCH_CODEC_MASK = 0x07
const Types = {
None: 0,
GZIP: 1,
Snappy: 2,
LZ4: 3,
ZSTD: 4,
}
const Codecs = {
[Types.GZIP]: () => require('./gzip'),
[Types.Snappy]: () => {
throw new KafkaJSNotImplemented('Snappy compression not implemented')
},
[Types.LZ4]: () => {
throw new KafkaJSNotImplemented('LZ4 compression not implemented')
},
[Types.ZSTD]: () => {
throw new KafkaJSNotImplemented('ZSTD compression not implemented')
},
}
const lookupCodec = type => (Codecs[type] ? Codecs[type]() : null)
const lookupCodecByAttributes = attributes => {
const codec = Codecs[attributes & MESSAGE_CODEC_MASK]
return codec ? codec() : null
}
const lookupCodecByRecordBatchAttributes = attributes => {
const codec = Codecs[attributes & RECORD_BATCH_CODEC_MASK]
return codec ? codec() : null
}
module.exports = {
Types,
Codecs,
lookupCodec,
lookupCodecByAttributes,
lookupCodecByRecordBatchAttributes,
}
|
const { KafkaJSNotImplemented } = require('../../../errors')
const MESSAGE_CODEC_MASK = 0x3
const RECORD_BATCH_CODEC_MASK = 0x07
const Types = {
None: 0,
GZIP: 1,
Snappy: 2,
LZ4: 3,
}
const Codecs = {
[Types.GZIP]: () => require('./gzip'),
[Types.Snappy]: () => {
throw new KafkaJSNotImplemented('Snappy compression not implemented')
},
[Types.LZ4]: () => {
throw new KafkaJSNotImplemented('LZ4 compression not implemented')
},
}
const lookupCodec = type => (Codecs[type] ? Codecs[type]() : null)
const lookupCodecByAttributes = attributes => {
const codec = Codecs[attributes & MESSAGE_CODEC_MASK]
return codec ? codec() : null
}
const lookupCodecByRecordBatchAttributes = attributes => {
const codec = Codecs[attributes & RECORD_BATCH_CODEC_MASK]
return codec ? codec() : null
}
module.exports = {
Types,
Codecs,
lookupCodec,
lookupCodecByAttributes,
lookupCodecByRecordBatchAttributes,
}
|
Add paratemers to mediaSession factory method
|
/*
* Kurento Commons MSControl: Simplified Media Control API for the Java Platform based on jsr309
* Copyright (C) 2012 Tikal Technologies
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kurento.mscontrol.commons;
import com.kurento.commons.config.Parameters;
/**
* This class is the entry point where a MediaSession can be obtained
*
*/
public interface MediaSessionFactory {
/**
* Creates a new mediaSession object using the given configuration
* parameters. See platform documentation for further details about the
* parameters.
*
* @param parameters
* The configuration of the MediaSession
* @return New media session for a platform
* @throws MediaSessionException
*/
public MediaSession createMediaSession(Parameters parameters)
throws MediaSessionException;
}
|
/*
* Kurento Commons MSControl: Simplified Media Control API for the Java Platform based on jsr309
* Copyright (C) 2012 Tikal Technologies
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kurento.mscontrol.commons;
/**
* This class is the entry point where a MediaSession can be obtained
*
*/
public interface MediaSessionFactory {
/**
* Creates a new mediaSession object
*
* @return New media session for a platform
* @throws MediaSessionException
*/
public MediaSession createMediaSession()
throws MediaSessionException;
}
|
Fix piechart on 0 chars
|
import {connect} from 'react-redux'
import {createSelector} from 'reselect'
import DemoPieChart from '../components/DemoPieChart'
import {countLetters} from '../utils/stringStats'
import {incrementRenderCount, piechartToggleFilter} from '../actions'
import toJS from '../toJS'
const getText = state => state.get('text')
const getHover = state => state.get('hover')
const getFilterEnabled = state => state.get('piechartFilterEnabled')
const selectHover = createSelector(
[getHover, getFilterEnabled],
(hover, filter) => {
return filter ? hover : null
}
)
const selectData = createSelector([getText, selectHover], (text, hover) => {
return text.reduce((result, userText, user) => {
const nbOfLetters = countLetters(userText, hover ? hover.toJS() : null)
result.push({
name: user,
value: nbOfLetters
})
return result
}, [])
})
const mapStateToProps = (state, ownProps) => {
return {
data: selectData(state),
hover: selectHover(state),
filter: state.get('piechartFilterEnabled')
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
incrementRenderCount: mode =>
dispatch(incrementRenderCount('piechart', mode)),
toggleFilter: () => dispatch(piechartToggleFilter())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(toJS(DemoPieChart))
|
import {connect} from 'react-redux'
import {createSelector} from 'reselect'
import DemoPieChart from '../components/DemoPieChart'
import {countLetters} from '../utils/stringStats'
import {incrementRenderCount, piechartToggleFilter} from '../actions'
import toJS from '../toJS'
const getText = state => state.get('text')
const getHover = state => state.get('hover')
const getFilterEnabled = state => state.get('piechartFilterEnabled')
const selectHover = createSelector(
[getHover, getFilterEnabled],
(hover, filter) => {
return filter ? hover : null
}
)
const selectData = createSelector([getText, selectHover], (text, hover) => {
return text.reduce((result, userText, user) => {
const nbOfLetters = countLetters(userText, hover ? hover.toJS() : null)
if (nbOfLetters > 0) {
result.push({
name: user,
value: nbOfLetters
})
}
return result
}, [])
})
const mapStateToProps = (state, ownProps) => {
return {
data: selectData(state),
hover: selectHover(state),
filter: state.get('piechartFilterEnabled')
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
incrementRenderCount: mode =>
dispatch(incrementRenderCount('piechart', mode)),
toggleFilter: () => dispatch(piechartToggleFilter())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(toJS(DemoPieChart))
|
Make internal urls relative (as before)
|
/*
Copyright 2016 The Fission Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fission
import (
"fmt"
)
func UrlForFunction(m *Metadata) string {
prefix := "/fission-function"
if len(m.Uid) > 0 {
return fmt.Sprintf("%v/%v/%v", prefix, m.Name, m.Uid)
} else {
return fmt.Sprintf("%v/%v", prefix, m.Name)
}
}
|
/*
Copyright 2016 The Fission Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fission
import (
"fmt"
)
func UrlForFunction(m *Metadata) string {
// TODO this assumes the router's namespace is the same as whatever is hitting
// this url -- so e.g. kubewatcher will have to run in the same ns as router.
prefix := "http://router/fission-function"
if len(m.Uid) > 0 {
return fmt.Sprintf("%v/%v/%v", prefix, m.Name, m.Uid)
} else {
return fmt.Sprintf("%v/%v", prefix, m.Name)
}
}
|
Rename private variable to $handler
|
<?php
namespace Lily\Application;
class MiddlewareApplication
{
private $handler;
private $middleware;
public function __construct(array $pipeline)
{
$this->handler = array_shift($pipeline);
$this->middleware = $pipeline;
}
private function handler()
{
return $this->handler;
}
private function middleware()
{
return $this->middleware;
}
public function __invoke($request)
{
$handler = $this->handler();
foreach ($this->middleware() as $_mw) {
$handler = $_mw($handler);
}
return $handler($request);
}
}
|
<?php
namespace Lily\Application;
class MiddlewareApplication
{
private $application;
private $middleware;
public function __construct(array $pipeline)
{
$this->handler = array_shift($pipeline);
$this->middleware = $pipeline;
}
private function handler()
{
return $this->handler;
}
private function middleware()
{
return $this->middleware;
}
public function __invoke($request)
{
$handler = $this->handler();
foreach ($this->middleware() as $_mw) {
$handler = $_mw($handler);
}
return $handler($request);
}
}
|
Remove pixel test fail expectation
This patch undo the failure expectation in
https://codereview.chromium.org/340603002/ and completes the rebaseline of the
pixel tests.
BUG=384551
Review URL: https://codereview.chromium.org/348853003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@278961 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class PixelExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
pass
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class PixelExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Pixel.Canvas2DRedBox', bug=384551)
self.Fail('Pixel.CSS3DBlueBox', bug=384551)
self.Fail('Pixel.WebGLGreenTriangle', bug=384551)
pass
|
Make using AMD imports a linting error
Change-Id: I8c5073d660b808f6eb62432f914be71941253a80
Reviewed-on: https://gerrit.instructure.com/105000
Tested-by: Jenkins
Reviewed-by: Ryan Shaw <ea3cd978650417470535f3a4725b6b5042a6ab59@instructure.com>
Product-Review: Clay Diffrient <9dff2e5c98626d20d2848250c411e8009465bb87@instructure.com>
QA-Review: Clay Diffrient <9dff2e5c98626d20d2848250c411e8009465bb87@instructure.com>
|
/*
* This file can be used to convey information to other eslint files inside
* Canvas.
*/
module.exports = {
globals: {
"ENV": true
},
plugins: [
"promise"
],
// 0 - off, 1 - warning, 2 - error
rules: {
"class-methods-use-this": [0],
"comma-dangle": [2, "only-multiline"],
"func-names": [0],
"max-len": [1, {"code": 140}],
"no-continue": [0],
"no-plusplus": [0],
"no-underscore-dangle": [0],
"no-unused-vars": [2, { "argsIgnorePattern": "^_"}],
"object-curly-spacing": [0],
"semi": [0],
"space-before-function-paren": [2, "always"],
// allows 'i18n!webzip_exports' and 'compiled/foo/bar'
"import/no-extraneous-dependencies": [0],
"import/named": [2],
"import/no-unresolved": [0],
"import/no-webpack-loader-syntax": [0],
"import/extensions": [1, { "js": "never", "jsx": "never", "json": "always" }],
"promise/avoid-new": [0],
}
};
|
/*
* This file can be used to convey information to other eslint files inside
* Canvas.
*/
module.exports = {
globals: {
"ENV": true
},
plugins: [
"promise"
],
// 0 - off, 1 - warning, 2 - error
rules: {
"class-methods-use-this": [0],
"comma-dangle": [2, "only-multiline"],
"func-names": [0],
"max-len": [1, {"code": 140}],
"no-continue": [0],
"no-plusplus": [0],
"no-underscore-dangle": [0],
"no-unused-vars": [2, { "argsIgnorePattern": "^_"}],
"object-curly-spacing": [0],
"semi": [0],
"space-before-function-paren": [2, "always"],
"import/no-amd": [0],
// allows 'i18n!webzip_exports' and 'compiled/foo/bar'
"import/no-extraneous-dependencies": [0],
"import/named": [2],
"import/no-unresolved": [0],
"import/no-webpack-loader-syntax": [0],
"import/extensions": [1, { "js": "never", "jsx": "never", "json": "always" }],
"promise/avoid-new": [0],
}
};
|
Test execution: Remove unneeded variable
|
#! /bin/python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
from coalib.tests.TestHelper import TestHelper
def show_help():
print("Usage: {name} [OPTIONS]".format(name=sys.argv[0]))
print()
print("--help : Show this help text")
print("--cover : Use coverage to get statement and branch coverage of tests")
if __name__ == '__main__':
use_coverage = False
for arg in sys.argv[1:]:
arg = str(arg).strip().lower()
if arg == "--cover" and not use_coverage:
use_coverage = True
else:
show_help()
exit()
files = TestHelper.get_test_files(os.path.abspath("coalib/tests"))
exit(TestHelper.execute_python3_files(files, use_coverage))
|
#! /bin/python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
from coalib.tests.TestHelper import TestHelper
def show_help():
print("Usage: {name} [OPTIONS]".format(name=sys.argv[0]))
print()
print("--help : Show this help text")
print("--cover : Use coverage to get statement and branch coverage of tests")
if __name__ == '__main__':
use_coverage = False
for arg in sys.argv[1:]:
arg = str(arg).strip().lower()
if arg == "--cover" and not use_coverage:
use_coverage = True
else:
show_help()
exit()
test_dir = os.path.abspath("coalib/tests")
files = TestHelper.get_test_files(test_dir)
exit(TestHelper.execute_python3_files(files, use_coverage))
|
Change module path for cluster evaluation and edit how to get original logs
|
# for local run, before pygraphc packaging
import sys
sys.path.insert(0, '../pygraphc/misc')
from LKE import *
sys.path.insert(0, '../pygraphc/evaluation')
from ExternalEvaluation import *
ip_address = '161.166.232.17'
standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address
standard_file = standard_path + 'auth.log.anon.labeled'
analyzed_file = 'auth.log.anon'
prediction_file = 'lke-result-' + ip_address + '.txt'
OutputPath = './results'
para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath)
myparser = LKE(para)
time = myparser.main_process()
clusters = myparser.get_clusters()
original_logs = myparser.logs
ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file)
homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file,
prediction_file)
print homogeneity_completeness_vmeasure
print ('The running time of LKE is', time)
|
# for local run, before pygraphc packaging
import sys
sys.path.insert(0, '../pygraphc/misc')
from LKE import *
sys.path.insert(0, '../pygraphc/clustering')
from ClusterUtility import *
from ClusterEvaluation import *
ip_address = '161.166.232.17'
standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address
standard_file = standard_path + 'auth.log.anon.labeled'
analyzed_file = 'auth.log.anon'
prediction_file = 'lke-result-' + ip_address + '.txt'
OutputPath = './results'
para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath)
myparser = LKE(para)
time = myparser.main_process()
clusters = myparser.get_clusters()
original_logs = myparser.get_logs()
ClusterUtility.set_cluster_label_id(None, clusters, original_logs, prediction_file)
homogeneity_completeness_vmeasure = ClusterEvaluation.get_homogeneity_completeness_vmeasure(standard_file,
prediction_file)
print homogeneity_completeness_vmeasure
print ('The running time of LKE is', time)
|
Update webhook handler example to use `http.MaxBytesReader`
Updates the webhook handler example to use `http.MaxBytesReader` to
protect against a malicious client streaming an endless request body.
We're making a similar change in our server side documentation examples,
so I'm updating this spot as well for consistency.
|
package webhook_test
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/stripe/stripe-go/webhook"
)
func Example() {
http.HandleFunc("/webhook", func(w http.ResponseWriter, req *http.Request) {
// Protects against a malicious client streaming us an endless requst
// body
const MaxBodyBytes = int64(65536)
req.Body = http.MaxBytesReader(w, req.Body, MaxBodyBytes)
body, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Pass the request body & Stripe-Signature header to ConstructEvent, along with the webhook signing key
event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), "whsec_DaLRHCRs35vEXqOE8uTEAXGLGUOnyaFf")
if err != nil {
w.WriteHeader(http.StatusBadRequest) // Return a 400 error on a bad signature
fmt.Fprintf(w, "%v", err)
return
}
fmt.Fprintf(w, "Received signed event: %v", event)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
|
package webhook_test
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/stripe/stripe-go/webhook"
)
func Example() {
http.HandleFunc("/webhook", func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Pass the request body & Stripe-Signature header to ConstructEvent, along with the webhook signing key
event, err := webhook.ConstructEvent(body, req.Header.Get("Stripe-Signature"), "whsec_DaLRHCRs35vEXqOE8uTEAXGLGUOnyaFf")
if err != nil {
w.WriteHeader(http.StatusBadRequest) // Return a 400 error on a bad signature
fmt.Fprintf(w, "%v", err)
return
}
fmt.Fprintf(w, "Received signed event: %v", event)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
|
Update collect ini script. Now it shows if field is required.
|
"""
collect information about fields and values in ini file
usage run script with file name in directory with unpacked stats.
Script will collect data from all files with name.
You can specify path as second argument.
python get_ini_fields.py body.ini
python get_ini_fields.py body.ini "C:/games/warzone2100"
"""
import os
import sys
from config_parser import WZConfigParser
def get_ini_fields(fields, path):
cp = WZConfigParser()
cp.load(path)
for section in cp.sections():
for key, value in cp.items(section):
fields.setdefault(key, []).append(value)
if __name__ == "__main__":
name = sys.argv[1]
path = sys.argv[2]
fields = {}
for base, dirs, files in os.walk(path):
if name in files:
file_path = os.path.join(base, name)
get_ini_fields(fields, file_path)
print "collectiong data from", file_path
max_size = max(map(len, fields.values()))
for field, values in fields.items():
print field, "requires=%s" % (len(values) == max_size), "values:", ', '.join('"%s"' % x for x in sorted(set(values)))
|
"""
collect information about fields and values in ini file
usage run script with file name in directory with unpacked stats.
Script will collect data from all files with name.
You can specify path as second argument.
python get_ini_fields.py body.ini
python get_ini_fields.py body.ini "C:/games/warzone2100"
"""
import os
import sys
from config_parser import WZConfigParser
def get_ini_fields(fields, path):
cp = WZConfigParser()
cp.load(path)
for section in cp.sections():
for key, value in cp.items(section):
fields.setdefault(key, set()).add(value)
if __name__ == "__main__":
name = sys.argv[1]
path = sys.argv[2]
fields = {}
for base, dirs, files in os.walk(path):
if name in files:
file_path = os.path.join(base, name)
get_ini_fields(fields, file_path)
print "collectiong data from", file_path
for field, values in fields.items():
print field, ' '.join(sorted(values))
|
Make this slightly less as simple as possible
|
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util\Metadata;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class AttributeReader implements Reader
{
/**
* @psalm-param class-string $className
*/
public function forClass(string $className): MetadataCollection
{
$result = [];
return MetadataCollection::fromArray($result);
}
/**
* @psalm-param class-string $className
*/
public function forMethod(string $className, string $methodName): MetadataCollection
{
$result = [];
return MetadataCollection::fromArray($result);
}
}
|
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util\Metadata;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class AttributeReader implements Reader
{
/**
* @psalm-param class-string $className
*/
public function forClass(string $className): MetadataCollection
{
return MetadataCollection::fromArray([]);
}
/**
* @psalm-param class-string $className
*/
public function forMethod(string $className, string $methodName): MetadataCollection
{
return MetadataCollection::fromArray([]);
}
}
|
Increase HTTP request limit to allow for larger imports
|
/*
* Biodiversity Heritage Library
* A backend for collecting OCR corrections from BHL games.
* Copyright 2015 Tiltfactor
*/
(function() {
global.requireLocal = function(name) {
return require(__dirname + '/' + name);
};
})();
var express = require('express');
var bodyParser = require('body-parser');
var http = require('http');
var cors = require('cors');
var mongoose = require('mongoose');
var config = requireLocal('config/config.js');
var PORT = process.env.PORT || config.ServerPort || 8081;
var app = express();
/** Connect to our database */
mongoose.connect(config.developmentDB);
/** Allow cross domain requests */
app.use(cors());
/** Initialize our routing logic */
var router = express.Router();
requireLocal('routes')(router);
/** Allows us to parse body and query parameters */
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json({limit: '1mb'}));
/** Remove the 'Powered by Express' header. */
app.disable('x-powered-by');
/** Set the root of our routes to be /api */
app.use('/api', router);
app.get('/', function(req, res) {
/** Will eventually send a better message */
res.send('Hello did you get lost?');
});
http.createServer(app).listen(PORT, function() {
console.log('Started on:', PORT);
});
|
/*
* Biodiversity Heritage Library
* A backend for collecting OCR corrections from BHL games.
* Copyright 2015 Tiltfactor
*/
(function() {
global.requireLocal = function(name) {
return require(__dirname + '/' + name);
};
})();
var express = require('express');
var bodyParser = require('body-parser');
var http = require('http');
var cors = require('cors');
var mongoose = require('mongoose');
var config = requireLocal('config/config.js');
var PORT = process.env.PORT || config.ServerPort || 8081;
var app = express();
/** Connect to our database */
mongoose.connect(config.developmentDB);
/** Allow cross domain requests */
app.use(cors());
/** Initialize our routing logic */
var router = express.Router();
requireLocal('routes')(router);
/** Allows us to parse body and query parameters */
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
/** Remove the 'Powered by Express' header. */
app.disable('x-powered-by');
/** Set the root of our routes to be /api */
app.use('/api', router);
app.get('/', function(req, res) {
/** Will eventually send a better message */
res.send('Hello did you get lost?');
});
http.createServer(app).listen(PORT, function() {
console.log('Started on:', PORT);
});
|
Remove name field from form
|
from django import forms
from .models import get_application_model
class AllowForm(forms.Form):
allow = forms.BooleanField(required=False)
redirect_uri = forms.CharField(widget=forms.HiddenInput())
scope = forms.CharField(required=False, widget=forms.HiddenInput())
client_id = forms.CharField(widget=forms.HiddenInput())
state = forms.CharField(required=False, widget=forms.HiddenInput())
response_type = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
data = kwargs.get('data')
# backwards compatible support for plural `scopes` query parameter
if data and 'scopes' in data:
data['scope'] = data['scopes']
return super(AllowForm, self).__init__(*args, **kwargs)
class RegistrationForm(forms.ModelForm):
"""
TODO: add docstring
"""
class Meta:
model = get_application_model()
fields = ('client_id', 'client_secret', 'client_type', 'authorization_grant_type', 'redirect_uris')
|
from django import forms
from .models import get_application_model
class AllowForm(forms.Form):
allow = forms.BooleanField(required=False)
redirect_uri = forms.CharField(widget=forms.HiddenInput())
scope = forms.CharField(required=False, widget=forms.HiddenInput())
client_id = forms.CharField(widget=forms.HiddenInput())
state = forms.CharField(required=False, widget=forms.HiddenInput())
response_type = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
data = kwargs.get('data')
# backwards compatible support for plural `scopes` query parameter
if data and 'scopes' in data:
data['scope'] = data['scopes']
return super(AllowForm, self).__init__(*args, **kwargs)
class RegistrationForm(forms.ModelForm):
"""
TODO: add docstring
"""
class Meta:
model = get_application_model()
fields = ('name', 'client_id', 'client_secret', 'client_type', 'authorization_grant_type', 'redirect_uris')
|
Increase debounce for settings input
|
import { h, Component } from 'preact';
import style from './style';
function debounce(fn, delay) {
let timer = null;
return function () {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
export default class Settings extends Component {
handleInput(e) {
const value = e.target.value;
this.props.changeUsername(value);
}
render() {
return (
<div class={style.page}>
<h1 class={style.title}>Settings</h1>
<label>Username</label>
<input type="text"
placeholder="zaccolley"
value={this.props.username}
onInput={debounce(this.handleInput.bind(this), 500)} />
</div>
);
}
}
|
import { h, Component } from 'preact';
import style from './style';
function debounce(fn, delay) {
let timer = null;
return function () {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
export default class Settings extends Component {
handleInput(e) {
const value = e.target.value;
this.props.changeUsername(value);
}
render() {
return (
<div class={style.page}>
<h1 class={style.title}>Settings</h1>
<label>Username</label>
<input type="text"
placeholder="zaccolley"
value={this.props.username}
onInput={debounce(this.handleInput.bind(this), 200)} />
</div>
);
}
}
|
Add data method to model
|
var Obstruct = require('obstruct');
var minivents = require('minivents');
var createGetter = require('./lib/createGet');
var createSetter = require('./lib/createSet');
var merge = require('./lib/merge');
var noop = function () {};
var Model = Obstruct.extend({
constructor: function (data) {
minivents(this);
data = merge({}, this.defaults, data || {});
var _attr = {};
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
_attr[prop] = data[prop];
Object.defineProperty(this, prop, {
get: createGetter(_attr, prop),
set: createSetter(_attr, prop, this)
});
}
}
this.init(data);
},
data: function () {
var data = {};
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
if (typeof this[prop] !== 'function') {
data[prop] = this[prop];
}
}
}
},
init: noop,
defaults: {}
});
module.exports = Model;
|
var Obstruct = require('obstruct');
var minivents = require('minivents');
var createGetter = require('./lib/createGet');
var createSetter = require('./lib/createSet');
var merge = require('./lib/merge');
var noop = function () {};
var Model = Obstruct.extend({
constructor: function (data) {
minivents(this);
data = merge({}, this.defaults, data || {});
var _attr = {};
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
_attr[prop] = data[prop];
Object.defineProperty(this, prop, {
get: createGetter(_attr, prop),
set: createSetter(_attr, prop, this)
});
}
}
this.init(data);
},
init: noop,
defaults: {}
});
module.exports = Model;
|
Change to predict 'on demand'
|
// Entry point of the application
var parser = require('./parser');
var Renderer = require('./renderer');
var Interpreter = require('./interpreter');
var Predictor = require('./predictor');
var interpreter;
var renderer;
var predictor;
window.onload = function() {
var code = document.getElementById('source').innerHTML;
interpreter = new Interpreter(code);
var predictQuota = interpreter.map.width * interpreter.map.height * 2;
predictor = new Predictor(interpreter.map);
for(var i = 0; i < predictQuota; ++i) {
if(!predictor.next()) break;
}
predictor.updated = [];
renderer = new Renderer(document.getElementById('viewport'), interpreter);
setInterval(function() {
renderer.preNext();
interpreter.next();
// Predict
predictor.stack = [{
segment: predictor.segments.length,
x: interpreter.state.x,
y: interpreter.state.y,
direction: {
x: interpreter.state.direction.x,
y: interpreter.state.direction.y
}
}];
predictor.segments.push([]);
for(var i = 0; i < predictQuota; ++i) {
if(!predictor.next()) break;
}
interpreter.updated = interpreter.updated.concat(predictor.updated);
predictor.updated = [];
renderer.postNext();
}, 1000);
window.interpreter = interpreter;
}
|
// Entry point of the application
var parser = require('./parser');
var Renderer = require('./renderer');
var Interpreter = require('./interpreter');
var Predictor = require('./predictor');
var interpreter;
var renderer;
window.onload = function() {
var code = document.getElementById('source').innerHTML;
interpreter = new Interpreter(code);
var predictQuota = interpreter.map.width * interpreter.map.height * 2;
var predictor = new Predictor(interpreter.map);
for(var i = 0; i < predictQuota; ++i) {
if(!predictor.next()) break;
predictor.updated = [];
}
renderer = new Renderer(document.getElementById('viewport'), interpreter);
setInterval(function() {
renderer.preNext();
interpreter.next();
renderer.postNext();
}, 20);
window.interpreter = interpreter;
}
|
Fix brittle TFLite Java version test
Mirror the native TF test for version checking.
PiperOrigin-RevId: 305948727
Change-Id: I18169d0a1b6b0deaefed7984237ea76481c2c59b
|
/* Copyright 2017 The TensorFlow 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.
==============================================================================*/
package org.tensorflow.lite;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link org.tensorflow.lite.TensorFlowLite}. */
@RunWith(JUnit4.class)
public final class TensorFlowLiteTest {
@Test
@SuppressWarnings("deprecation")
public void testVersion() {
assertThat(TensorFlowLite.version()).isEqualTo("3");
}
@Test
public void testSchemaVersion() {
assertThat(TensorFlowLite.schemaVersion()).isEqualTo("3");
}
@Test
public void testRuntimeVersion() {
// Unlike the schema version, which should almost never change, the runtime version can change
// with some frequency, so simply ensure that it's non-empty and doesn't fail.
assertThat(TensorFlowLite.runtimeVersion()).isNotEmpty();
}
}
|
/* Copyright 2017 The TensorFlow 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.
==============================================================================*/
package org.tensorflow.lite;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link org.tensorflow.lite.TensorFlowLite}. */
@RunWith(JUnit4.class)
public final class TensorFlowLiteTest {
@Test
@SuppressWarnings("deprecation")
public void testVersion() {
assertThat(TensorFlowLite.version()).isEqualTo("3");
}
@Test
public void testSchemaVersion() {
assertThat(TensorFlowLite.schemaVersion()).isEqualTo("3");
}
@Test
public void testRuntimeVersion() {
assertThat(TensorFlowLite.runtimeVersion()).startsWith("1.");
}
}
|
Add comments and validation to create msg
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request.channel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;
import javax.validation.constraints.Size;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class CreateMessageRequest {
/**
* The message contents (up to 2000 characters).
*/
@Size(min = 1, max = 2000)
private String content;
/**
* A nonce that can be used for optimistic message sending.
*/
private String nonce;
/**
* If this is a TTS message.
*/
private boolean tts;
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.request.channel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class CreateMessageRequest {
private String content;
private String nonce;
private boolean tts;
}
|
Fix template name reference (zfcuser/login -> zfc-user/user/login)
|
<?php
namespace ZfcUser\View\Helper;
use Zend\View\Helper\AbstractHelper,
ZfcUser\Form\Login as LoginForm,
Zend\View\Model\ViewModel;
class ZfcUserLoginWidget extends AbstractHelper
{
/**
* Login Form
* @var LoginForm
*/
protected $loginForm;
/**
* __invoke
*
* @access public
* @return string
*/
public function __invoke()
{
$vm = new ViewModel(array(
'loginForm' => $this->getLoginForm()
));
$vm->setTemplate('zfc-user/user/login');
//@TODO Return ViewModel instead, and let consumer do render?
return $this->getView()->render($vm);
}
/**
* Retrieve Login Form Object
* @return LoginForm
*/
public function getLoginForm()
{
return $this->loginForm;
}
/**
* Inject Login Form Object
* @param LoginForm $loginForm
* @return ZfcUserLoginWidget
*/
public function setLoginForm(LoginForm $loginForm)
{
$this->loginForm = $loginForm;
return $this;
}
}
|
<?php
namespace ZfcUser\View\Helper;
use Zend\View\Helper\AbstractHelper,
ZfcUser\Form\Login as LoginForm,
Zend\View\Model\ViewModel;
class ZfcUserLoginWidget extends AbstractHelper
{
/**
* Login Form
* @var LoginForm
*/
protected $loginForm;
/**
* __invoke
*
* @access public
* @return string
*/
public function __invoke()
{
$vm = new ViewModel(array(
'loginForm' => $this->getLoginForm()
));
$vm->setTemplate('zfcuser/login');
//@TODO Return ViewModel instead, and let consumer do render?
return $this->getView()->render($vm);
}
/**
* Retrieve Login Form Object
* @return LoginForm
*/
public function getLoginForm()
{
return $this->loginForm;
}
/**
* Inject Login Form Object
* @param LoginForm $loginForm
* @return ZfcUserLoginWidget
*/
public function setLoginForm(LoginForm $loginForm)
{
$this->loginForm = $loginForm;
return $this;
}
}
|
Add site footer to each documentation generator
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-images/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-images/tachyons-images.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_images.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/images/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/general/images/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-images/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-images/tachyons-images.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_images.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/images/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/general/images/index.html', html)
|
Add jquery to global require
|
(function() {
'use strict';
require.config({
baseUrl: "..",
paths: {
'jasmine': 'test/lib/jasmine-2.0.0/jasmine',
'jasmine-html': 'test/lib/jasmine-2.0.0/jasmine-html',
'boot': 'test/lib/jasmine-2.0.0/boot',
'jquery': 'lib/jquery-2.1.0.min',
'd3': 'lib/d3.v3.min',
'alertify': 'lib/alertify.min'
},
shim: {
'jasmine': {
exports: 'jasmine'
},
'jasmine-html': {
deps: ['jasmine'],
exports: 'jasmine'
},
'boot': {
deps: ['jasmine-html'],
exports: 'jasmine'
}
}
});
var specs = [
'test/spec/background_spec',
'test/spec/content_spec',
'test/spec/history_spec',
'test/spec/tree_spec'
];
require(['boot', 'jquery'], function() {
require(specs, function() {
window.onload();
});
});
})();
|
(function() {
'use strict';
require.config({
baseUrl: "..",
paths: {
'jasmine': 'test/lib/jasmine-2.0.0/jasmine',
'jasmine-html': 'test/lib/jasmine-2.0.0/jasmine-html',
'boot': 'test/lib/jasmine-2.0.0/boot',
'jquery': 'lib/jquery-2.1.0.min',
'd3': 'lib/d3.v3.min',
'alertify': 'lib/alertify.min'
},
shim: {
'jasmine': {
exports: 'jasmine'
},
'jasmine-html': {
deps: ['jasmine'],
exports: 'jasmine'
},
'boot': {
deps: ['jasmine-html'],
exports: 'jasmine'
}
}
});
var specs = [
'test/spec/background_spec',
'test/spec/content_spec',
'test/spec/history_spec',
'test/spec/tree_spec'
];
require(['boot'], function() {
require(specs, function() {
window.onload();
});
});
})();
|
Fix use regions cancelling interaction with blocks
|
package in.twizmwaz.cardinal.module.modules.appliedRegion.type;
import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.regions.RegionModule;
import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion;
import in.twizmwaz.cardinal.util.ChatUtils;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class UseRegion extends AppliedRegion {
public UseRegion(RegionModule region, FilterModule filter, String message) {
super(region, filter, message);
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getClickedBlock() == null || (event.getItem() != null && event.getItem().getType().isBlock())) return;
if (region.contains(new BlockRegion(null, event.getClickedBlock().getLocation().toVector())) && (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) && filter.evaluate(event.getPlayer(), event.getClickedBlock(), event).equals(FilterState.DENY)) {
event.setCancelled(true);
ChatUtils.sendWarningMessage(event.getPlayer(), message);
}
}
}
|
package in.twizmwaz.cardinal.module.modules.appliedRegion.type;
import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.regions.RegionModule;
import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion;
import in.twizmwaz.cardinal.util.ChatUtils;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class UseRegion extends AppliedRegion {
public UseRegion(RegionModule region, FilterModule filter, String message) {
super(region, filter, message);
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getClickedBlock() == null) return;
if (region.contains(new BlockRegion(null, event.getClickedBlock().getLocation().toVector())) && (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) && filter.evaluate(event.getPlayer(), event.getClickedBlock(), event).equals(FilterState.DENY)) {
event.setCancelled(true);
ChatUtils.sendWarningMessage(event.getPlayer(), message);
}
}
}
|
Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
|
from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
|
from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
|
Correct key for revision in tool playbook parser
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
import yaml
def get_revision_number(yaml_content, tool_name):
for tool in yaml_content['tools']:
if tool["name"] == tool_name:
if tool.has_key("revisions"):
print tool["revisions"][0]
def get_owner(yaml_content, tool_name):
for tool in yaml_content['tools']:
if tool["name"] == tool_name:
print tool['owner']
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--file', required=True)
parser.add_argument('--tool_name', required=True)
parser.add_argument('--tool_function', required=True)
args = parser.parse_args()
with open(args.file,'r') as yaml_file:
yaml_content = yaml.load(yaml_file)
functions = {
'get_revision_number': get_revision_number,
'get_owner': get_owner
}
functions[args.tool_function](yaml_content, args.tool_name)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
import yaml
def get_revision_number(yaml_content, tool_name):
for tool in yaml_content['tools']:
if tool["name"] == tool_name:
if tool.has_key("revision"):
print tool["revision"][0]
def get_owner(yaml_content, tool_name):
for tool in yaml_content['tools']:
if tool["name"] == tool_name:
print tool['owner']
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--file', required=True)
parser.add_argument('--tool_name', required=True)
parser.add_argument('--tool_function', required=True)
args = parser.parse_args()
with open(args.file,'r') as yaml_file:
yaml_content = yaml.load(yaml_file)
functions = {
'get_revision_number': get_revision_number,
'get_owner': get_owner
}
functions[args.tool_function](yaml_content, args.tool_name)
|
Disable caching for CMS plugin.
CSRF tokens may get cached otherwise.
This is for compatibility with Django CMS 3.0+.
|
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition
from form_designer.views import process_form
from form_designer import settings
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext as _
class FormDesignerPlugin(CMSPluginBase):
model = CMSFormDefinition
module = _('Form Designer')
name = _('Form')
admin_preview = False
render_template = False
cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html
def render(self, context, instance, placeholder):
if instance.form_definition.form_template_name:
self.render_template = instance.form_definition.form_template_name
else:
self.render_template = settings.DEFAULT_FORM_TEMPLATE
# Redirection does not work with CMS plugin, hence disable:
return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False)
plugin_pool.register_plugin(FormDesignerPlugin)
|
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition
from form_designer.views import process_form
from form_designer import settings
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext as _
class FormDesignerPlugin(CMSPluginBase):
model = CMSFormDefinition
module = _('Form Designer')
name = _('Form')
admin_preview = False
render_template = False
def render(self, context, instance, placeholder):
if instance.form_definition.form_template_name:
self.render_template = instance.form_definition.form_template_name
else:
self.render_template = settings.DEFAULT_FORM_TEMPLATE
# Redirection does not work with CMS plugin, hence disable:
return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False)
plugin_pool.register_plugin(FormDesignerPlugin)
|
Delete wrong attributes of 'cols' and 'rows' (these are for texture).
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zip Address Util</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
</head>
<body>
<h1>Zip Address Util</h1>
<form name="search_form" method="get" action="/address/result">
<button>検索</button>
</form>
<div id="result">
<?php if (isset($results)) {
foreach ($results as $addr) {
/** @var App\Models\Address $addr */
echo '<div><span>' . $addr->getWholeAddress() . '</span></div>';
}
} ?>
<input type="text" name="search" title="search" id="search"
value=<?php
/** @var string $searchWord */
if (isset($searchWord)) {
echo $searchWord;
} ?>
>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zip Address Util</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
</head>
<body>
<h1>Zip Address Util</h1>
<form name="search_form" method="get" action="/address/result">
<button>検索</button>
</form>
<div id="result">
<?php if (isset($results)) {
foreach ($results as $addr) {
/** @var App\Models\Address $addr */
echo '<div><span>' . $addr->getWholeAddress() . '</span></div>';
}
} ?>
<input type="text" name="search" title="search" id="search" cols="30" rows="10"
value=<?php
/** @var string $searchWord */
if (isset($searchWord)) {
echo $searchWord;
} ?>
>
</div>
</body>
</html>
|
Use CourseOverview instead of modulestore.
|
""" Signal handler for enabling self-generated certificates by default
for self-paced courses.
"""
from celery.task import task
from django.dispatch.dispatcher import receiver
from certificates.models import CertificateGenerationCourseSetting
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from xmodule.modulestore.django import SignalHandler
@receiver(SignalHandler.course_published)
def _listen_for_course_publish(sender, course_key, **kwargs): # pylint: disable=unused-argument
""" Catches the signal that a course has been published in Studio and
enable the self-generated certificates by default for self-paced
courses.
"""
enable_self_generated_certs.delay(unicode(course_key))
@task()
def enable_self_generated_certs(course_key):
"""Enable the self-generated certificates by default for self-paced courses."""
course_key = CourseKey.from_string(course_key)
course = CourseOverview.get_from_id(course_key)
is_enabled_for_course = CertificateGenerationCourseSetting.is_enabled_for_course(course_key)
if course.self_paced and not is_enabled_for_course:
CertificateGenerationCourseSetting.set_enabled_for_course(course_key, True)
|
""" Signal handler for enabling self-generated certificates by default
for self-paced courses.
"""
from celery.task import task
from django.dispatch.dispatcher import receiver
from certificates.models import CertificateGenerationCourseSetting
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import SignalHandler, modulestore
@receiver(SignalHandler.course_published)
def _listen_for_course_publish(sender, course_key, **kwargs): # pylint: disable=unused-argument
""" Catches the signal that a course has been published in Studio and
enable the self-generated certificates by default for self-paced
courses.
"""
enable_self_generated_certs.delay(unicode(course_key))
@task()
def enable_self_generated_certs(course_key):
"""Enable the self-generated certificates by default for self-paced courses."""
course_key = CourseKey.from_string(course_key)
course = modulestore().get_course(course_key)
is_enabled_for_course = CertificateGenerationCourseSetting.is_enabled_for_course(course_key)
if course.self_paced and not is_enabled_for_course:
CertificateGenerationCourseSetting.set_enabled_for_course(course_key, True)
|
Remove attempts to force corrections on the gradient.
|
<?php
declare(strict_types=1);
namespace mcordingley\Regression\Linkings;
use InvalidArgumentException;
use mcordingley\Regression\Helpers;
final class Logistic extends Linking
{
public function delinearize(float $value): float
{
return 1.0 / (1.0 + exp(-$value));
}
public function linearize(float $value): float
{
if ($value <= 0 || $value >= 1) {
throw new InvalidArgumentException('Unable to linearize values outside of the range (0, 1).');
}
return -log(1.0 / $value - 1.0);
}
public function loss(array $coefficients, array $observations, float $outcome, int $index): float
{
$hypothesis = $this->delinearize(Helpers::sumProduct($coefficients, $observations));
return -2.0 * ($outcome - $hypothesis) * $hypothesis * (1.0 - $hypothesis) * $observations[$index];
}
}
|
<?php
declare(strict_types=1);
namespace mcordingley\Regression\Linkings;
use InvalidArgumentException;
use mcordingley\Regression\Helpers;
final class Logistic extends Linking
{
public function delinearize(float $value): float
{
return 1.0 / (1.0 + exp(-$value));
}
public function linearize(float $value): float
{
if ($value <= 0 || $value >= 1) {
throw new InvalidArgumentException('Unable to linearize values outside of the range (0, 1).');
}
return -log(1.0 / $value - 1.0);
}
public function loss(array $coefficients, array $observations, float $outcome, int $index): float
{
$hypothesis = $this->delinearize(Helpers::sumProduct($coefficients, $observations));
$error = $outcome - $hypothesis;
// 0.5 will maximize the gradient, since we're on the wrong side.
if ($error < -0.5 || $error > 0.5) {
$hypothesis = 0.5;
}
return -2 * $error * $hypothesis * (1.0 - $hypothesis) * $observations[$index];
}
}
|
Fix checkboxes for Patient Summary.
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from 'react-bootstrap';
const PTCustomCheckbox = ({ title, name, isChecked, disabled = false, onChange }) => {
const toggleCheckbox = () => !disabled && onChange(name);
return <Col xs={6} sm={4}>
<div className="wrap-fcustominp">
<div className={classNames('fcustominp-state', { disabled })} onClick={toggleCheckbox} >
<div className="fcustominp">
<input type="checkbox" id={`dashboard-${name}`} name={`dashboard-${name}`} checked={isChecked} onChange={toggleCheckbox} />
<label htmlFor={`dashboard-${name}`} />
</div>
<label htmlFor={`dashboard-${name}`} className="fcustominp-label">{title}</label>
</div>
</div>
</Col>
}
PTCustomCheckbox.propTypes = {
title: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
isChecked: PropTypes.bool.isRequired,
onChange: PropTypes.func,
disabled: PropTypes.bool,
};
export default PTCustomCheckbox
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Col } from 'react-bootstrap';
const PTCustomCheckbox = ({ title, name, isChecked, disabled = false, onChange }) => {
const toggleCheckbox = () => !disabled && onChange(name);
return <Col xs={6} sm={4}>
<div className="wrap-fcustominp">
<div className={classNames('fcustominp-state', { disabled })} onClick={toggleCheckbox} >
<div className="fcustominp">
<input type="checkbox" name={name} checked={isChecked} onChange={toggleCheckbox} />
<label htmlFor="patients-table-info-name" />
</div>
<label htmlFor={name} className="fcustominp-label">{title}</label>
</div>
</div>
</Col>
}
PTCustomCheckbox.propTypes = {
title: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
isChecked: PropTypes.bool.isRequired,
onChange: PropTypes.func,
disabled: PropTypes.bool,
};
export default PTCustomCheckbox
|
Remove version info from app.
|
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylorotwell@gmail.com>
*/
define('ILLUMINATE_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let's turn on the lights.
| This bootstrap the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight these users.
|
*/
$app = require_once __DIR__.'/../shine.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can simple call the run method,
| which will execute the request and send the response back to
| the client's browser allowing them to enjoy the creative
| this wonderful applications we have created for them.
|
*/
$app->run();
|
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @version 4.0.0
* @author Taylor Otwell <taylorotwell@gmail.com>
*/
define('ILLUMINATE_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let's turn on the lights.
| This bootstrap the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight these users.
|
*/
$app = require_once __DIR__.'/../shine.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can simple call the run method,
| which will execute the request and send the response back to
| the client's browser allowing them to enjoy the creative
| this wonderful applications we have created for them.
|
*/
$app->run();
|
Allow args and kwargs to upload_handler_name
Now can use args and kwargs for reverse url. Example in template:
{% jfu 'core/core_fileuploader.html' 'core_upload' object_id=1 content_type_str='app.model' %}
|
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload',
*args, **kwargs
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name, kwargs=kwargs, args=args ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
|
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload'
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
|
Simplify LogWriter by making it a PassThrough
Allows the use of pipe internally which is safer than wrapping writes
to this.sink.
|
var util = require('util');
var stream = require('stream');
var fs = require('fs');
var generateLogName = require('./logname').generate;
module.exports = LogWriter;
function LogWriter(worker, options) {
if (!(this instanceof LogWriter)) return new LogWriter(worker, options);
stream.PassThrough.call(this);
this.template = options.log;
this.worker = {
id: worker.id || 'supervisor',
pid: worker.pid || worker.process.pid
}
this.name = generateLogName(this.template, this.worker);
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(this.sink);
}
util.inherits(LogWriter, stream.PassThrough);
LogWriter.prototype.reOpen = function LogWriterReOpen() {
if (this.sink instanceof fs.WriteStream) {
this.unpipe(this.sink);
this.sink.end();
// lose our reference to previous stream, but it should clean itself up
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(sink);
}
}
|
var util = require('util');
var stream = require('stream');
var fs = require('fs');
var generateLogName = require('./logname').generate;
module.exports = LogWriter;
function LogWriter(worker, options) {
if (!(this instanceof LogWriter)) return new LogWriter(worker, options);
stream.Writable.call(this);
this.template = options.log;
this.worker = {
id: worker.id || 'supervisor',
pid: worker.pid || worker.process.pid
}
this.name = generateLogName(this.template, this.worker);
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
}
util.inherits(LogWriter, stream.Writable);
LogWriter.prototype.reOpen = function LogWriterReOpen() {
if (this.sink instanceof fs.WriteStream) {
this.sink.end();
// lose our reference to previous stream, but it should clean itself up
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
}
}
LogWriter.prototype._write = function LogWriter_write(chunk, encoding, callback) {
return this.sink.write(chunk, encoding, callback);
}
|
Fix pb in base test class
|
<?php
namespace Neblion\ScrumBundle\Tests;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
abstract class WebTestCase extends BaseWebTestCase
{
protected function login($username, $password)
{
$client = static::createClient();
$crawler = $client->request('GET', '/login');
$form = $crawler->selectButton('Login')->form();
$client->submit($form, array(
'_username' => $username,
'_password' => $password
));
$this->assertEquals(302, $client->getResponse()->getStatusCode());
$client->followRedirect();
return $client;
}
}
|
<?php
namespace Neblion\ScrumBundle\Tests;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
abstract class WebTestCase extends BaseWebTestCase
{
protected function login($username, $password)
{
$client = static::createClient();
$crawler = $client->request('GET', '/login');
$form = $crawler->selectButton('Login')->form();
$client->submit($form, array(
'_username' => $username,
'_password' => $password
));
$this->assertEquals(302, $client->getResponse()->getStatusCode());
$client->followRedirect();
$this->assertEquals(200, $client->getResponse()->getStatusCode());
return $client;
}
}
|
Improve log lines for private/public clones
|
var fs = require('fs');
var gitane = require('gitane');
var winston = require('winston');
function cloneInto(repoUrl, destPath, keyPath, callback) {
var gitClone = function(keyData) {
// clone with . to avoid the extra containing folder
var gitCmd = 'git clone ' + repoUrl + ' .';
// If keyData is truthy, we're using a key to clone a private repo;
// otherwise, we're cloning a public repo and don't need a key
if (keyData) {
winston.log('info', 'Cloning', repoUrl, 'with private key');
} else {
winston.log('info', 'Cloning', repoUrl);
}
winston.log('debug', 'Running git command:', gitCmd);
gitane.run(destPath, keyData, gitCmd, function(err, stdout, stderr, exitCode) {
callback(err, stdout, stderr, exitCode);
});
};
// If there's a key, clone with the key; otherwise, clone with no key
if (keyPath) {
winston.log('debug', 'Using key:', keyPath);
fs.readFile(keyPath, function(err, keyData) {
if (err) { callback(err); return; }
gitClone(keyData);
});
} else {
winston.log('debug', 'No key provided');
gitClone(null);
}
}
module.exports = {
cloneInto: cloneInto
};
|
var fs = require('fs');
var gitane = require('gitane');
var winston = require('winston');
function cloneInto(repoUrl, destPath, keyPath, callback) {
var gitClone = function(keyData) {
// clone with . to avoid the extra containing folder
var gitCmd = 'git clone ' + repoUrl + ' .';
winston.log('info', 'Cloning', repoUrl);
winston.log('debug', 'Running git command:', gitCmd);
gitane.run(destPath, keyData, gitCmd, function(err, stdout, stderr, exitCode) {
callback(err, stdout, stderr, exitCode);
});
};
// If there's a key, clone with the key; otherwise, clone with no key
if (keyPath) {
winston.log('debug', 'Using key:', keyPath);
fs.readFile(keyPath, function(err, keyData) {
if (err) { callback(err); return; }
gitClone(keyData);
});
} else {
winston.log('debug', 'No key provided');
gitClone(null);
}
}
module.exports = {
cloneInto: cloneInto
};
|
Add python 3 trove classifier
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-extra-fields',
version='0.9',
packages=['drf_extra_fields',
'drf_extra_fields.runtests'],
include_package_data=True,
license='License', # example license
description='Additional fields for Django Rest Framework.',
long_description=README,
author='hipo',
author_email='pypi@hipolabs.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-extra-fields',
version='0.9',
packages=['drf_extra_fields',
'drf_extra_fields.runtests'],
include_package_data=True,
license='License', # example license
description='Additional fields for Django Rest Framework.',
long_description=README,
author='hipo',
author_email='pypi@hipolabs.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Use "link" to reference enum literal, fixing javadoc issue.
|
/*******************************************************************************
* Copyright (c) 2018 Red Hat Inc 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:
* Dejan Bosanac - initial implementation
*******************************************************************************/
package org.eclipse.hono.util;
/**
* Utility used to determine type of the endpoint.
*/
public enum EndpointType {
TELEMETRY, EVENT, UNKNOWN;
/**
* Gets the endpoint type from a string value.
*
* @param name The name of the endpoint type.
*
* @return The enum literal of the endpoint type. Returns {@link #UNKNOWN} if it cannot find the endpoint type.
* Never returns {@code null}.
*/
public static EndpointType fromString(String name) {
switch (name) {
case TelemetryConstants.TELEMETRY_ENDPOINT:
case TelemetryConstants.TELEMETRY_ENDPOINT_SHORT:
return TELEMETRY;
case EventConstants.EVENT_ENDPOINT:
case EventConstants.EVENT_ENDPOINT_SHORT:
return EVENT;
default:
return UNKNOWN;
}
}
}
|
/*******************************************************************************
* Copyright (c) 2018 Red Hat Inc 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:
* Dejan Bosanac - initial implementation
*******************************************************************************/
package org.eclipse.hono.util;
/**
* Utility used to determine type of the endpoint.
*/
public enum EndpointType {
TELEMETRY, EVENT, UNKNOWN;
/**
* Gets the endpoint type from a string value.
*
* @param name The name of the endpoint type.
*
* @return The enum literal of the endpoint type. Returns {@value #UNKNOWN} if it cannot find the endpoint type.
* Never returns {@code null}.
*/
public static EndpointType fromString(String name) {
switch (name) {
case TelemetryConstants.TELEMETRY_ENDPOINT:
case TelemetryConstants.TELEMETRY_ENDPOINT_SHORT:
return TELEMETRY;
case EventConstants.EVENT_ENDPOINT:
case EventConstants.EVENT_ENDPOINT_SHORT:
return EVENT;
default:
return UNKNOWN;
}
}
}
|
Fix NPM command that was failing and breaking code
May not handle all cases, but at least it's not broken anymore
|
'use strict';
// is this installed in a node_modules dir?
// is this version not equal to npm latest?
var fs = require('fs');
var colors = require('colors/safe');
var exec = require('child_process').exec;
module.exports = function(callback) {
var cancel = false;
var tid = setTimeout(function(){
cancel = true;
callback();
}, 5000);
exec('npm view --json calvin-network-tools', {},
function (error, stdout, stderr) {
if( cancel ) {
return;
}
clearTimeout(tid);
if( error || stderr ) {
console.log(colors.red('\n** Unable to verify package version **\n'));
return callback();
}
var info = eval('('+stdout+')');
var cInfo = require('../../package.json');
if( info['dist-tags'].latest !== cInfo.version ) {
console.log(colors.yellow('\n**** CNF Update Available ****'));
console.log(colors.yellow('* Your version is '+cInfo.version));
console.log(colors.yellow('* Current version is '+info['dist-tags'].latest));
console.log(colors.yellow('* Run "cnf library update" to update'));
console.log(colors.yellow('******************************\n'));
}
callback();
}
);
};
|
'use strict';
// is this installed in a node_modules dir?
// is this version not equal to npm latest?
var fs = require('fs');
var colors = require('colors/safe');
var exec = require('child_process').exec;
module.exports = function(callback) {
var cancel = false;
var tid = setTimeout(function(){
cancel = true;
callback();
}, 5000);
exec('npm info calvin-network-tools', {},
function (error, stdout, stderr) {
if( cancel ) {
return;
}
clearTimeout(tid);
if( error || stderr ) {
console.log(colors.red('\n** Unable to verify package version **\n'));
return callback();
}
var info = eval('('+stdout+')');
var cInfo = require('../../package.json');
if( info['dist-tags'].latest !== cInfo.version ) {
console.log(colors.yellow('\n**** CNF Update Available ****'));
console.log(colors.yellow('* Your version is '+cInfo.version));
console.log(colors.yellow('* Current version is '+info['dist-tags'].latest));
console.log(colors.yellow('* Run "cnf library update" to update'));
console.log(colors.yellow('******************************\n'));
}
callback();
}
);
};
|
Use findOneAndUpdate for PATCH request so new username will be saved
|
const express = require('express'),
router = express.Router(),
db = require('../models');
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/new', function(req, res, next) {
res.render('users/new');
});
router.get('/:username', function(req, res, next) {
db.User.findOne({username: req.params.username}).then(function(user) {
res.render('users/show', {user});
});
});
router.get('/:username/edit', function(req, res, next) {
db.User.findOne({username: req.params.username}).then(function(user) {
res.render('users/edit', {user});
});
});
router.post('/', function(req, res, next) {
db.User.create(req.body).then(function() {
res.redirect('/');
});
});
// find not by ID and update
router.patch('/:username', function(req, res, next) {
db.User.findOneAndUpdate({username: req.params.username}, {username: req.body.newUsername}).then(function(user) {
res.redirect('/');
});
});
// find and then remove
router.delete('/:username', function(req, res, next) {
db.User.findOneAndRemove({username: req.params.username}).then(function() {
res.redirect('/');
});
});
module.exports = router;
|
const express = require('express'),
router = express.Router(),
db = require('../models');
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/new', function(req, res, next) {
res.render('users/new');
});
router.get('/:username', function(req, res, next) {
db.User.findOne({username: req.params.username}).then(function(user) {
res.render('users/show', {user});
});
});
router.get('/:username/edit', function(req, res, next) {
db.User.findOne({username: req.params.username}).then(function(user) {
res.render('users/edit', {user});
});
});
router.post('/', function(req, res, next) {
db.User.create(req.body).then(function() {
res.redirect('/');
});
});
// find not by ID and update
router.patch('/:username', function(req, res, next) {
db.User.findOne({username: req.params.username}).then(function(user) {
user.username = req.body.newUsername;
res.redirect('/:username');
});
});
// find and then remove
router.delete('/:username', function(req, res, next) {
db.User.findOneAndRemove({username: req.params.username}).then(function() {
res.redirect('/');
});
});
module.exports = router;
|
Update to latest version of trusty-URI
|
package ch.tkuhn.nanopub.validator;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.request.resource.IResource;
import org.nanopub.Nanopub;
import org.nanopub.NanopubUtils;
import org.openrdf.rio.RDFFormat;
import net.trustyuri.rdf.TransformNanopub;
public class DownloadTrustyResource implements IResource {
private static final long serialVersionUID = -4558302923207618223L;
private RDFFormat format;
private ValidatorPage mainPage;
public DownloadTrustyResource(RDFFormat format, ValidatorPage mainPage) {
this.format = format;
this.mainPage = mainPage;
}
@Override
public void respond(Attributes attributes) {
if (mainPage.getNanopub() == null) return;
WebResponse resp = (WebResponse) attributes.getResponse();
resp.setContentType(format.getMIMETypes().get(0));
resp.setAttachmentHeader("nanopub." + format.getDefaultFileExtension());
try {
Nanopub np = mainPage.getNanopub();
Nanopub trustyNp = TransformNanopub.transform(np);
NanopubUtils.writeToStream(trustyNp, resp.getOutputStream(), format);
} catch (Exception ex) {
ex.printStackTrace();
}
resp.close();
}
}
|
package ch.tkuhn.nanopub.validator;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.request.resource.IResource;
import org.nanopub.Nanopub;
import org.nanopub.NanopubUtils;
import org.openrdf.rio.RDFFormat;
import net.trustyuri.rdf.TransformNanopub;
public class DownloadTrustyResource implements IResource {
private static final long serialVersionUID = -4558302923207618223L;
private RDFFormat format;
private ValidatorPage mainPage;
public DownloadTrustyResource(RDFFormat format, ValidatorPage mainPage) {
this.format = format;
this.mainPage = mainPage;
}
@Override
public void respond(Attributes attributes) {
if (mainPage.getNanopub() == null) return;
WebResponse resp = (WebResponse) attributes.getResponse();
resp.setContentType(format.getMIMETypes().get(0));
resp.setAttachmentHeader("nanopub." + format.getDefaultFileExtension());
try {
Nanopub np = mainPage.getNanopub();
Nanopub trustyNp = TransformNanopub.transform(np, np.getUri().toString());
NanopubUtils.writeToStream(trustyNp, resp.getOutputStream(), format);
} catch (Exception ex) {
ex.printStackTrace();
}
resp.close();
}
}
|
Fix webpack lodash external require
|
var webpack = require('webpack')
, glob = require('glob').sync
, ExtractTextPlugin = require('extract-text-webpack-plugin');
// Find all the css files but sort the common ones first
var cssFiles = glob('./src/common/**/*.css').concat(glob('./src/!(common)/**/*.css'));
module.exports = {
entry: {
'sir-trevor-blocks.js' : './src/entry.js',
'sir-trevor-blocks.css' : cssFiles
},
output: {
path: __dirname,
filename: '[name]'
},
module: {
loaders: [
{ test: /\.html$/, loader: 'html' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
]
},
plugins: [
new ExtractTextPlugin('[name]'),
],
externals: {
'lodash': '_',
'jquery': 'jQuery',
'sir-trevor-js': 'SirTrevor',
'i18n': 'i18n',
'highlightjs': 'hljs',
'ckeditor': 'CKEDITOR'
}
};
|
var webpack = require('webpack')
, glob = require('glob').sync
, ExtractTextPlugin = require('extract-text-webpack-plugin');
// Find all the css files but sort the common ones first
var cssFiles = glob('./src/common/**/*.css').concat(glob('./src/!(common)/**/*.css'));
module.exports = {
entry: {
'sir-trevor-blocks.js' : './src/entry.js',
'sir-trevor-blocks.css' : cssFiles
},
output: {
path: __dirname,
filename: '[name]'
},
module: {
loaders: [
{ test: /\.html$/, loader: 'html' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
]
},
plugins: [
new ExtractTextPlugin('[name]'),
],
externals: {
'lodash': 'lodash',
'jquery': 'jQuery',
'sir-trevor-js': 'SirTrevor',
'i18n': 'i18n',
'highlightjs': 'hljs',
'ckeditor': 'CKEDITOR'
}
};
|
Add missing license header to js files
|
/*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// Define each block's generated code
Blockly.JavaScript['simple_input_output'] = function(block) {
return ['simple_input_output', Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript['multiple_input_output'] = function(block) {
return ['multiple_input_output', Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript['statement_no_input'] = function(block) {
return 'do something;\n';
};
Blockly.JavaScript['statement_value_input'] = function(block) {
return 'statement_value_input';
};
Blockly.JavaScript['statement_multiple_value_input'] = function(block) {
return 'statement_multiple_value_input';
};
Blockly.JavaScript['statement_statement_input'] = function(block) {
return 'statement_statement_input';
};
Blockly.JavaScript['output_no_input'] = function(block) {
return ['output_no_input', Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript['statement_no_next'] = function(block) {
return 'statement_no_next';
};
|
'use strict';
// Define each block's generated code
Blockly.JavaScript['simple_input_output'] = function(block) {
return ['simple_input_output', Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript['multiple_input_output'] = function(block) {
return ['multiple_input_output', Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript['statement_no_input'] = function(block) {
return 'do something;\n';
};
Blockly.JavaScript['statement_value_input'] = function(block) {
return 'statement_value_input';
};
Blockly.JavaScript['statement_multiple_value_input'] = function(block) {
return 'statement_multiple_value_input';
};
Blockly.JavaScript['statement_statement_input'] = function(block) {
return 'statement_statement_input';
};
Blockly.JavaScript['output_no_input'] = function(block) {
return ['output_no_input', Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript['statement_no_next'] = function(block) {
return 'statement_no_next';
};
|
Remove extra logging that exposed secrets to cloud watch log
|
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var yaml = require('js-yaml');
// const s3EnvVars = require('s3-env-vars');
// var doc = s3EnvVars("mybucketname", "folderpathinbucket", "filename", function(err, data) {
// if(err) console.log(err);
// else console.log(data);
// });
module.exports = function(bucket, path, filename, callback) {
var s3Params = {
Bucket: bucket,
Key: path + "/" + filename
};
s3.getObject(s3Params, function(err, data) {
if (err) callback(err, err.stack); // an error occurred
else {
try {
var doc = yaml.safeLoad(data.Body);
callback(null, doc);
} catch (e) {
callback(err, err.stack); // an error occurred reading the yml file
}
}
});
};
|
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var yaml = require('js-yaml');
// const s3EnvVars = require('s3-env-vars');
// var doc = s3EnvVars("mybucketname", "folderpathinbucket", "filename", function(err, data) {
// if(err) console.log(err);
// else console.log(data);
// });
module.exports = function(bucket, path, filename, callback) {
var s3Params = {
Bucket: bucket,
Key: path + "/" + filename
};
s3.getObject(s3Params, function(err, data) {
if (err) callback(err, err.stack); // an error occurred
else {
try {
console.log('info: ', "Retrieved s3 object.");
var doc = yaml.safeLoad(data.Body);
console.log('data: ', "yml file contents: ", doc);
callback(null, doc);
} catch (e) {
callback(err, err.stack); // an error occurred reading the yml file
}
}
});
};
|
Fix admin URL import in devproject for Django 2.0
For #191
|
from django.conf.urls import include, static, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^flickr/', include('ditto.flickr.urls', namespace='flickr')),
url(r'^lastfm/', include('ditto.lastfm.urls', namespace='lastfm')),
url(r'^pinboard/', include('ditto.pinboard.urls', namespace='pinboard')),
url(r'^twitter/', include('ditto.twitter.urls', namespace='twitter')),
url(r'', include('ditto.core.urls', namespace='ditto')),
]
from django.conf import settings
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += \
static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += \
static.static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
from django.conf.urls import include, static, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^flickr/', include('ditto.flickr.urls', namespace='flickr')),
url(r'^lastfm/', include('ditto.lastfm.urls', namespace='lastfm')),
url(r'^pinboard/', include('ditto.pinboard.urls', namespace='pinboard')),
url(r'^twitter/', include('ditto.twitter.urls', namespace='twitter')),
url(r'', include('ditto.core.urls', namespace='ditto')),
]
from django.conf import settings
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += \
static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += \
static.static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
Add transitionTo stub to solve interaction error
|
import _ from 'lodash';
import React from 'react/addons';
var stubRouterContext = (Component, props, stubs) => {
return React.createClass({
childContextTypes: {
transitionTo: React.PropTypes.func,
getCurrentPath: React.PropTypes.func,
getCurrentRoutes: React.PropTypes.func,
getCurrentPathname: React.PropTypes.func,
getCurrentParams: React.PropTypes.func,
getCurrentQuery: React.PropTypes.func
},
getChildContext: function() {
return _.extend({
transitionTo () {},
getCurrentPath () {},
getCurrentRoutes () {},
getCurrentPathname () {},
getCurrentParams () {},
getCurrentQuery () {}
}, stubs);
},
render: function() {
return <Component ref='stub' {...props} />;
}
});
};
export default stubRouterContext;
|
import _ from 'lodash';
import React from 'react/addons';
var stubRouterContext = (Component, props, stubs) => {
return React.createClass({
childContextTypes: {
getCurrentPath: React.PropTypes.func,
getCurrentRoutes: React.PropTypes.func,
getCurrentPathname: React.PropTypes.func,
getCurrentParams: React.PropTypes.func,
getCurrentQuery: React.PropTypes.func
},
getChildContext: function() {
return _.extend({
getCurrentPath () {},
getCurrentRoutes () {},
getCurrentPathname () {},
getCurrentParams () {},
getCurrentQuery () {}
}, stubs);
},
render: function() {
return <Component ref='stub' {...props} />;
}
});
};
export default stubRouterContext;
|
Add index to user_id on social_identities for speeding up searches with lots of records.
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSocialIdentitiesTable extends Migration
{
/**
* Run the migration.
*
* @return void
*/
public function up()
{
Schema::create('social_identities', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('provider');
$table->string('reference');
$table->text('access_token');
$table->string('expires_at')->nullable();
$table->string('refresh_token')->nullable();
$table->string('confirm_token')->default('');
$table->dateTime('confirm_until')->nullable();
$table->dateTime('confirmed_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migration.
*
* @return void
*/
public function down()
{
Schema::drop('social_identities');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSocialIdentitiesTable extends Migration
{
/**
* Run the migration.
*
* @return void
*/
public function up()
{
Schema::create('social_identities', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('provider');
$table->string('reference');
$table->text('access_token');
$table->string('expires_at')->nullable();
$table->string('refresh_token')->nullable();
$table->string('confirm_token')->default('');
$table->dateTime('confirm_until')->nullable();
$table->dateTime('confirmed_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migration.
*
* @return void
*/
public function down()
{
Schema::drop('social_identities');
}
}
|
Put comment on seperate line
|
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>
// Creates the component instance
/*let component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
|
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>
// Creates the component instance
/*let component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
|
Fix template URL generation (WAL-141)
|
'use strict';
(function() {
angular.module('ncsaas')
.service('invoicesService', ['baseServiceClass', '$http', 'ENV', '$state', invoicesService]);
function invoicesService(baseServiceClass, $http, ENV, $state) {
/*jshint validthis: true */
var ServiceClass = baseServiceClass.extend({
init:function() {
this._super();
this.endpoint = '/invoices/';
},
sendNotification: function(invoice_uuid) {
var url = ENV.apiEndpoint + 'api' + this.endpoint + invoice_uuid + '/send_notification/';
return $http.post(url, {link_template: this.getTemplateUrl()});
},
getTemplateUrl: function() {
var path = $state.href('organization.invoiceDetails', {invoiceUUID: 'TEMPLATE'});
return location.origin + path.replace('TEMPLATE', '{uuid}');
}
});
return new ServiceClass();
}
})();
|
'use strict';
(function() {
angular.module('ncsaas')
.service('invoicesService', ['baseServiceClass', '$http', 'ENV', '$state', invoicesService]);
function invoicesService(baseServiceClass, $http, ENV, $state) {
/*jshint validthis: true */
var ServiceClass = baseServiceClass.extend({
init:function() {
this._super();
this.endpoint = '/invoices/';
},
sendNotification: function(invoice_uuid) {
var url = ENV.apiEndpoint + 'api' + this.endpoint + invoice_uuid + '/send_notification/';
return $http.post(url, {link_template: this.getTemplateUrl()});
},
getTemplateUrl: function() {
var path = $state.href('organization.invoiceDetails', {uuid: 'TEMPLATE'});
return location.origin + path.replace('TEMPLATE', '{uuid}');
}
});
return new ServiceClass();
}
})();
|
Use ?: instead of ??
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php
namespace Orchestra\Database\Console\Migrations;
trait Packages
{
/**
* The path to the packages directory (vendor).
*
* @var string
*/
protected $packagePath;
/**
* Set package path.
*
* @param string $packagePath
*
* @return $this
*/
public function setPackagePath($packagePath)
{
$this->packagePath = $packagePath;
return $this;
}
/**
* Get the path to the package migration directory.
*
* @param string $package
*
* @return array
*/
protected function getPackageMigrationPaths($package)
{
return collect($this->option('path') ?: 'resources/migrations')
->map(function ($path) use ($package) {
return $this->packagePath.'/'.$package.'/'.$path;
})->all();
}
}
|
<?php
namespace Orchestra\Database\Console\Migrations;
trait Packages
{
/**
* The path to the packages directory (vendor).
*
* @var string
*/
protected $packagePath;
/**
* Set package path.
*
* @param string $packagePath
*
* @return $this
*/
public function setPackagePath($packagePath)
{
$this->packagePath = $packagePath;
return $this;
}
/**
* Get the path to the package migration directory.
*
* @param string $package
*
* @return array
*/
protected function getPackageMigrationPaths($package)
{
return collect($this->option('path') ?? 'resources/migrations')
->map(function ($path) use ($package) {
return $this->packagePath.'/'.$package.'/'.$path;
})->all();
}
}
|
Add slash if not present
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.xcodeml.xnode;
import org.w3c.dom.Document;
/**
* The Xmod represents the module information produced by the Fortran front-end
* of OMNI Compiler.
*
* @author clementval
*/
public class Xmod extends XcodeML {
// Xmod inner elements
private final String _path;
private final String _name;
private final XtypeTable _typeTable;
/**
* Constructs a basic Xmod object representing the XcodeML module file given
* in input.
* @param baseElement XcodeML document.
* @param name Name of the module.
* @param path Path of the XcodeML module file without the filename.
*/
public Xmod(Document baseElement, String name, String path){
super(baseElement);
_typeTable = new XtypeTable(find(Xcode.TYPETABLE).getElement());
_name = name;
_path = path.endsWith("/") ? path : path + "/";
}
/**
* Get the type table of the Xmod module.
* @return The types table.
*/
public XtypeTable getTypeTable(){
return _typeTable;
}
/**
* Get the path associated with this XcodeML module.
* @return Path of the module file.
*/
public String getPath(){
return _path;
}
/**
* Get the name of the module.
* @return Name of the module.
*/
public String getName() {
return _name;
}
}
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.xcodeml.xnode;
import org.w3c.dom.Document;
/**
* The Xmod represents the module information produced by the Fortran front-end
* of OMNI Compiler.
*
* @author clementval
*/
public class Xmod extends XcodeML {
// Xmod inner elements
private final String _path;
private final String _name;
private final XtypeTable _typeTable;
/**
* Constructs a basic Xmod object representing the XcodeML module file given
* in input.
* @param baseElement XcodeML document.
* @param name Name of the module.
* @param path Path of the XcodeML module file without the filename.
*/
public Xmod(Document baseElement, String name, String path){
super(baseElement);
_typeTable = new XtypeTable(find(Xcode.TYPETABLE).getElement());
_name = name;
_path = path;
}
/**
* Get the type table of the Xmod module.
* @return The types table.
*/
public XtypeTable getTypeTable(){
return _typeTable;
}
/**
* Get the path associated with this XcodeML module.
* @return Path of the module file.
*/
public String getPath(){
return _path;
}
/**
* Get the name of the module.
* @return Name of the module.
*/
public String getName() {
return _name;
}
}
|
Update message for error 500
|
import apiConfig from '../../config/api'
import googleConfig from '../../config/google'
function handleErrors (response) {
if (response.status >= 200 && response.status < 300) {
return response // .json()
} else if (response.status === 400) {
throw Error('Le formulaire est incomplet')
// return response.json().then(err => {
// console.log('err', err)
// throw err
// })
} else if (response.status === 500) {
throw Error('Une erreur est survenue')
} else if (!response.ok) {
throw Error(response.statusText)
}
}
export function addExpense (
type,
recipient,
description,
amount,
currency,
date,
proof
) {
const formData = new FormData()
formData.append('gg_spreadsheetId', googleConfig.spreadsheetId)
formData.append('gg_folderId', googleConfig.folderId)
formData.append('type', type)
formData.append('recipient', recipient)
formData.append('description', description)
formData.append('amount', amount)
formData.append('currency', currency)
formData.append('date', date)
formData.append('proof', {
type: 'image/jpeg',
name: 'proof.jpg',
uri: proof
})
return fetch(`${apiConfig.endpoint}/expense`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(handleErrors)
}
|
import apiConfig from '../../config/api'
import googleConfig from '../../config/google'
function handleErrors (response) {
if (response.status >= 200 && response.status < 300) {
return response // .json()
} else if (response.status === 400) {
throw Error('Le formulaire est incomplet')
// return response.json().then(err => {
// console.log('err', err)
// throw err
// })
} else if (!response.ok) {
throw Error(response.statusText)
}
}
export function addExpense (
type,
recipient,
description,
amount,
currency,
date,
proof
) {
const formData = new FormData()
formData.append('gg_spreadsheetId', googleConfig.spreadsheetId)
formData.append('gg_folderId', googleConfig.folderId)
formData.append('type', type)
formData.append('recipient', recipient)
formData.append('description', description)
formData.append('amount', amount)
formData.append('currency', currency)
formData.append('date', date)
formData.append('proof', {
type: 'image/jpeg',
name: 'proof.jpg',
uri: proof
})
return fetch(`${apiConfig.endpoint}/expense`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(handleErrors)
}
|
Return the result of loading module
|
(function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var Module = app.Module || require('./module.js');
var ModuleContainer = helper.inherits(function(props) {
ModuleContainer.super_.call(this);
this.modules = this.prop([]);
this.element = this.prop(props.element);
}, jCore.Component);
ModuleContainer.prototype.loadModule = function(props) {
var module = new Module(props);
this.modules().push(module);
module.parentElement(this.element());
module.redraw();
return module.loadComponent();
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ModuleContainer;
else
app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
|
(function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var Module = app.Module || require('./module.js');
var ModuleContainer = helper.inherits(function(props) {
ModuleContainer.super_.call(this);
this.modules = this.prop([]);
this.element = this.prop(props.element);
}, jCore.Component);
ModuleContainer.prototype.loadModule = function(props) {
var module = new Module(props);
module.parentElement(this.element());
module.redraw();
module.loadComponent();
this.modules().push(module);
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ModuleContainer;
else
app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
|
Add support for single quoted multi-line strings in Python
|
Prism.languages.python={comment:{pattern:/(^|[^\\])#.*?(\r?\n|$)/g,lookbehind:!0},string:/"""[\s\S]+?"""|'''[\s\S]+?'''|("|')(\\?.)*?\1/g,keyword:/\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g,"boolean":/\b(True|False)\b/g,number:/\b-?(0x)?\d*\.?[\da-f]+\b/g,operator:/[-+]{1,2}|=?<|=?>|!|={1,2}|(&){1,2}|(&){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};
|
Prism.languages.python={comment:{pattern:/(^|[^\\])#.*?(\r?\n|$)/g,lookbehind:!0},string:/"""[\s\S]+?"""|("|')(\\?.)*?\1/g,keyword:/\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g,"boolean":/\b(True|False)\b/g,number:/\b-?(0x)?\d*\.?[\da-f]+\b/g,operator:/[-+]{1,2}|=?<|=?>|!|={1,2}|(&){1,2}|(&){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};
|
fix: Send access token as a header instead of querystring parameter
|
import version from '../version'
/**
* Create pre configured axios instance
* @private
* @param {Object} axios - Axios library
* @param {Object} HTTPClientParams - Initialization parameters for the HTTP client
* @prop {string} space - Space ID
* @prop {string} accessToken - Access Token
* @prop {boolean=} insecure - If we should use http instead
* @prop {string=} host - Alternate host
* @prop {Object=} agent - HTTP agent for node
* @prop {Object=} headers - Additional headers
* @return {Object} Initialized axios instance
*/
export default function createHttpClient (axios, {space, accessToken, insecure, host, agent, headers}) {
let [hostname, port] = (host && host.split(':')) || []
hostname = hostname || 'cdn.contentful.com'
port = port || (insecure ? 80 : 443)
headers = headers || {}
headers['Authorization'] = 'Bearer ' + accessToken
headers['Content-Type'] = 'application/vnd.contentful.delivery.v1+json'
headers['X-Contentful-User-Agent'] = 'contentful.js/' + version
if (process && process.release && process.release.name === 'node') {
headers['user-agent'] = 'node.js/' + process.version
}
return axios.create({
baseURL: `${insecure ? 'http' : 'https'}://${hostname}:${port}/spaces/${space}/`,
headers: headers,
agent: agent
})
}
|
import qs from 'querystring'
import version from '../version'
/**
* Create pre configured axios instance
* @private
* @param {Object} axios - Axios library
* @param {Object} HTTPClientParams - Initialization parameters for the HTTP client
* @prop {string} space - Space ID
* @prop {string} accessToken - Access Token
* @prop {boolean=} insecure - If we should use http instead
* @prop {string=} host - Alternate host
* @prop {Object=} agent - HTTP agent for node
* @prop {Object=} headers - Additional headers
* @return {Object} Initialized axios instance
*/
export default function createHttpClient (axios, {space, accessToken, insecure, host, agent, headers}) {
let [hostname, port] = (host && host.split(':')) || []
hostname = hostname || 'cdn.contentful.com'
port = port || (insecure ? 80 : 443)
headers = headers || {}
headers['Content-Type'] = 'application/vnd.contentful.delivery.v1+json'
headers['X-Contentful-User-Agent'] = 'contentful.js/' + version
if (process && process.release && process.release.name === 'node') {
headers['user-agent'] = 'node.js/' + process.version
}
return axios.create({
baseURL: `${insecure ? 'http' : 'https'}://${hostname}:${port}/spaces/${space}/`,
headers: headers,
agent: agent,
params: {
access_token: accessToken
},
paramsSerializer: params => qs.stringify(params)
})
}
|
Add Travis UA for API calls
|
var Travis = require('travis-ci');
var child_process = require('child_process');
var repo = "excaliburjs/excaliburjs.github.io";
var travis = new Travis({
version: '2.0.0',
headers: {
'User-Agent': 'Travis/1.0'
}
});
var branch = process.env.TRAVIS_BRANCH;
if (branch !== "master") {
console.log("Current branch is `" + branch + "`, skipping docs deployment...");
} else {
console.log("Current branch is `" + branch + "`, triggering remote build of edge docs...");
travis.authenticate({
github_token: process.env.GH_TOKEN
}, function (err, res) {
if (err) {
return console.error(err);
}
travis.repos(repo.split('/')[0], repo.split('/')[1]).builds.get(
function (err, res) {
if (err) {
return console.error(err);
}
travis.requests.post({
build_id: res.builds[0].id
}, function (err, res) {
if (err) {
return console.error(err);
}
console.log(res.flash[0].notice);
});
});
});
}
|
var Travis = require('travis-ci');
var child_process = require('child_process');
var repo = "excaliburjs/excaliburjs.github.io";
var travis = new Travis({
version: '2.0.0'
});
var branch = process.env.TRAVIS_BRANCH;
if (branch !== "master") {
console.log("Current branch is `" + branch + "`, skipping docs deployment...");
} else {
console.log("Current branch is `" + branch + "`, triggering remote build of edge docs...");
travis.authenticate({
github_token: process.env.GH_TOKEN
}, function (err, res) {
if (err) {
return console.error(err);
}
travis.repos(repo.split('/')[0], repo.split('/')[1]).builds.get(
function (err, res) {
if (err) {
return console.error(err);
}
travis.requests.post({
build_id: res.builds[0].id
}, function (err, res) {
if (err) {
return console.error(err);
}
console.log(res.flash[0].notice);
});
});
});
}
|
Add /rl to command blacklist
|
package protocolsupport.server.listeners;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandListener implements Listener {
private final Set<String> blacklist = new HashSet<>();
public CommandListener() {
blacklist.add("/reload");
blacklist.add("/reload confirm");
blacklist.add("/rl");
blacklist.add("/rl confirm");
blacklist.add("/bukkit:reload");
blacklist.add("/bukkit:reload confirm");
blacklist.add("/bukkit:rl");
blacklist.add("/bukkit:rl confirm");
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent event) {
if (event.getPlayer().hasPermission("bukkit.command.reload") && blacklist.contains(event.getMessage().toLowerCase())) {
event.setCancelled(true);
event.getPlayer().sendMessage("The reload command has been disabled by ProtocolSupport");
}
}
}
|
package protocolsupport.server.listeners;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandListener implements Listener {
private final Set<String> blacklist = new HashSet<>();
public CommandListener() {
blacklist.add("/reload");
blacklist.add("/reload confirm");
blacklist.add("/bukkit:reload");
blacklist.add("/bukkit:reload confirm");
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent event) {
if (event.getPlayer().hasPermission("bukkit.command.reload") && blacklist.contains(event.getMessage().toLowerCase())) {
event.setCancelled(true);
event.getPlayer().sendMessage("The reload command has been disabled by ProtocolSupport");
}
}
}
|
[cleanup] Read dev server port from env if its there
|
/* eslint no-var: 0, func-names: 0 , no-console: 0 */
/**
* Development Server
* - See https://github.com/gaearon/react-transform-boilerplate
*/
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var app = express();
var compiler = webpack(config);
var PORT = process.env.PORT || 3000;
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'src/index.html'));
});
app.listen(PORT, 'localhost', function (err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:' + PORT);
});
|
/* eslint no-var: 0, func-names: 0 , no-console: 0 */
/**
* Development Server
* - See https://github.com/gaearon/react-transform-boilerplate
*/
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'src/index.html'));
});
app.listen(3000, 'localhost', function (err) {
if (err) {
console.log(err);
return;
}
console.log(process.env.NODE_ENV);
console.log('Listening at http://localhost:3000');
});
|
Fix revision ID of an alternate-language document.
|
<?php
declare (strict_types = 1);
namespace Crell\Document\Document;
use Ramsey\Uuid\Uuid;
trait DocumentTrait
{
/**
* UUID of this document.
*
* @var string
*/
protected $uuid;
/**
* Revision ID of this document.
*
* @var string.
*/
protected $revision;
/**
* The language this document is in.
*
* @var string
*/
protected $language;
public function uuid() : string
{
return $this->uuid;
}
public function revision() : string
{
return $this->revision;
}
public function language() : string
{
return $this->language;
}
public function asLanguage(string $language) : DocumentInterface
{
$new = clone $this;
$new->revision = Uuid::uuid4()->toString();
$new->language = $language;
return $new;
}
public function jsonSerialize() {
return [
'uuid' => $this->uuid,
'revision' => $this->revision,
'language' => $this->language,
];
}
}
|
<?php
declare (strict_types = 1);
namespace Crell\Document\Document;
trait DocumentTrait
{
/**
* UUID of this document.
*
* @var string
*/
protected $uuid;
/**
* Revision ID of this document.
*
* @var string.
*/
protected $revision;
/**
* The language this document is in.
*
* @var string
*/
protected $language;
public function uuid() : string
{
return $this->uuid;
}
public function revision() : string
{
return $this->revision;
}
public function language() : string
{
return $this->language;
}
public function asLanguage(string $language) : DocumentInterface
{
$new = clone $this;
$new->revision = '';
$new->language = $language;
return $new;
}
public function jsonSerialize() {
return [
'uuid' => $this->uuid,
'revision' => $this->revision,
'language' => $this->language,
];
}
}
|
Improve ActiveLanguageMixin to hide original field
|
from .conf import get_default_language
from .translator import get_i18n_field
from .utils import get_language
class ActiveLanguageMixin(object):
'''
Add this mixin to your admin class to hide the untranslated field and all
translated fields, except:
- The field for the default language (settings.LANGUAGE_CODE)
- The field for the currently active language.
'''
def get_exclude(self, request, obj=None):
# use default implementation for models without i18n-field
i18n_field = get_i18n_field(self.model)
if i18n_field is None:
return super(ActiveLanguageMixin, self).get_exclude(request)
language = get_language()
if language == get_default_language():
language = False
excludes = []
for field in i18n_field.get_translated_fields():
if field.language is None or field.language == language:
continue
excludes.append(field.name)
# also add the name of the original field, as it is added
excludes.append(field.original_field.name)
# de-duplicate
return list(set(excludes))
|
from .conf import get_default_language
from .translator import get_i18n_field
from .utils import get_language
class ActiveLanguageMixin(object):
'''
Hide all translated fields, except:
- The field for the default language (settings.LANGUAGE_CODE)
- The field for the currently active language.
'''
def get_exclude(self, request, obj=None):
i18n_field = get_i18n_field(self.model)
if i18n_field is None:
return super(ActiveLanguageMixin, self).get_exclude(request)
language = get_language()
if language == get_default_language():
language = False
excludes = []
for field in i18n_field.get_translated_fields():
if field.language is None or field.language == language:
continue
excludes.append(field.name)
return excludes
|
Make Spanish tutorial images also load for Latinamerican Spanish
|
/**
* @fileoverview
* Utility functions for handling tutorial images in multiple languages
*/
import {enImages as defaultImages} from './en-steps.js';
let savedImages = {};
let savedLocale = '';
const loadSpanish = () =>
import(/* webpackChunkName: "es-steps" */ './es-steps.js')
.then(({esImages: imageData}) => imageData);
const translations = {
'es': () => loadSpanish(),
'es-419': () => loadSpanish()
};
const loadImageData = locale => {
if (translations.hasOwnProperty(locale)) {
translations[locale]()
.then(newImages => {
savedImages = newImages;
savedLocale = locale;
});
}
};
/**
* Return image data for tutorials based on locale (default: en)
* @param {string} imageId key in the images object, or id string.
* @param {string} locale requested locale
* @return {string} image
*/
const translateImage = (imageId, locale) => {
if (locale !== savedLocale || !savedImages.hasOwnProperty(imageId)) {
return defaultImages[imageId];
}
return savedImages[imageId];
};
export {
loadImageData,
translateImage
};
|
/**
* @fileoverview
* Utility functions for handling tutorial images in multiple languages
*/
import {enImages as defaultImages} from './en-steps.js';
let savedImages = {};
let savedLocale = '';
const loadSpanish = () =>
import(/* webpackChunkName: "es-steps" */ './es-steps.js')
.then(({esImages: imageData}) => imageData);
const translations = {
es: () => loadSpanish()
};
const loadImageData = locale => {
if (translations.hasOwnProperty(locale)) {
translations[locale]()
.then(newImages => {
savedImages = newImages;
savedLocale = locale;
});
}
};
/**
* Return image data for tutorials based on locale (default: en)
* @param {string} imageId key in the images object, or id string.
* @param {string} locale requested locale
* @return {string} image
*/
const translateImage = (imageId, locale) => {
if (locale !== savedLocale || !savedImages.hasOwnProperty(imageId)) {
return defaultImages[imageId];
}
return savedImages[imageId];
};
export {
loadImageData,
translateImage
};
|
Fix in expected attribute value.
|
<?php
/*
* Bear CMS addon for Bear Framework
* https://bearcms.com/
* Copyright (c) 2016 Amplilabs Ltd.
* Free to use under the MIT license.
*/
$onClick = 'none';
if ($component->onClick === 'fullscreen') {
$onClick = 'fullscreen';
} elseif ($component->onClick === 'openUrl') {
$onClick = 'url';
}
$onClickAttribute = ' onClick="' . $onClick . '"';
$class = (string) $component->class;
$classAttribute = isset($class{0}) ? ' class="' . htmlentities($class) . '"' : '';
$filename = (string) $component->filename;
$content = '<div class="bearcms-image-element">';
if (isset($filename{0})) {
$filename = $app->bearCMS->data->getRealFilename($filename);
$content .= '<component src="image-gallery" columnsCount="1"' . $onClickAttribute . $classAttribute . '>';
$content .= '<file class="bearcms-image-element-image"' . ($onClick === 'url' ? ' url="' . htmlentities($component->url) . '"' : '') . ' title="' . htmlentities($component->title) . '" filename="' . $filename . '"/>';
$content .= '</component>';
}
$content .= '</div>';
$content = \BearCMS\Internal\ElementsHelper::getElementComponentContent($component, 'image', $content);
?><html>
<body><?= $content ?></body>
</html>
|
<?php
/*
* Bear CMS addon for Bear Framework
* https://bearcms.com/
* Copyright (c) 2016 Amplilabs Ltd.
* Free to use under the MIT license.
*/
$onClick = 'none';
if ($component->onClick === 'fullscreen') {
$onClick = 'fullscreen';
} elseif ($component->onClick === 'openUrl') {
$onClick = 'url';
}
$onClickAttribute = ' onClick="' . $onClick . '"';
$class = (string) $component->class;
$classAttribute = isset($class{0}) ? ' class="' . htmlentities($class) . '"' : '';
$filename = $app->bearCMS->data->getRealFilename($component->filename);
$content = '<div class="bearcms-image-element">';
if (isset($filename{0})) {
$content .= '<component src="image-gallery" columnsCount="1"' . $onClickAttribute . $classAttribute . '>';
$content .= '<file class="bearcms-image-element-image"' . ($onClick === 'url' ? ' url="' . htmlentities($component->url) . '"' : '') . ' title="' . htmlentities($component->title) . '" filename="' . $filename . '"/>';
$content .= '</component>';
}
$content .= '</div>';
$content = \BearCMS\Internal\ElementsHelper::getElementComponentContent($component, 'image', $content);
?><html>
<body><?= $content ?></body>
</html>
|
[fix] Set default API limit to 1000.
Fixes an exception on /artists when there are more than 20 artists on
the page (e.g. with ?limit=40).
|
import _ from "lodash";
import jQuery from "jquery";
import moment from "moment";
import DText from "./dtext.js";
import Tag from "./tag.js";
import UI from "./ui.js";
import "./danbooru-ex.css";
export default class EX {
static search(url, data, success) {
return $.getJSON(url, { search: data, limit: 1000 }, success);
}
}
EX.DText = DText;
EX.Tag = Tag;
EX.UI = UI;
EX.initialize = function () {
EX.UI.initialize();
EX.UI.Artists.initialize();
EX.UI.Comments.initialize();
EX.UI.ForumPosts.initialize();
EX.UI.ModeMenu.initialize();
EX.UI.Pools.initialize();
EX.UI.Posts.initialize();
EX.UI.PostVersions.initialize();
EX.UI.WikiPages.initialize();
}
window.EX = EX;
jQuery(function () {
"use strict";
EX.initialize();
});
|
import _ from "lodash";
import jQuery from "jquery";
import moment from "moment";
import DText from "./dtext.js";
import Tag from "./tag.js";
import UI from "./ui.js";
import "./danbooru-ex.css";
export default class EX {
static search(url, data, success) {
return $.getJSON(url, { search: data }, success);
}
}
EX.DText = DText;
EX.Tag = Tag;
EX.UI = UI;
EX.initialize = function () {
EX.UI.initialize();
EX.UI.Artists.initialize();
EX.UI.Comments.initialize();
EX.UI.ForumPosts.initialize();
EX.UI.ModeMenu.initialize();
EX.UI.Pools.initialize();
EX.UI.Posts.initialize();
EX.UI.PostVersions.initialize();
EX.UI.WikiPages.initialize();
}
window.EX = EX;
jQuery(function () {
"use strict";
EX.initialize();
});
|
Update structure tables with common D8 entries and add option for easily excluding watchdog as well.
|
<?php
/**
* Drush System configuration
*
* This file configures usage of Drush on the build container, in conjunction
* with configuration and commands placed in /etc/drush.
*/
// On drush sql-dump and other database extraction operations, ignore the data
// in these tables, but keep the table structures.
// Make sure to update the list when new cache tables are added.
// For Atrium sites see the `example.drushrc.php` shipped with the distribution
// for a complete list.
$options['structure-tables']['common'] = array(
'cache',
'cache_block',
'cache_bootstrap',
'cache_config',
'cache_container',
'cache_data',
'cache_default',
'cache_discovery',
'cache_entity',
'cache_field',
'cache_filter',
'cache_form',
'cache_menu',
'cache_migrate',
'cache_page',
'cache_path',
'cache_render',
'cache_rest',
'cache_token',
'cache_toolbar',
'cache_update',
'cache_variable',
'cache_views',
'cache_views_data',
'history',
'search_index',
'search_node_links',
'search_total',
'sessions',
);
$options['structure-tables']['common-and-logging'] = array_merge($options['structure-tables']['common'], array(
'watchdog',
));
// Use the list of cache tables above.
$options['structure-tables-key'] = 'common';
|
<?php
/**
* Drush System configuration
*
* This file configures usage of Drush on the build container, in conjunction
* with configuration and commands placed in /etc/drush.
*/
// On drush sql-dump and other database extraction operations, ignore the data
// in these tables, but keep the table structures.
// Make sure to update the list when new cache tables are added.
// For Atrium sites see the `example.drushrc.php` shipped with the distribution
// for a complete list.
$options['structure-tables']['common'] = array(
'cache',
'cache_block',
'cache_bootstrap',
'cache_field',
'cache_filter',
'cache_form',
'cache_menu',
'cache_page',
'cache_path',
'cache_token',
'cache_update',
'cache_variable',
'cache_views',
'cache_views_data',
'history',
'search_index',
'search_node_links',
'search_total',
'sessions',
);
// Use the list of cache tables above.
$options['structure-tables-key'] = 'common';
|
Fix boolean logic related to showing delete button
|
import React, { Component } from 'react';
import style from './style';
import CommentItem from '../CommentItem';
export default class CommentList extends Component {
componentDidMount() {
this.wrapper.scrollTop = this.wrapper.scrollHeight;
}
componentDidUpdate(prev) {
if (this.props.comments.length !== prev.comments.length) {
this.wrapper.scrollTop = this.wrapper.scrollHeight;
}
}
render() {
const { comments } = this.props;
if (comments.length === 0) {
return (
<div ref={(el) => { this.wrapper = el; }} style={style.wrapper}>
<div style={style.noComments}>No Comments Yet!</div>
</div>
);
}
return (
<div ref={(el) => { this.wrapper = el; }} style={style.wrapper}>
{comments.map((comment, idx) => (
<CommentItem
key={`comment_${idx}`}
comment={comment}
ownComment={comment.userId === (this.props.user && this.props.user.id)}
deleteComment={() => this.props.deleteComment(comment.id)}
/>
))}
</div>
);
}
}
CommentList.propTypes = {
comments: React.PropTypes.array,
user: React.PropTypes.object,
deleteComment: React.PropTypes.func,
};
|
import React, { Component } from 'react';
import style from './style';
import CommentItem from '../CommentItem';
export default class CommentList extends Component {
componentDidMount() {
this.wrapper.scrollTop = this.wrapper.scrollHeight;
}
componentDidUpdate(prev) {
if (this.props.comments.length !== prev.comments.length) {
this.wrapper.scrollTop = this.wrapper.scrollHeight;
}
}
render() {
const { comments } = this.props;
if (comments.length === 0) {
return (
<div ref={(el) => { this.wrapper = el; }} style={style.wrapper}>
<div style={style.noComments}>No Comments Yet!</div>
</div>
);
}
return (
<div ref={(el) => { this.wrapper = el; }} style={style.wrapper}>
{comments.map((comment, idx) => (
<CommentItem
key={`comment_${idx}`}
comment={comment}
ownComment={comment.userId === this.props.user && this.props.user.id}
deleteComment={() => this.props.deleteComment(comment.id)}
/>
))}
</div>
);
}
}
CommentList.propTypes = {
comments: React.PropTypes.array,
user: React.PropTypes.object,
deleteComment: React.PropTypes.func,
};
|
Create json for bsx server status
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Homepage extends Application {
/**
* Index Page for the Homepage controller.
*/
public function index()
{
/* Grab data from database for Stocks and Players */
$this->data['stocks'] = $this->stocks->getAllStocks();
$this->data['players'] = $this->players->getAllPlayers();
$this->data['latestmovements'] = $this->movements->latest5Movements();
$this->data['latesttransactions'] = $this->transactions->latest5transactions();
/* Set up data to render page */
$this->data['title'] = "Stock Ticker";
$this->data['left-panel-content'] = 'base/players.php';
$this->data['right-panel-content'] = 'base/stocks.php';
$this->render();
}
public function status()
{
/* Grab game status */
$status = $this->managements->getServerStatus();
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($status);
}
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Homepage extends Application {
/**
* Index Page for the Homepage controller.
*/
public function index()
{
/* Grab data from database for Stocks and Players */
$this->data['stocks'] = $this->stocks->getAllStocks();
$this->data['players'] = $this->players->getAllPlayers();
$this->data['latestmovements'] = $this->movements->latest5Movements();
$this->data['latesttransactions'] = $this->transactions->latest5transactions();
/* Grab game status */
$status = $this->managements->getServerStatus();
/* Set up data to render page */
$this->data['title'] = "Stock Ticker";
$this->data['left-panel-content'] = 'base/players.php';
$this->data['right-panel-content'] = 'base/stocks.php';
$this->render();
}
}
|
Fix logging from afterEach hook in tests
|
import 'es5-shim';
beforeEach(() => {
sinon.stub(console, 'error');
});
afterEach(function checkNoUnexpectedWarnings() {
if (typeof console.error.restore === 'function') {
assert(!console.error.called, () => {
return `${console.error.getCall(0).args[0]} \nIn '${this.currentTest.fullTitle()}'`;
});
console.error.restore();
}
});
describe('Process environment for tests', () => {
it('Should be development for React console warnings', () => {
assert.equal(process.env.NODE_ENV, 'development');
});
});
// Ensure all files in src folder are loaded for proper code coverage analysis
const srcContext = require.context('../src', true, /.*\.js$/);
srcContext.keys().forEach(srcContext);
const testsContext = require.context('.', true, /Spec$/);
testsContext.keys().forEach(testsContext);
|
import 'es5-shim';
beforeEach(() => {
sinon.stub(console, 'error');
});
afterEach(() => {
if (typeof console.error.restore === 'function') {
assert(!console.error.called, () => {
return `${console.error.getCall(0).args[0]} \nIn '${this.currentTest.fullTitle()}'`;
});
console.error.restore();
}
});
describe('Process environment for tests', () => {
it('Should be development for React console warnings', () => {
assert.equal(process.env.NODE_ENV, 'development');
});
});
// Ensure all files in src folder are loaded for proper code coverage analysis
const srcContext = require.context('../src', true, /.*\.js$/);
srcContext.keys().forEach(srcContext);
const testsContext = require.context('.', true, /Spec$/);
testsContext.keys().forEach(testsContext);
|
Remove default null because nullable does that
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddQuantityColumnToPostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->integer('quantity')->after('northstar_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('quantity');
});
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddQuantityColumnToPostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->integer('quantity')->after('northstar_id')->default(null)->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('quantity');
});
}
}
|
Add fright script back in, just in case
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='ghostly',
version='0.7.1',
description='Create simple browser tests',
author='Brenton Cleeland',
url='https://github.com/sesh/ghostly',
install_requires=['click', 'colorama', 'pillow', 'PyYAML', 'selenium'],
py_modules=['ghostly', 'fright'],
entry_points={
'console_scripts': [
'ghostly=ghostly:run_ghostly',
'fright=fright:run_fright',
]
},
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
)
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='ghostly',
version='0.7.1',
description='Create simple browser tests',
author='Brenton Cleeland',
url='https://github.com/sesh/ghostly',
install_requires=['click', 'colorama', 'pillow', 'PyYAML', 'selenium'],
py_modules=['ghostly', 'fright'],
entry_points={
'console_scripts': [
'ghostly=ghostly:run_ghostly',
]
},
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
)
)
|
Fix bug with broken receiving of values.
|
import React, { PropTypes } from 'react';
import styles from 'styles/Input';
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value
};
}
componentWillReceiveProps({ value }) {
this.setState({ value });
}
render() {
const { value } = this.state;
return (
<input
type='text'
className={styles.input}
placeholder={this.props.placeholder}
value={ value }
autoFocus={ true }
onChange={ e => {
this.setState({
value: e.target.value
});
}}
onBlur={ () => { this.props.requersHandler(value); }}
onKeyPress={ e => {
if (e.key === 'Enter') {
this.props.requersHandler(value);
}
}}/>
);
}
}
Input.propsTypes = {
value: PropTypes.string.isRequired,
placeholder: PropTypes.string
};
Input.defaultProps = {
placeholder: 'Type query…'
};
export default Input;
|
import React, { PropTypes } from 'react';
import styles from 'styles/Input';
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value
};
}
render() {
const { value } = this.state;
return (
<input
type='text'
className={styles.input}
placeholder={this.props.placeholder}
value={ value }
autoFocus={ true }
onChange={ e => {
this.setState({
value: e.target.value
});
}}
onBlur={ () => { this.props.requersHandler(value); }}
onKeyPress={ e => {
if (e.key === 'Enter') {
this.props.requersHandler(value);
}
}}/>
);
}
}
Input.propsTypes = {
value: PropTypes.string.isRequired,
placeholder: PropTypes.string
};
Input.defaultProps = {
placeholder: 'Type query…'
};
export default Input;
|
Add default selected state to toolbar selections.
|
import SelectStateItemsCollection from '../collections/SelectStateItemsCollection';
import meta from '../meta';
export default Backbone.Model.extend({
initialize() {
const items = this.get('items');
const itemsCollection = new SelectStateItemsCollection(items);
this.listenTo(itemsCollection, 'select:one', model => this.set('iconClass', model.get('iconClass')));
this.set('items', itemsCollection);
this.__selectDefaultModel(itemsCollection);
this.__addDropdownClass();
},
__addDropdownClass() {
const dropdownClass = this.get('dropdownClass');
let SelectStateDropdownClass = 'toolbar-panel_container__select-state';
dropdownClass && (SelectStateDropdownClass = `${dropdownClass} ${SelectStateDropdownClass}`);
this.set('dropdownClass', SelectStateDropdownClass);
},
__selectDefaultModel(itemsCollection) {
let firstNotHeadlineModel = null;
firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE && model.get('default'));
if (!firstNotHeadlineModel) {
firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE);
}
itemsCollection.select(firstNotHeadlineModel);
}
});
|
import SelectStateItemsCollection from '../collections/SelectStateItemsCollection';
import meta from '../meta';
export default Backbone.Model.extend({
initialize() {
const items = this.get('items');
const itemsCollection = new SelectStateItemsCollection(items);
this.listenTo(itemsCollection, 'select:one', model => this.set('iconClass', model.get('iconClass')));
this.set('items', itemsCollection);
const firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE);
itemsCollection.select(firstNotHeadlineModel);
this.__addDropdownClass();
},
__addDropdownClass() {
const dropdownClass = this.get('dropdownClass');
let SelectStateDropdownClass = 'toolbar-panel_container__select-state';
dropdownClass && (SelectStateDropdownClass = `${dropdownClass} ${SelectStateDropdownClass}`);
this.set('dropdownClass', SelectStateDropdownClass);
}
});
|
Add support for a dir of client tests
|
#!/usr/bin/env python
'''
Discover all instances of unittest.TestCase in this directory.
'''
# Import python libs
import os
# Import salt libs
import saltunittest
from integration import TestDaemon
TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))
def run_integration_tests():
with TestDaemon():
moduleloader = saltunittest.TestLoader()
moduletests = moduleloader.discover(os.path.join(TEST_DIR, 'integration', 'modules'), '*.py')
saltunittest.TextTestRunner(verbosity=1).run(moduletests)
clientloader = saltunittest.TestLoader()
clienttests = clientloader.discover(os.path.join(TEST_DIR, 'integration', 'client'), '*.py')
saltunittest.TextTestRunner(verbosity=1).run(clienttests)
def run_unit_tests():
loader = saltunittest.TestLoader()
tests = loader.discover(os.path.join(TEST_DIR, 'unit', 'templates'), '*.py')
saltunittest.TextTestRunner(verbosity=1).run(tests)
if __name__ == "__main__":
run_integration_tests()
run_unit_tests()
|
#!/usr/bin/env python
'''
Discover all instances of unittest.TestCase in this directory.
'''
# Import python libs
import os
# Import salt libs
import saltunittest
from integration import TestDaemon
TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))
def run_integration_tests():
with TestDaemon():
loader = saltunittest.TestLoader()
tests = loader.discover(os.path.join(TEST_DIR, 'integration', 'modules'), '*.py')
saltunittest.TextTestRunner(verbosity=1).run(tests)
def run_unit_tests():
loader = saltunittest.TestLoader()
tests = loader.discover(os.path.join(TEST_DIR, 'unit', 'templates'), '*.py')
saltunittest.TextTestRunner(verbosity=1).run(tests)
if __name__ == "__main__":
run_integration_tests()
run_unit_tests()
|
Backup directory is made, and a notification is sent and logged if the directory doesn't exist
|
#!/usr/bin/python2
import LogUncaught, ConfigParser, logging, PushBullet, os
from time import localtime, strftime
sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')
# Logger File Handler
sbLFH = logging.FileHandler(sbConfig.get('ServerBackup', 'log_location'))
sbLFH.setLevel(logging.DEBUG)
# Logger Formatter
sbLFORMAT = logging.Formatter('[%(asctime)s | %(levelname)s] - %(message)s')
sbLFH.setFormatter(sbLFORMAT)
# Logger
sbLogger = logging.getLogger("serverbackup_logger")
sbLogger.setLevel(logging.DEBUG)
sbLogger.addHandler(sbLFH)
sbLogger.info("Script has begun")
sbLocation = sbConfig.get('ServerBackup', 'backup_location')
databasePass = sbConfig.get('Database', 'password')
lbLocation = sbConfig.get('LogBackup', 'backup_location')
date = strftime("%m_%d_%Y_%H_%M_%S", localtime())
sbFolder = sbLocation + "backup_" + date + "/"
os.makedirs(sbFolder)
if not os.path.exists(sbFolder):
message = "Folder, \"%s\", couldn't be made" % sbFolder
sbLogger.critical(message)
PushBullet.sendPushNote({'id':PushBullet.getPushDevicesIds(), 'title':"Server Backup Error", 'message':message})
exit(message)
|
#!/usr/bin/python2
import LogUncaught, ConfigParser, logging, os
sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')
# Logger File Handler
sbLFH = logging.FileHandler(sbConfig.get('ServerBackup', 'log_location'))
sbLFH.setLevel(logging.DEBUG)
# Logger Formatter
sbLFORMAT = logging.Formatter('[%(asctime)s | %(levelname)s] - %(message)s')
sbLFH.setFormatter(sbLFORMAT)
# Logger
sbLogger = logging.getLogger("serverbackup_logger")
sbLogger.setLevel(logging.DEBUG)
sbLogger.addHandler(sbLFH)
sbLogger.info("Script has begun")
sbLocation = sbConfig.get('ServerBackup', 'backup_location')
databasePass = sbConfig.get('Database', 'password')
lbLocation = sbConfig.get('LogBackup', 'backup_location')
|
Add compatibility with Python 3.x
|
#!/usr/bin/env python
# encoding: utf-8
"""
import debug: https://github.com/narfdotpl/debug
"""
try:
import __builtin__
except ImportError:
# Python 3.x
import builtins as __builtin__
from sys import _getframe
from ipdb import set_trace
# do not forget
old_import = __builtin__.__import__
def debug():
# get frame
frame = _getframe(2)
# inject see (`from see import see`)
ns = frame.f_globals
if 'see' not in ns:
ns['see'] = old_import('see', fromlist=['see']).see
# start ipdb
set_trace(frame)
# run on first import
debug()
# monkeypatch `import` so `import debug` will work every time
def new_import(*args, **kwargs):
if args[0] == 'debug':
debug()
else:
return old_import(*args, **kwargs)
__builtin__.__import__ = new_import
|
#!/usr/bin/env python
# encoding: utf-8
"""
import debug: https://github.com/narfdotpl/debug
"""
import __builtin__
from sys import _getframe
from ipdb import set_trace
# do not forget
old_import = __builtin__.__import__
def debug():
# get frame
frame = _getframe(2)
# inject see (`from see import see`)
ns = frame.f_globals
if 'see' not in ns:
ns['see'] = old_import('see', fromlist=['see']).see
# start ipdb
set_trace(frame)
# run on first import
debug()
# monkeypatch `import` so `import debug` will work every time
def new_import(*args, **kwargs):
if args[0] == 'debug':
debug()
else:
return old_import(*args, **kwargs)
__builtin__.__import__ = new_import
|
Revert "Remove Windows build for ia32 arch"
This reverts commit ec504d074f02783b8e90ec149437e08f7d647bed.
|
'use strict';
const gulp = require('gulp');
const { build } = require('electron-builder');
const config = require('../electron-builder.json');
const { getEnvName } = require('./utils');
const publish = getEnvName() !== 'production' ? 'never' : 'onTagOrDraft';
gulp.task('release:darwin', () => build({ publish, x64: true, mac: [] }));
gulp.task('release:win32', () => build({ publish, ia32: true, x64: true, win: [ 'nsis', 'appx' ] }));
gulp.task('release:linux', (cb) => {
build({ publish, x64: true, linux: [] })
.then(() => build({ publish, ia32: true, linux: config.linux.target.filter(target => target !== 'snap') }))
.then(() => cb(), (error) => cb(error));
});
gulp.task('release', [ 'build-app', `release:${ process.platform }` ]);
|
'use strict';
const gulp = require('gulp');
const { build } = require('electron-builder');
const config = require('../electron-builder.json');
const { getEnvName } = require('./utils');
const publish = getEnvName() !== 'production' ? 'never' : 'onTagOrDraft';
gulp.task('release:darwin', () => build({ publish, x64: true, mac: [] }));
gulp.task('release:win32', () => build({ publish, x64: true, win: [ 'nsis', 'appx' ] }));
gulp.task('release:linux', (cb) => {
build({ publish, x64: true, linux: [] })
.then(() => build({ publish, ia32: true, linux: config.linux.target.filter(target => target !== 'snap') }))
.then(() => cb(), (error) => cb(error));
});
gulp.task('release', [ 'build-app', `release:${ process.platform }` ]);
|
Check if results from bank are not equal null
|
import { expect } from 'chai';
import NBG from '../src/banks/NBG';
import CreditAgricole from '../src/banks/CreditAgricole';
import CBE from '../src/banks/CBE';
const { describe, it } = global;
const banks = [
NBG,
CreditAgricole,
CBE,
];
describe('Banks', () => {
banks.forEach((Bank) => {
const bank = new Bank();
describe(bank.name.acronym, () => {
const bankTestPromise = new Promise((resolve) => {
bank.scrape((rates) => {
resolve(rates);
});
});
it('Should not equal null', () => {
return bankTestPromise.then((result) => {
expect(result).to.not.equal(null);
});
});
});
});
});
|
import { expect } from 'chai';
import NBG from '../src/banks/NBG';
import CreditAgricole from '../src/banks/CreditAgricole';
import CBE from '../src/banks/CBE';
const { describe, it } = global;
const banks = [
NBG,
CreditAgricole,
CBE,
];
describe('Banks', () => {
banks.forEach((Bank) => {
const bank = new Bank();
describe(bank.name.acronym, () => {
it('Should not equal null', () => {
const testPromise = new Promise((resolve) => {
bank.scrape((rates) => {
resolve(rates);
});
});
return testPromise.then((result) => {
expect(result).to.not.equal(null);
});
});
});
});
});
|
Fix application name in admin
|
from django.db import models
class AirtimeApplication(models.Model):
name = models.CharField(max_length=50)
ratio = models.IntegerField(null=True, blank=True)
max_per_day = models.IntegerField(null=True, blank=True)
amount = models.IntegerField(null=True, blank=True)
active = models.BooleanField()
product_key = models.CharField(max_length=10)
def __unicode__(self):
return self.name
class Meta:
verbose_name = "Airtime Application"
class SendAirtime(models.Model):
app_id = models.ForeignKey(AirtimeApplication)
msisdn = models.CharField(max_length=30,
verbose_name="MSISDN (Mobile Number)")
product_key = models.CharField(max_length=10)
amount = models.IntegerField()
sent = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True,
blank=False,
editable=False)
def __unicode__(self):
return self.msisdn
class Meta:
verbose_name_plural = "Send Airtime"
|
from django.db import models
class AirtimeApplication(models.Model):
name = models.CharField(max_length=50)
ratio = models.IntegerField(null=True, blank=True)
max_per_day = models.IntegerField(null=True, blank=True)
amount = models.IntegerField(null=True, blank=True)
active = models.BooleanField()
product_key = models.CharField(max_length=10)
def __unicode__(self):
return self.name
class Meta:
verbose_name = "Airtime Application"
class SendAirtime(models.Model):
app_id = models.ForeignKey(AirtimeApplication)
msisdn = models.CharField(max_length=30,
verbose_name="MSISDN (Mobile Number)")
product_key = models.CharField(max_length=10)
amount = models.IntegerField()
sent = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True,
blank=False,
editable=False)
def __unicode__(self):
return self.msisdn
class Meta:
verbose_name = "Send Airtime"
|
Add mocks to movies controller tests
|
'use strict';
describe('controllers', function() {
var httpBackend, scope, createController;
beforeEach(module('polyflix'));
beforeEach(inject(function($rootScope, $httpBackend, $controller) {
httpBackend = $httpBackend;
scope = $rootScope.$new();
httpBackend.whenGET(mocks.configUrl).respond(
JSON.stringify(mocks.configResults)
);
httpBackend.whenGET(mocks.allMoviesUrl).respond(
JSON.stringify(mocks.allMoviesResults)
);
httpBackend.whenDELETE(mocks.deleteUrl).respond(
JSON.stringify(mocks.deleteResults)
);
createController = function() {
return $controller('MoviesCtrl', {
'$scope': scope
});
};
}));
describe('controller', function() {
it('should exist', function() {
var controller = createController();
httpBackend.flush();
expect(controller).toBeDefined();
});
});
});
|
'use strict';
describe('controllers', function() {
var httpBackend, scope, createController;
beforeEach(module('polyflix'));
beforeEach(inject(function($rootScope, $httpBackend, $controller) {
httpBackend = $httpBackend;
scope = $rootScope.$new();
httpBackend.whenGET(mocks.configUrl).respond(
JSON.stringify(mocks.configResults)
);
httpBackend.whenGET(mocks.allMoviesUrl).respond(
JSON.stringify(mocks.allMoviesResults)
);
createController = function() {
return $controller('MoviesCtrl', {
'$scope': scope
});
};
}));
describe('controller', function() {
it('should exist', function() {
var controller = createController();
expect(controller).toBeDefined();
});
});
});
|
Call writeAll() to make sure pre/post operations by subclasses get applied properly.
|
package org.pharmgkb.parsers;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
/**
* Counterpart to {@link LineParser}.
*
* @author Douglas Myers-Turnbull
*/
public interface LineWriter<T> extends Function<T, String> {
default void writeToFile(@Nonnull Collection<T> lines, @Nonnull Path file) throws IOException {
try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(file))) {
writeAll(lines.stream())
.forEach(pw::println);
}
}
/**
* Override this to add post- or pre- validation or processing.
*/
default @Nonnull Stream<String> writeAll(@Nonnull Stream<T> stream) {
return stream.map(this);
}
/**
* @return The total number of lines this writer processed since its creation
*/
@Nonnegative
long nLinesProcessed();
@Override
@Nonnull String apply(@Nonnull T t);
}
|
package org.pharmgkb.parsers;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
/**
* Counterpart to {@link LineParser}.
*
* @author Douglas Myers-Turnbull
*/
public interface LineWriter<T> extends Function<T, String> {
default void writeToFile(@Nonnull Collection<T> lines, @Nonnull Path file) throws IOException {
try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(file))) {
lines.stream()
.map(this)
.forEach(pw::println);
}
}
/**
* Override this to add post- or pre- validation or processing.
*/
default @Nonnull Stream<String> writeAll(@Nonnull Stream<T> stream) {
return stream.map(this);
}
/**
* @return The total number of lines this writer processed since its creation
*/
@Nonnegative
long nLinesProcessed();
@Override
@Nonnull String apply(@Nonnull T t);
}
|
Use parameter to pass Webdriver object to share execution
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
def sign_in(self, driver):
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
driver.find_element_by_id("submitButton2").click()
return driver
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, driver, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
self.driver = webdriver.Firefox()
self.cookie_jar = self.driver.get_cookies()
def sign_in(self):
# Open the profile URL. This will forward to the sign in page if session is invalid
self.driver.get("https://developer.apple.com/account/ios/profile/")
email_element = self.driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = self.driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
self.driver.find_element_by_id("submitButton2").click()
self.cookie_jar = self.driver.get_cookies()
return self.cookie_jar
|
Check for default values in dropdowns
|
import React from 'react'
import PropTypes from 'prop-types'
import FormGroup from '../forms/FormGroup'
import Select from '../forms/Select'
const SelectStackOption = ({ label, name, value, definitions, required, onChange, error }) => {
// default value may be null
if (value === null) {
value = ''
}
const onChangeLocal = e => {
if (e.target.value.includes(`(default: ${definitions.default})`)) {
e.target.value = definitions.default
}
return onChange(e)
}
return (
<FormGroup label={label} htmlFor={name} error={error} required={required}>
<Select
name={name}
id={name}
value={value}
defaultValue={definitions.default}
className="rka-select"
onChange={onChangeLocal}
>
{definitions.values.map(option => (
<option key={option} value={option}>
{option}
</option>
))}
</Select>
</FormGroup>
)
}
SelectStackOption.propTypes = {
label: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
definitions: PropTypes.object.isRequired,
required: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
error: PropTypes.string
}
export default SelectStackOption
|
import React from 'react'
import PropTypes from 'prop-types'
import FormGroup from '../forms/FormGroup'
import Select from '../forms/Select'
const SelectStackOption = ({ label, name, value, definitions, required, onChange, error }) => {
// default value may be null
if (value === null) {
value = ''
}
return (
<FormGroup label={label} htmlFor={name} error={error} required={required}>
<Select
name={name}
id={name}
value={value}
defaultValue={definitions.default}
className="rka-select"
onChange={onChange}
>
{definitions.values.map(option => (
<option key={option} value={option}>
{option}
</option>
))}
</Select>
</FormGroup>
)
}
SelectStackOption.propTypes = {
label: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
definitions: PropTypes.object.isRequired,
required: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
error: PropTypes.string
}
export default SelectStackOption
|
Add an API for formatter functionality.
|
"use strict";
/*
default options
*/
var defaultOptions = {
// force additionalProperties and additionalItems to be defined on "object" and "array" types
forceAdditional: false,
// force items to be defined on "array" types
forceItems: false,
// force maxLength to be defined on "string" types
forceMaxLength: false,
// force properties or patternProperties to be defined on "object" types
forceProperties: false,
// disallow usage of keywords that this validator can't handle
noExtraKeywords: false,
// disallow usage of schema's without "type" defined
noTypeless: false,
// disallow zero length strings in validated objects
noZeroLengthStrings: false,
// forces "uri" format to be in fully rfc3986 compliant
strictUris: false,
// forces "email" format to be validated more strictly
strictEmails: false,
// turn on all of the above
strict: false
};
/*
constructor
*/
function ZSchema(options) {
this.options = options;
}
/*
instance methods
*/
ZSchema.prototype.compileSchema = function (schema, callback) {
};
ZSchema.prototype.validateSchema = function (schema, callback) {
};
ZSchema.prototype.validate = function (json, schema, callback) {
};
/*
static methods
*/
ZSchema.registerFormat = function (formatName, validatorFunction) {
};
ZSchema.registerFormatter = function (formatterName, formatterFunction) {
};
module.exports = ZSchema;
|
"use strict";
/*
default options
*/
var defaultOptions = {
// force additionalProperties and additionalItems to be defined on "object" and "array" types
forceAdditional: false,
// force items to be defined on "array" types
forceItems: false,
// force maxLength to be defined on "string" types
forceMaxLength: false,
// force properties or patternProperties to be defined on "object" types
forceProperties: false,
// disallow usage of keywords that this validator can't handle
noExtraKeywords: false,
// disallow usage of schema's without "type" defined
noTypeless: false,
// disallow zero length strings in validated objects
noZeroLengthStrings: false,
// forces "uri" format to be in fully rfc3986 compliant
strictUris: false,
// forces "email" format to be validated more strictly
strictEmails: false,
// turn on all of the above
strict: false
};
/*
constructor
*/
function ZSchema(options) {
this.options = options;
}
/*
instance methods
*/
ZSchema.prototype.compileSchema = function (schema, callback) {
};
ZSchema.prototype.validateSchema = function (schema, callback) {
};
ZSchema.prototype.validate = function (json, schema, callback) {
};
/*
static methods
*/
ZSchema.registerFormat = function (formatName, validatorFunction) {
};
module.exports = ZSchema;
|
Use port number from command line argument
|
import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
/**
* Created by Xinan on 11/9/15.
*/
public class WebProxy {
public static void main(String[] args) {
try {
int port = Integer.parseInt(args[0]);
ServerSocket socket = new ServerSocket(port);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
System.out.printf("Server is shutting down...\n");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.out.printf("Server listening on %d...\n\n", port);
while (!socket.isClosed()) {
(new RequestHandlerThread(socket.accept())).start();
}
} catch (SocketException e) {
System.out.printf("%s\n", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException | NumberFormatException e) {
System.out.printf("Invalid argument!\n");
}
}
}
|
import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
/**
* Created by Xinan on 11/9/15.
*/
public class WebProxy {
public static void main(String[] args) {
try {
int port = Integer.parseInt("1234");
ServerSocket socket = new ServerSocket(port);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
System.out.printf("Server is shutting down...\n");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.out.printf("Server listening on %d...\n\n", port);
while (!socket.isClosed()) {
(new RequestHandlerThread(socket.accept())).start();
}
} catch (SocketException e) {
System.out.printf("%s\n", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException | NumberFormatException e) {
System.out.printf("Invalid argument!\n");
}
}
}
|
[FIX] Fix email (as username) validation when login_is_email pref is on
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@59506 b456876b-0849-0410-b77d-98878d47e9d5
|
<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
function validator_username($input, $parameter = '', $message = '')
{
global $prefs;
$userlib = TikiLib::lib('user');
if ($prefs['login_is_email'] === 'y') {
if ($userlib->get_user_by_email($input)) {
return tra("Email already in use");
}
if (!validate_email($input)){
return tra("Invalid email");
}
} else {
if ($userlib->user_exists($input)) {
return tra("User already exists");
}
if (!empty($prefs['username_pattern']) && !preg_match($prefs['username_pattern'], $input)) {
return tra("Invalid character combination for username");
}
if (strtolower($input) == 'anonymous' || strtolower($input) == 'registered') {
return tra("Invalid username");
}
if (strlen($input) > $prefs['max_username_length']) {
$error = tr("Username cannot contain more than %0 characters", $prefs['max_username_length']);
return $error;
}
if (strlen($input) < $prefs['min_username_length']) {
$error = tr("Username must be at least %0 characters long", $prefs['min_username_length']);
return $error;
}
}
return true;
}
|
<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
function validator_username($input, $parameter = '', $message = '')
{
global $prefs;
$userlib = TikiLib::lib('user');
if ($userlib->user_exists($input)) {
return tra("User already exists");
}
if (!empty($prefs['username_pattern']) && !preg_match($prefs['username_pattern'], $input)) {
return tra("Invalid character combination for username");
}
if (strtolower($input) == 'anonymous' || strtolower($input) == 'registered') {
return tra("Invalid username");
}
if (strlen($input) > $prefs['max_username_length']) {
$error = tr("Username cannot contain more than %0 characters", $prefs['max_username_length']);
return $error;
}
if (strlen($input) < $prefs['min_username_length']) {
$error = tr("Username must be at least %0 characters long", $prefs['min_username_length']);
return $error;
}
return true;
}
|
Fix for undocumented timestamp filtering in python-instagram
|
from instagram import InstagramAPI, helper
from social.backends.instagram import InstagramOAuth2
from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin
class Instagram(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, InstagramOAuth2):
@staticmethod
def save_extra_data(response, user):
if response['data']['bio']:
user.about = response['bio']
user.save()
@staticmethod
def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs):
image_url = response['data']['profile_picture']
return image_url
@staticmethod
def post(user_social_auth, social_obj):
return
@staticmethod
def get_friends(user_social_auth):
return
@staticmethod
def get_posts(user_social_auth, last_updated_time):
api = InstagramAPI(access_token=user_social_auth.extra_data['access_token'])
formatted_time = helper.datetime_to_timestamp(last_updated_time)
recent_media, next_ = api.user_recent_media(user_id=user_social_auth.uid, min_timestamp=formatted_time)
return recent_media
|
from instagram import InstagramAPI
from social.backends.instagram import InstagramOAuth2
from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin
class Instagram(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, InstagramOAuth2):
@staticmethod
def save_extra_data(response, user):
if response['data']['bio']:
user.about = response['bio']
user.save()
@staticmethod
def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs):
image_url = response['data']['profile_picture']
return image_url
@staticmethod
def post(user_social_auth, social_obj):
return
@staticmethod
def get_friends(user_social_auth):
return
@staticmethod
def get_posts(user_social_auth, last_updated_time):
api = InstagramAPI(access_token=user_social_auth.extra_data['access_token'])
recent_media, next_ = api.user_recent_media(user_id=user_social_auth.uid, min_time=last_updated_time)
return recent_media
|
Send the error message as JSON
|
const watch = require(`${__dirname}/watch.js`);
const datastore = require(`${__dirname}/datastore`);
const express = require('express');
const app = express();
app.use('/', express.static(`${__dirname}/../public`));
app.get('/api/full', function (req, res) {
res.json(datastore.full);
});
app.get('/api/delta', function (req, res) {
res.json(datastore.delta);
});
app.get('/api/merc/:id', function (req, res) {
if (req.params.id && datastore.full.Merchants.list[req.params.id]) {
res.json(datastore.full.Merchants.list[req.params.id]);
} else {
res.status(404).json({"error": "Not found."});
}
});
app.listen(3088, 'localhost', function () {
console.log('Server started on port 3088');
});
|
const watch = require(`${__dirname}/watch.js`);
const datastore = require(`${__dirname}/datastore`);
const express = require('express');
const app = express();
app.use('/', express.static(`${__dirname}/../public`));
app.get('/api/full', function (req, res) {
res.json(datastore.full);
});
app.get('/api/delta', function (req, res) {
res.json(datastore.delta);
});
app.get('/api/merc/:id', function (req, res) {
if (req.params.id && datastore.full.Merchants.list[req.params.id]) {
res.json(datastore.full.Merchants.list[req.params.id]);
} else {
res.status(404).send('Not found.');
}
});
app.listen(3088, 'localhost', function () {
console.log('Server started on port 3088');
});
|
Add names to each url
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
url(r'^(?P<id>\d+)$', 'tempel.views.view', {'mode': 'html'}, name='tempel_view'),
url(r'^(?P<id>\d+).html$', 'tempel.views.view', {'mode': 'html'}, name='tempel_html'),
url(r'^(?P<id>\d+).txt$', 'tempel.views.view', {'mode': 'txt'}, name='tempel_raw'),
url(r'^e/(?P<id>\d+)/download/$', 'tempel.views.download', name='tempel_download'),
url(r'^$', 'tempel.views.index', name='tempel_index'),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
(r'^(?P<id>\d+)$', 'tempel.views.view', {'mode': 'html'}),
(r'^(?P<id>\d+).html$', 'tempel.views.view', {'mode': 'html'}),
(r'^(?P<id>\d+).txt$', 'tempel.views.view', {'mode': 'txt'}),
(r'^e/(?P<id>\d+)/download/$', 'tempel.views.download'),
(r'^$', 'tempel.views.index'),
)
|
Fix globbing pattern in Modernizr taks when not defined
|
import config from '../lib/config';
import log from 'fancy-log';
import pump from 'pump';
import gulpModernizr from 'gulp-modernizr';
import terser from 'gulp-terser';
import { src, dest, task } from 'gulp';
/**
* Check .js and .scss source files for Modernizr tests and create a custom
* Modernizr build containing those tests.
*
* Note: this task isn't run on watch, you can run it manually via `gulp modernizr`
*/
export const modernizr = done => {
if (!config.get('tasks.sass.src') && !config.get('tasks.javascript.src')) {
log(`Skipping 'modernizr' task`);
return done();
}
return pump([
src([
config.get('tasks.sass.src'),
config.get('tasks.javascript.src'),
'!**/{vendor,polyfills}/**/*.js',
].filter(entry => entry)),
gulpModernizr({
options: [
'setClasses',
],
...config.get('tasks.modernizr') || {},
}),
terser(),
dest(config.get('tasks.javascript.dist')),
], done);
};
task('modernizr', modernizr);
|
import config from '../lib/config';
import log from 'fancy-log';
import pump from 'pump';
import gulpModernizr from 'gulp-modernizr';
import terser from 'gulp-terser';
import { src, dest, task } from 'gulp';
/**
* Check .js and .scss source files for Modernizr tests and create a custom
* Modernizr build containing those tests.
*
* Note: this task isn't run on watch, you can run it manually via `gulp modernizr`
*/
export const modernizr = done => {
if (!config.get('tasks.sass.src') && !config.get('tasks.javascript.src')) {
log(`Skipping 'modernizr' task`);
return done();
}
return pump([
src([
config.get('tasks.sass.src') || '',
config.get('tasks.javascript.src') || '',
'!**/{vendor,polyfills}/**/*.js',
]),
gulpModernizr({
options: [
'setClasses',
],
...config.get('tasks.modernizr') || {},
}),
terser(),
dest(config.get('tasks.javascript.dist')),
], done);
};
task('modernizr', modernizr);
|
Test MGI translation loading too.
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import and_
import mgi
import mgi.load
import mgi.models
from translations.models import Translation
def test_mgi_load():
engine = create_engine('sqlite://')
metadata = mgi.models.Base.metadata
metadata.bind = engine
metadata.create_all()
sessionmaker_ = sessionmaker(engine)
_testinput = 'tests/data/'
nr_entries = mgi.load.load(_testinput, sessionmaker_)
session = sessionmaker_ ()
loaded = session.query(mgi.models.Entry).count()
assert nr_entries == 15
assert loaded == nr_entries
# MGI:1915545 is in the file but does not have a cellular component
assert not session.query(mgi.models.Entry).filter(mgi.models.Entry.mgi_id == 'MGI:1915545').count()
assert session.query(Translation).filter(
and_(Translation.input_namespace == 'ensembl:gene_id',
Translation.input_name == 'ENSMUSG00000026004',
Translation.output_namespace == 'mgi')).count()
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import mgi
import mgi.load
import mgi.models
def test_mgi_load():
engine = create_engine('sqlite://')
metadata = mgi.models.Base.metadata
metadata.bind = engine
metadata.create_all()
sessionmaker_ = sessionmaker(engine)
_testinput = 'tests/data/'
nr_entries = mgi.load.load(_testinput, sessionmaker_)
session = sessionmaker_ ()
loaded = session.query(mgi.models.Entry).count()
assert nr_entries == 15
assert loaded == nr_entries
# MGI:1915545 is in the file but does not have a cellular component
assert not session.query(mgi.models.Entry).filter(mgi.models.Entry.mgi_id == 'MGI:1915545').count()
|
Use a transparent pixel to hold the height
|
Photo = function (doc) {
_.extend(this, doc);
};
_.extend(Photo.prototype, {
getImgTag: function (dimension) {
return {
'class': 'lazy',
'src': 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
'data-src': _.str.sprintf(
'%s/photos/%s/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
'data-src-retina': _.str.sprintf(
'%s/photos/%s@2x/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
alt: this.title,
width: dimension,
height: dimension
};
}
});
Photos = new Mongo.Collection('Photos', {
transform: function (doc) { return new Photo(doc); }
});
|
Photo = function (doc) {
_.extend(this, doc);
};
_.extend(Photo.prototype, {
getImgTag: function (dimension) {
return {
'class': 'lazy',
'data-src': _.str.sprintf(
'%s/photos/%s/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
'data-src-retina': _.str.sprintf(
'%s/photos/%s@2x/%s',
Meteor.settings.public.uri.cdn,
dimension,
this.filename
),
alt: this.title,
width: dimension,
height: dimension
};
}
});
Photos = new Mongo.Collection('Photos', {
transform: function (doc) { return new Photo(doc); }
});
|
Remove "less-than" restrictions on Astropy, LXML.
I think I put these in place before I had Travis-CI cron-jobs available.
Therefore wanted to avoid future unknowns. Now at least an email gets sent
when there's a new release and it breaks something.
|
#!/usr/bin/env python
from setuptools import find_packages, setup
import versioneer
install_requires = [
"astropy>=1.2",
"lxml>=2.3",
'iso8601',
'orderedmultidict',
'pytz',
'six',
]
test_requires = [
'pytest>3',
'coverage'
]
extras_require = {
'test': test_requires,
'all': test_requires,
}
setup(
name="voevent-parse",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages=find_packages(where='src'),
package_dir={'': 'src'},
package_data={'voeventparse': ['fixtures/*.xml']},
description="Convenience routines for parsing and manipulation of "
"VOEvent XML packets.",
author="Tim Staley",
author_email="github@timstaley.co.uk",
url="https://github.com/timstaley/voevent-parse",
install_requires=install_requires,
extras_require=extras_require,
)
|
#!/usr/bin/env python
from setuptools import find_packages, setup
import versioneer
install_requires = [
"astropy>=1.2, <3",
"lxml>=2.3, <4.0",
'iso8601',
'orderedmultidict',
'pytz',
'six',
]
test_requires = [
'pytest>3',
'coverage'
]
extras_require = {
'test': test_requires,
'all': test_requires,
}
setup(
name="voevent-parse",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages=find_packages(where='src'),
package_dir={'': 'src'},
package_data={'voeventparse': ['fixtures/*.xml']},
description="Convenience routines for parsing and manipulation of "
"VOEvent XML packets.",
author="Tim Staley",
author_email="github@timstaley.co.uk",
url="https://github.com/timstaley/voevent-parse",
install_requires=install_requires,
extras_require=extras_require,
)
|
Stop the HRM when display is off
|
/*
Returns the Heart Rate BPM, with off-wrist detection.
Callback rasied to update your UI.
*/
import { display } from "display";
import { HeartRateSensor } from "heart-rate";
import { user } from "user-profile";
let hrm, watchID, hrmCallback;
let lastReading = 0;
let heartRate;
export function initialize(callback) {
hrmCallback = callback;
hrm = new HeartRateSensor();
start();
lastReading = hrm.timestamp;
}
function getReading() {
if (hrm.timestamp === lastReading) {
heartRate = "--";
} else {
heartRate = hrm.heartRate;
}
lastReading = hrm.timestamp;
hrmCallback({
bpm: heartRate,
zone: user.heartRateZone(hrm.heartRate || 0),
restingHeartRate: user.restingHeartRate
});
}
display.addEventListener("change", function() {
if (display.on) {
start();
} else {
stop();
}
})
function start() {
if (!watchID) {
hrm.start();
getReading();
watchID = setInterval(getReading, 1000);
}
}
function stop() {
hrm.stop();
clearInterval(watchID);
watchID = null;
}
|
/*
Returns the Heart Rate BPM, with off-wrist detection.
Callback rasied to update your UI.
*/
import { display } from "display";
import { HeartRateSensor } from "heart-rate";
import { user } from "user-profile";
let hrm, watchID, hrmCallback;
let lastReading = 0;
let heartRate;
export function initialize(callback) {
hrmCallback = callback;
hrm = new HeartRateSensor();
hrm.start();
lastReading = hrm.timestamp;
start();
}
function getReading() {
if (hrm.timestamp === lastReading) {
heartRate = "--";
} else {
heartRate = hrm.heartRate;
}
lastReading = hrm.timestamp;
hrmCallback({
bpm: heartRate,
zone: user.heartRateZone(hrm.heartRate || 0),
restingHeartRate: user.restingHeartRate
});
}
display.addEventListener("change", function() {
if (display.on) {
start();
} else {
stop();
}
})
function start() {
if (!watchID) {
getReading();
watchID = setInterval(getReading, 1000);
}
}
function stop() {
clearInterval(watchID);
watchID = null;
}
|
Fix error message in t.test()
|
'use strict';
const t = require('tcomb-validation');
const Type = t.irreducible('Type', t.isType);
function test (value, type) {
const result = t.validate(value, type);
if (!result.isValid()) t.fail(result.firstError().message);
}
function typedFunc (obj) {
return t.func(obj.inputs || [], obj.outputs || t.Any).of(obj.fn);
}
module.exports = t.mixin(t, {
Type,
test: typedFunc({
inputs: [t.Any, Type],
fn: test
}),
typedFunc: typedFunc({
inputs: [t.struct({
inputs: t.maybe(t.Array),
output: t.maybe(Type),
fn: t.Function
})],
output: t.Function,
fn: typedFunc
})
});
|
'use strict';
const t = require('tcomb-validation');
const Type = t.irreducible('Type', t.isType);
function test (value, type) {
const result = t.validate(value, type);
if (!result.isValid()) t.fail(result.firstError());
}
function typedFunc (obj) {
return t.func(obj.inputs || [], obj.outputs || t.Any).of(obj.fn);
}
module.exports = t.mixin(t, {
Type,
test: typedFunc({
inputs: [t.Any, Type],
fn: test
}),
typedFunc: typedFunc({
inputs: [t.struct({
inputs: t.maybe(t.Array),
output: t.maybe(Type),
fn: t.Function
})],
output: t.Function,
fn: typedFunc
})
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.