text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update regex property validator such that it works with null | /*
* Copyright 2013 the original author or 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 org.broadleafcommerce.openadmin.server.service.persistence.validation;
import org.broadleafcommerce.openadmin.dto.Entity;
import java.io.Serializable;
import java.util.Map;
/**
* Validates a field against a configured 'regularExpression' item
*
* @author Phillip Verheyden
*/
public class RegexPropertyValidator implements PropertyValidator {
@Override
public boolean validate(Entity entity, Map<String, String> validationConfiguration, Serializable instance, String value) {
String expression = validationConfiguration.get("regularExpression");
return (value == null) ? true : value.matches(expression);
}
}
| /*
* Copyright 2013 the original author or 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 org.broadleafcommerce.openadmin.server.service.persistence.validation;
import org.broadleafcommerce.openadmin.dto.Entity;
import java.io.Serializable;
import java.util.Map;
/**
* Validates a field against a configured 'regularExpression' item
*
* @author Phillip Verheyden
*/
public class RegexPropertyValidator implements PropertyValidator {
@Override
public boolean validate(Entity entity, Map<String, String> validationConfiguration, Serializable instance, String value) {
String expression = validationConfiguration.get("regularExpression");
return value.matches(expression);
}
}
|
Remove stack trace from missing Essentials warp | package com.elmakers.mine.bukkit.warp;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.Warps;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
/**
* Encapsulates Essentials warps
*/
public class EssentialsWarps {
private final Warps warps;
private EssentialsWarps(Warps warps) {
this.warps = warps;
}
public static EssentialsWarps create(Plugin plugin) {
if (plugin instanceof Essentials) {
Essentials essentials = (Essentials)plugin;
Warps warps = essentials.getWarps();
return warps == null ? null : new EssentialsWarps(warps);
}
return null;
}
public Location getWarp(String warpName) {
try {
return warps.getWarp(warpName);
} catch (Exception ex) {
}
return null;
}
}
| package com.elmakers.mine.bukkit.warp;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.Warps;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
/**
* Encapsulates Essentials warps
*/
public class EssentialsWarps {
private final Warps warps;
private EssentialsWarps(Warps warps) {
this.warps = warps;
}
public static EssentialsWarps create(Plugin plugin) {
if (plugin instanceof Essentials) {
Essentials essentials = (Essentials)plugin;
Warps warps = essentials.getWarps();
return warps == null ? null : new EssentialsWarps(warps);
}
return null;
}
public Location getWarp(String warpName) {
try {
return warps.getWarp(warpName);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
|
Define date in docs dynamically
Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com> | import datetime
import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = f"2016-{datetime.date.today().year}, {author}"
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.viewcode"
]
source_suffix = ".rst"
master_doc = "index"
language = None
exclude_patterns = ["build", "*.egg*"]
# Output options
html_theme = "sphinx_rtd_theme"
html_show_sphinx = False
html_baseurl = "pymanopt.org"
htmlhelp_basename = "pymanoptdoc"
html_last_updated_fmt = ""
# autodoc
autodoc_default_options = {
"member-order": "bysource",
"members": True,
"undoc-members": True,
"show-inheritance": True
}
| import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = "2016-2021, {:s}".format(author)
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.viewcode"
]
source_suffix = ".rst"
master_doc = "index"
language = None
exclude_patterns = ["build", "*.egg*"]
# Output options
html_theme = "sphinx_rtd_theme"
html_show_sphinx = False
html_baseurl = "www.pymanopt.org"
htmlhelp_basename = "pymanoptdoc"
html_last_updated_fmt = ""
# autodoc
autodoc_default_options = {
"member-order": "bysource",
"members": True,
"undoc-members": True,
"show-inheritance": True
}
|
Fix for typed arrays not being transferred | var ResultCollector = require('./result_collector');
var work = require('webworkify');
var workers = [];
Object.defineProperty(module.exports, 'length', {
get: function(){
return workers.length;
}
});
module.exports.init = function(workersCount){
while (workersCount--) {
var worker = work(require('./worker.js'));
workers.push(worker);
}
};
module.exports.terminate = function(){
workers.forEach(function(w){
w.terminate();
});
workers = [];
};
module.exports.sendPacks = function(packs, callback){
var collector = new ResultCollector(workers.length, callback);
packs.forEach(function(pack, index){
var onMessageHandler = function (event){
event.target.removeEventListener('error', onErrorHandler);
event.target.removeEventListener('message', onMessageHandler);
return collector.onPart(event.data);
};
var onErrorHandler = function (event){
event.preventDefault();
event.target.removeEventListener('error', onErrorHandler);
event.target.removeEventListener('message', onMessageHandler);
return collector.onError(event.message);
};
workers[index].addEventListener('error', onErrorHandler);
workers[index].addEventListener('message', onMessageHandler);
if (pack.buffer){
workers[index].postMessage(pack, [ pack.buffer ]);
} else {
workers[index].postMessage(pack);
}
});
}; | var ResultCollector = require('./result_collector');
var work = require('webworkify');
var workers = [];
Object.defineProperty(module.exports, 'length', {
get: function(){
return workers.length;
}
});
module.exports.init = function(workersCount){
while (workersCount--) {
var worker = work(require('./worker.js'));
workers.push(worker);
}
};
module.exports.terminate = function(){
workers.forEach(function(w){
w.terminate();
});
workers = [];
};
module.exports.sendPacks = function(packs, callback){
var collector = new ResultCollector(workers.length, callback);
packs.forEach(function(pack, index){
var onMessageHandler = function (event){
event.target.removeEventListener('error', onErrorHandler);
event.target.removeEventListener('message', onMessageHandler);
return collector.onPart(event.data);
};
var onErrorHandler = function (event){
event.preventDefault();
event.target.removeEventListener('error', onErrorHandler);
event.target.removeEventListener('message', onMessageHandler);
return collector.onError(event.message);
};
workers[index].addEventListener('error', onErrorHandler);
workers[index].addEventListener('message', onMessageHandler);
workers[index].postMessage(pack);
});
}; |
Add default ordering to weight entries | # This file is part of Workout Manager.
#
# Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Workout Manager 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 Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
class WeightEntry(models.Model):
"""Model for a weight point
"""
creation_date = models.DateField(_('Creation date'))
weight = models.FloatField(_('Weight'))
user = models.ForeignKey(User, verbose_name = _('User'))
# Metaclass to set some other properties
class Meta:
ordering = ["creation_date", ]
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s: %s kg" % (self.creation_date, self.weight)
| # This file is part of Workout Manager.
#
# Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Workout Manager 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 Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
class WeightEntry(models.Model):
"""Model for a weight point
"""
creation_date = models.DateField(_('Creation date'))
weight = models.FloatField(_('Weight'))
user = models.ForeignKey(User, verbose_name = _('User'))
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s: %s kg" % (self.creation_date, self.weight)
|
Reformat the code to match the rest of Paper.js | /**
* Imports svg into items with groups
* Stetson Alpha - Paper.js
*
*/
var ImportSVG = this.ImportSVG = Base.extend({
{
//initialize
initialize: function()
{
},
/**
*
* Takes the svg dom obj and parses the data
* to create a layer with groups (if needed) with
* items inside. Should support nested groups.
*
* takes in a svg object (xml dom)
* returns Paper.js Layer
*/
importSVG: function(svg)
{
//TODO: return layer;
},
/**
* Creates a Paper.js Group by parsing
* a specific svg g node
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
importGroup: function(svg)
{
//TODO: return group;
},
/**
* Creates a Paper.js Path by parsing
* a specific svg node (rect, path, circle, polygon, etc)
* and creating the right path object based on the svg type.
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
importPath: function(svg)
{
//TODO: return path;
}
}); | /**
* Imports svg into items with groups
* Stetson Alpha - Paper.js
*
*/
var ImportSVG = function()
{
//initialize
function initialize()
{
};
/**
*
* Takes the svg dom obj and parses the data
* to create a layer with groups (if needed) with
* items inside. Should support nested groups.
*
* takes in a svg object (xml dom)
* returns Paper.js Layer
*/
this.importSVG = function(svg)
{
return layer;
};
/**
* Creates a Paper.js Group by parsing
* a specific svg g node
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importGroup(svg)
{
return group;
};
/**
* Creates a Paper.js Path by parsing
* a specific svg node (rect, path, circle, polygon, etc)
* and creating the right path object based on the svg type.
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importPath(svg)
{
return path;
};
initialize(); // calls the init function after class is loaded
}; |
Make `test_except` swift test pass
Currently it is expected to fail. This asserts that the correct
exception is raised. Fixes #155. | #!/usr/bin/env python3.5
from nose.tools import assert_raises
import parsl
from parsl import *
parsl.set_stream_logger()
from parsl.executors.swift_t import *
def foo(x, y):
return x * y
def slow_foo(x, y):
import time
time.sleep(x)
return x * y
def bad_foo(x, y):
time.sleep(x)
return x * y
def test_simple():
print("Start")
tex = TurbineExecutor()
x = tex.submit(foo, 5, 10)
print("Got: ", x)
print("X result: ", x.result())
assert x.result() == 50, "X != 50"
print("done")
def test_slow():
futs = {}
tex = TurbineExecutor()
for i in range(0, 3):
futs[i] = tex.submit(slow_foo, 1, 2)
total = sum([futs[i].result(timeout=10) for i in futs])
assert total == 6, "expected 6, got {}".format(total)
def test_except():
def get_bad_result():
tex = TurbineExecutor()
x = tex.submit(bad_foo, 5, 10)
return x.result()
assert_raises(NameError, get_bad_result)
if __name__ == "__main__":
# test_simple()
# test_slow()
test_except()
print("Done")
| #!/usr/bin/env python3.5
import parsl
from parsl import *
parsl.set_stream_logger()
from parsl.executors.swift_t import *
def foo(x, y):
return x * y
def slow_foo(x, y):
import time
time.sleep(x)
return x * y
def bad_foo(x, y):
time.sleep(x)
return x * y
def test_simple():
print("Start")
tex = TurbineExecutor()
x = tex.submit(foo, 5, 10)
print("Got : ", x)
print("X result : ", x.result())
assert x.result() == 50, "X != 50"
print("done")
def test_except():
print("Start")
tex = TurbineExecutor()
x = tex.submit(bad_foo, 5, 10)
print("Got : ", x)
print("X exception : ", x.exception())
print("X result : ", x.result())
print("done")
if __name__ == "__main__":
# test_simple()
test_except()
exit(0)
futs = {}
for i in range(0, 1):
futs[i] = tex.submit(slow_foo, 3, 10)
x.result(timeout=10)
for x in range(0, 10):
print(futs)
time.sleep(4)
print("Done")
|
test(commit-all): Test for project folder limit | /** @babel */
import commitAll from "../../lib/commands/commit-all";
import commit from "../../lib/commands/commit";
import {getFilePath, removeGitRoot, createGitRoot, files} from "../mocks";
describe("commit-all", function () {
beforeEach(async function () {
await atom.packages.activatePackage("git-menu");
this.gitRoot = await createGitRoot();
this.filePaths = getFilePath(this.gitRoot, [files.t1]);
});
afterEach(async function () {
await removeGitRoot(this.gitRoot);
});
it("should call commit with project folders", async function () {
spyOn(commit, "command").and.callFake(() => Promise.resolve());
await commitAll.command(this.filePaths);
expect(commit.command.calls.mostRecent().args[0]).toEqual(atom.project.getPaths());
});
it("should only send project folders that contain filePaths", async function () {
spyOn(commit, "command").and.callFake(() => Promise.resolve());
const [projectFolder] = atom.project.getPaths();
spyOn(atom.project, "getPaths").and.callFake(() => [projectFolder, "test"]);
await commitAll.command(this.filePaths);
expect(commit.command.calls.mostRecent().args[0]).toEqual([projectFolder]);
});
});
| /** @babel */
import commitAll from "../../lib/commands/commit-all";
import commit from "../../lib/commands/commit";
import {getFilePath, removeGitRoot, createGitRoot, files} from "../mocks";
describe("commit-all", function () {
beforeEach(async function () {
await atom.packages.activatePackage("git-menu");
this.gitRoot = await createGitRoot();
this.filePaths = getFilePath(this.gitRoot, [files.t1]);
});
afterEach(async function () {
await removeGitRoot(this.gitRoot);
});
it("should call commit with project folders", async function () {
spyOn(commit, "command").and.callFake(() => Promise.resolve());
await commitAll.command(this.filePaths);
expect(commit.command.calls.mostRecent().args[0]).toEqual(atom.project.getPaths());
});
});
|
Fix HasQueryTrait, return model objects collection | <?php
namespace Milax\Mconsole\Traits;
use Milax\Mconsole\Exceptions\ModelPropertyException;
use Milax\Mconsole\Processors\TableProcessor;
use View;
trait HasQueryTraits
{
/**
* Run queries with Paginatable and Redirectable traits
*
* @return
*/
public function run($view, $cb, $query = null)
{
// Check if $model property exists
if (!property_exists($this, 'model')) {
throw new ModelPropertyException('Controller must have protected $model property.');
}
// Check if $query property exists
if (!property_exists($this, 'query')) {
if ($query === null) {
$model = $this->model;
$this->query = $model::query();
} else {
$this->query = $query;
}
}
// Filterable Trait
if (method_exists($this, 'filtrate'))
$this->query = $this->filtrate($this->query);
if (method_exists($this, 'paginate')) {
$this->items = $this->query->paginate($this->perPage);
View::share('paging', $this->items);
} else {
$this->items = $this->query->get();
}
return view($view, [
'items' => TableProcessor::processItems($cb, $this->items),
]);
}
} | <?php
namespace Milax\Mconsole\Traits;
use Milax\Mconsole\Exceptions\ModelPropertyException;
use Milax\Mconsole\Processors\TableProcessor;
use View;
trait HasQueryTraits
{
/**
* Run queries with Paginatable and Redirectable traits
*
* @return
*/
public function run($view, $cb, $query = null)
{
// Check if $model property exists
if (!property_exists($this, 'model')) {
throw new ModelPropertyException('Controller must have protected $model property.');
}
// Check if $query property exists
if (!property_exists($this, 'query')) {
if ($query === null) {
$model = $this->model;
$this->query = $model::getQuery();
} else {
$this->query = $query;
}
}
// Filterable Trait
if (method_exists($this, 'filtrate'))
$this->query = $this->filtrate($this->query);
if (method_exists($this, 'paginate')) {
$this->items = $this->query->paginate($this->perPage);
View::share('paging', $this->items);
} else {
$this->items = $this->query->get();
}
return view($view, [
'items' => TableProcessor::processItems($cb, $this->items),
]);
}
} |
Update expected results of generated liting | // Package main is used for testing of generated 'views' listing.
// There is no way to include a new import dynamically, thus
// we are running this test from generate_test.go
// as a new command using exec package.
package main
import (
"../assets/views"
"github.com/anonx/sunplate/log"
)
func main() {
if l := len(views.Context); l != 2 {
log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l)
}
//
// Make sure templates are presented in the format we expect.
//
for k, v := range expectedValues {
if views.Context[k] != v {
log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context)
}
}
}
var expectedValues = map[string]string{
"test1.template": "testdata/views/test1.template",
"test2.template": "testdata/views/test2.template",
}
| // Package main is used for testing of generated 'views' listing.
// There is no way to include a new import dynamically, thus
// we are running this test from generate_test.go
// as a new command using exec package.
package main
import (
"../assets/views"
"github.com/anonx/sunplate/log"
)
func main() {
if l := len(views.Context); l != 2 {
log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l)
}
//
// Make sure templates are presented in the format we expect.
//
for k, v := range expectedValues {
if views.Context[k] != v {
log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context)
}
}
}
var expectedValues = map[string]string{
"testdata/views/test1.template": "testdata/views/test1.template",
"testdata/views/test2.template": "testdata/views/test2.template",
}
|
Add type to search results | // User Model
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
type: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING, allowNull: false },
email: { type: DataTypes.STRING, allowNull: false },
password: { type: DataTypes.STRING, allowNull: false },
salt: { type: DataTypes.STRING, allowNull: false },
postal: { type: DataTypes.STRING, allowNull: false },
token: { type: DataTypes.STRING, allowNull: true }
}, {
associate: function(models) {
User.hasOne(models.Profile);
User.hasMany(models.Message, { as: 'SentMessages', foreignKey: 'SenderId' });
User.hasMany(models.Message, { as: 'ReceivedMessages', foreignKey: 'ReceiverId' });
},
getterMethods: {
isTutor: function() {
return this.type === 1;
}
},
instanceMethods: {
getSimple: function() {
var obj = {};
obj.type = this.type;
obj.name = this.name;
obj.email = this.email;
obj.postal = this.postal;
obj.profile = this.profile.getSimple();
return obj;
}
}
});
return User;
}
| // User Model
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
type: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING, allowNull: false },
email: { type: DataTypes.STRING, allowNull: false },
password: { type: DataTypes.STRING, allowNull: false },
salt: { type: DataTypes.STRING, allowNull: false },
postal: { type: DataTypes.STRING, allowNull: false },
token: { type: DataTypes.STRING, allowNull: true }
}, {
associate: function(models) {
User.hasOne(models.Profile);
User.hasMany(models.Message, { as: 'SentMessages', foreignKey: 'SenderId' });
User.hasMany(models.Message, { as: 'ReceivedMessages', foreignKey: 'ReceiverId' });
},
getterMethods: {
isTutor: function() {
return this.type === 1;
}
},
instanceMethods: {
getSimple: function() {
var obj = {};
obj.name = this.name;
obj.email = this.email;
obj.postal = this.postal;
obj.profile = this.profile.getSimple();
return obj;
}
}
});
return User;
}
|
Fix the static resources path | import {Server} from 'hapi'
import inert from 'inert'
import path from 'path'
import getProjects from './app/get-projects'
/**
* @param {string} configFilename The config filename
* @param {number} port The port number
*/
export function serve(configFilename, port) {
const server = new Server()
server.connection({port})
server.register(inert, err => {
if (err) {
console.log(err.stack)
process.exit(1)
}
server.route({
method: 'GET',
path: '/api/projects',
handler: (request, reply) => {
reply(getProjects(configFilename))
}
})
server.route({
method: 'GET',
path: '/site/{param*}',
handler: { directory: { path: `${path.dirname(__dirname)}/site`, listing: true } }
})
server.start(err => {
if (err) {
console.log(err.stack)
return
}
try {
// checks if the config file is ok, does not use the returns projects object
getProjects(configFilename)
} catch (e) {
console.log(e.stack)
process.exit(1)
}
console.log('Server running at:', server.info.uri + '/site')
})
})
}
| import {Server} from 'hapi'
import inert from 'inert'
import getProjects from './app/get-projects'
/**
* @param {string} configFilename The config filename
* @param {number} port The port number
*/
export function serve(configFilename, port) {
const server = new Server()
server.connection({port})
server.register(inert, err => {
if (err) {
console.log(err.stack)
process.exit(1)
}
server.route({
method: 'GET',
path: '/api/projects',
handler: (request, reply) => {
reply(getProjects(configFilename))
}
})
server.route({
method: 'GET',
path: '/site/{param*}',
handler: { directory: { path: 'site', listing: true } }
})
server.start(err => {
if (err) {
console.log(err.stack)
return
}
try {
// checks if the config file is ok, does not use the returns projects object
getProjects(configFilename)
} catch (e) {
console.log(e.stack)
process.exit(1)
}
console.log('Server running at:', server.info.uri + '/site')
})
})
}
|
Fix incorrect operators on Metadata.Equal method | package state
import "encoding/json"
type Metadata struct {
Name string // Unique name to associate with a state
Type string // The type of state "package", "file", etc.
State string // The desired state "installed", "rendered", etc.
}
func (md *Metadata) Equal(metadata *Metadata) bool {
return metadata.Name == md.Name && metadata.Type == md.Type && metadata.State == md.State
}
func MetadataFromJSON(data json.RawMessage) (Metadata, error) {
metadata := Metadata{}
raw := make(map[string]json.RawMessage)
err := json.Unmarshal(data, &raw)
if err != nil {
return metadata, err
}
for key, value := range raw {
if key == "metadata" {
err := json.Unmarshal(value, &metadata)
if err != nil {
return metadata, err
}
}
}
return metadata, nil
}
| package state
import "encoding/json"
type Metadata struct {
Name string // Unique name to associate with a state
Type string // The type of state "package", "file", etc.
State string // The desired state "installed", "rendered", etc.
}
func (md *Metadata) Equal(metadata *Metadata) bool {
return metadata.Name == md.Name || metadata.Type == md.Type || metadata.State == md.State
}
func MetadataFromJSON(data json.RawMessage) (Metadata, error) {
metadata := Metadata{}
raw := make(map[string]json.RawMessage)
err := json.Unmarshal(data, &raw)
if err != nil {
return metadata, err
}
for key, value := range raw {
if key == "metadata" {
err := json.Unmarshal(value, &metadata)
if err != nil {
return metadata, err
}
}
}
return metadata, nil
}
|
Add some boilerplate checks to the exception context integration | <?php
namespace Sentry\Laravel\Integration;
use Sentry\Event;
use Sentry\EventHint;
use Sentry\SentrySdk;
use Sentry\State\Scope;
use Sentry\Integration\IntegrationInterface;
class ExceptionContextIntegration implements IntegrationInterface
{
public function setupOnce(): void
{
Scope::addGlobalEventProcessor(static function (Event $event, ?EventHint $hint = null): Event {
$self = SentrySdk::getCurrentHub()->getIntegration(self::class);
if (!$self instanceof self) {
return $event;
}
if ($hint === null || $hint->exception === null) {
return $event;
}
if (!method_exists($hint->exception, 'context')) {
return $event;
}
$context = $hint->exception->context();
if (is_array($context)) {
$event->setExtra(['exception_context' => $context]);
}
return $event;
});
}
}
| <?php
namespace Sentry\Laravel\Integration;
use Sentry\Event;
use Sentry\EventHint;
use Sentry\State\Scope;
use Sentry\Integration\IntegrationInterface;
class ExceptionContextIntegration implements IntegrationInterface
{
public function setupOnce(): void
{
Scope::addGlobalEventProcessor(static function (Event $event, ?EventHint $hint = null): Event {
if ($hint === null || $hint->exception === null) {
return $event;
}
if (!method_exists($hint->exception, 'context')) {
return $event;
}
$context = $hint->exception->context();
if (is_array($context)) {
$event->setExtra(['exception_context' => $context]);
}
return $event;
});
}
}
|
Fix secret:generate command to simply generate random 32-char length string | <?php
/**
* This file is part of the PHPLucidFrame library.
* The script executes the command `php lucidframe secret:generate [options]`
*
* @package PHPLucidFrame\Console
* @since PHPLucidFrame v 1.11.0
* @copyright Copyright (c), PHPLucidFrame.
* @author Sithu K. <cithukyaw@gmail.com>
* @link http://phplucidframe.com
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE
*/
_consoleCommand('secret:generate')
->setDescription('Generate a secret key')
->addOption('show', 's', 'Display the generated secret key', null, LC_CONSOLE_OPTION_NOVALUE)
->setDefinition(function(\LucidFrame\Console\Command $cmd) {
$secret = _randomCode(32);
$file = INC . '.secret';
file_put_contents($file, $secret . PHP_EOL);
if ($cmd->getOption('show')) {
_writeln($secret);
}
})
->register();
| <?php
/**
* This file is part of the PHPLucidFrame library.
* The script executes the command `php lucidframe secret:generate [options]`
*
* @package PHPLucidFrame\Console
* @since PHPLucidFrame v 1.11.0
* @copyright Copyright (c), PHPLucidFrame.
* @author Sithu K. <cithukyaw@gmail.com>
* @link http://phplucidframe.com
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE
*/
_consoleCommand('secret:generate')
->setDescription('Generate a secret hash key')
->addOption('method', 'm', 'The hashing algorithm method (e.g. "md5", "sha256", etc..)', 'md5')
->addOption('data', 'd', 'Secret text to be hashed.')
->setDefinition(function(\LucidFrame\Console\Command $cmd) {
$data = $cmd->getOption('data');
if (!$data) {
$data = time();
}
$secret = hash($cmd->getOption('method'), $data) . "\n";
$file = INC . '.secret';
file_put_contents($file, $secret);
})
->register();
|
Reorder nav items in main-header view | <header class="main-header">
<!-- Logo -->
<a href="{{ url('') }}" class="logo">
<span class="logo-mini">O<b>D</b></span>
<span class="logo-lg">Open<b>Dominion</b></span>
</a>
<!-- Header Navbar -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button -->
<a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
@include('partials.staff-nav')
@include('partials.wiki-nav')
@include('partials.notification-nav')
@include('partials.auth-user-nav')
</ul>
</div>
</nav>
</header>
| <header class="main-header">
<!-- Logo -->
<a href="{{ url('') }}" class="logo">
<span class="logo-mini">O<b>D</b></span>
<span class="logo-lg">Open<b>Dominion</b></span>
</a>
<!-- Header Navbar -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button -->
<a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
@include('partials.notification-nav')
@include('partials.wiki-nav')
@include('partials.staff-nav')
@include('partials.auth-user-nav')
</ul>
</div>
</nav>
</header>
|
Update cmd to accept new return value | package main
import (
"fmt"
"os"
"strings"
"github.com/hackebrot/go-librariesio/librariesio"
)
func loadFromEnv(keys ...string) (map[string]string, error) {
env := make(map[string]string)
for _, key := range keys {
v := os.Getenv(key)
if v == "" {
return nil, fmt.Errorf("environment variable %q is required", key)
}
env[key] = v
}
return env, nil
}
func main() {
env, err := loadFromEnv("LIBRARIESIO_API_KEY")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%v\n", env)
c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
project, _, err := c.GetProject("pypi", "cookiecutter")
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%v\n", project)
}
| package main
import (
"fmt"
"os"
"strings"
"github.com/hackebrot/go-librariesio/librariesio"
)
func loadFromEnv(keys ...string) (map[string]string, error) {
env := make(map[string]string)
for _, key := range keys {
v := os.Getenv(key)
if v == "" {
return nil, fmt.Errorf("environment variable %q is required", key)
}
env[key] = v
}
return env, nil
}
func main() {
env, err := loadFromEnv("LIBRARIESIO_API_KEY")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%v\n", env)
c := librariesio.NewClient(strings.TrimSpace(env["LIBRARIESIO_API_KEY"]))
project, err := c.GetProject("pypi", "cookiecutter")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "%v\n", project)
}
|
Increase cache tile duration from 6 hours to 1 week | import logging
from time import time
from pylons import tmpl_context as c
from adhocracy import config
from adhocracy.lib.cache import memoize
log = logging.getLogger(__name__)
class BaseTile(object):
'''
Base class for tiles
'''
def render_tile(template_name, def_name, tile, cached=False, **kwargs):
from adhocracy.lib import templating
begin_time = time()
def render():
return templating.render_def(template_name, def_name,
tile=tile, **kwargs)
rendered = ""
if cached and config.get_bool('adhocracy.cache_tiles'):
@memoize('tile_cache' + template_name + def_name, 7 * 86400)
def _cached(**kwargs):
return render()
rendered = _cached(locale=c.locale, **kwargs)
else:
rendered = render()
if False:
log.debug("Rendering tile %s:%s took %sms" % (
template_name, def_name, (time() - begin_time) * 1000))
return rendered
| import logging
from time import time
from pylons import tmpl_context as c
from adhocracy import config
from adhocracy.lib.cache import memoize
log = logging.getLogger(__name__)
class BaseTile(object):
'''
Base class for tiles
'''
def render_tile(template_name, def_name, tile, cached=False, **kwargs):
from adhocracy.lib import templating
begin_time = time()
def render():
return templating.render_def(template_name, def_name,
tile=tile, **kwargs)
rendered = ""
if cached and config.get_bool('adhocracy.cache_tiles'):
@memoize('tile_cache' + template_name + def_name, 86400 / 4)
def _cached(**kwargs):
return render()
rendered = _cached(locale=c.locale, **kwargs)
else:
rendered = render()
if False:
log.debug("Rendering tile %s:%s took %sms" % (
template_name, def_name, (time() - begin_time) * 1000))
return rendered
|
Use common testHarness in derived projects | from SCons.Script import *
import inspect
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
path = inspect.getfile(inspect.currentframe())
home = os.path.dirname(os.path.abspath(path)) + '/../..'
cmd = python + ' ' + home + '/tests/testHarness -C tests --diff-failed ' \
'--view-failed --view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
| from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
|
Fix namespace for PaymentCommand class | <?php
/**
* This file is part of the PHP Telegram Bot example-bot package.
* https://github.com/php-telegram-bot/example-bot/
*
* (c) PHP Telegram Bot Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generic message command
*
* Gets executed when any type of message is sent.
*/
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Commands\UserCommands\PaymentCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;
class GenericmessageCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'genericmessage';
/**
* @var string
*/
protected $description = 'Handle generic message';
/**
* @var string
*/
protected $version = '0.1.0';
/**
* Main command execution
*
* @return ServerResponse
*/
public function execute(): ServerResponse
{
$message = $this->getMessage();
$user_id = $message->getFrom()->getId();
// Handle successful payment
if ($payment = $message->getSuccessfulPayment()) {
return PaymentCommand::handleSuccessfulPayment($payment, $user_id);
}
return Request::emptyResponse();
}
}
| <?php
/**
* This file is part of the PHP Telegram Bot example-bot package.
* https://github.com/php-telegram-bot/example-bot/
*
* (c) PHP Telegram Bot Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generic message command
*
* Gets executed when any type of message is sent.
*/
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;
class GenericmessageCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'genericmessage';
/**
* @var string
*/
protected $description = 'Handle generic message';
/**
* @var string
*/
protected $version = '0.1.0';
/**
* Main command execution
*
* @return ServerResponse
*/
public function execute(): ServerResponse
{
$message = $this->getMessage();
$user_id = $message->getFrom()->getId();
// Handle successful payment
if ($payment = $message->getSuccessfulPayment()) {
return PaymentCommand::handleSuccessfulPayment($payment, $user_id);
}
return Request::emptyResponse();
}
}
|
Check it's actually a URL\! | <?php
namespace TwwSaml\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class AcsController extends AbstractActionController
{
public function indexAction()
{
$serviceLocator = $this->getServiceLocator();
$config = $serviceLocator->get('Config');
$auth = new \OneLogin_Saml2_Auth($config['tww-saml']['settings']);
$auth->processResponse();
$errors = $auth->getErrors();
if (!empty($errors)) {
print_r('<p>'.implode(', ', $errors).'</p>');
exit();
}
if (!$auth->isAuthenticated()) {
throw new \Exception('Authentication failed.');
}
$_SESSION['samlUserdata'] = $auth->getAttributes();
if (isset($_POST['RelayState']) && (strlen($_POST['RelayState']) > 0) && (\OneLogin_Saml2_Utils::getSelfURL() != $_POST['RelayState'])) {
return $this->redirect()->toUrl($_POST['RelayState']);
} else {
return $this->redirect()->toRoute('home');
}
}
}
| <?php
namespace TwwSaml\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class AcsController extends AbstractActionController
{
public function indexAction()
{
$serviceLocator = $this->getServiceLocator();
$config = $serviceLocator->get('Config');
$auth = new \OneLogin_Saml2_Auth($config['tww-saml']['settings']);
$auth->processResponse();
$errors = $auth->getErrors();
if (!empty($errors)) {
print_r('<p>'.implode(', ', $errors).'</p>');
exit();
}
if (!$auth->isAuthenticated()) {
throw new \Exception('Authentication failed.');
}
$_SESSION['samlUserdata'] = $auth->getAttributes();
if (isset($_POST['RelayState']) && \OneLogin_Saml2_Utils::getSelfURL() != $_POST['RelayState']) {
return $this->redirect()->toUrl($_POST['RelayState']);
} else {
return $this->redirect()->toRoute('home');
}
}
}
|
Add cDatePublic to indexed search result constructor | <?
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedSearchResult {
public function __construct($id, $name, $description, $score, $cPath, $content, $cDatePublic = false) {
$this->cID = $id;
$this->cName = $name;
$this->cDescription = $description;
$this->score = $score;
$this->cPath = $cPath;
$this->content = $content;
if ($cDatePublic) {
$this->setDate($cDatePublic);
}
$this->nh = Loader::helper('navigation');
}
public function getID() {return $this->cID;}
public function getName() {return $this->cName;}
public function getDescription() {return $this->cDescription;}
public function getScore() {return $this->score;}
public function getCollectionPath() {return $this->cPath;}
public function getCpath() {return $this->cPath;}
public function getBodyContent() {return $this->content;}
public function getDate($mask = '') {
if ($mask == '') {
$mask = t('Y-m-d H:i:s');
}
return date($mask, strtotime($this->cDate));
}
public function getPath() {
$c = Page::getByID($this->cID);
return $this->nh->getLinkToCollection($c, true);
}
public function setDate($date) { $this->cDate = $date;}
}
| <?
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedSearchResult {
public function __construct($id, $name, $description, $score, $cPath, $content) {
$this->cID = $id;
$this->cName = $name;
$this->cDescription = $description;
$this->score = $score;
$this->cPath = $cPath;
$this->content = $content;
$this->nh = Loader::helper('navigation');
}
public function getID() {return $this->cID;}
public function getName() {return $this->cName;}
public function getDescription() {return $this->cDescription;}
public function getScore() {return $this->score;}
public function getCollectionPath() {return $this->cPath;}
public function getCpath() {return $this->cPath;}
public function getBodyContent() {return $this->content;}
public function getDate($mask = '') {
if ($mask == '') {
$mask = t('Y-m-d H:i:s');
}
return date($mask, strtotime($this->cDate));
}
public function getPath() {
$c = Page::getByID($this->cID);
return $this->nh->getLinkToCollection($c, true);
}
public function setDate($date) { $this->cDate = $date;}
}
|
Make implementation node a comment rather than public documentation. | """
The qiprofile Mongodb data model.
The model field choices are listed in the preferred display order,
most common to least common.
The data capture client has the following responsibility:
* Validate the data upon input as determined by the model
validation documentation.
* Resolve conflicts between data capture and the model, e.g. the
default value or validation.
"""
# Note: mongoengine 0.8.7 has the following bug:
# * Each mongoengine non-embedded class embedded field must specify
# a class by reference rather than name, e.g.::
#
# class SessionDetail(mongoengine.Document):
# volumes = fields.ListField(field=mongoengine.EmbeddedDocumentField(Volume))
#
# rather than::
#
# class SessionDetail(mongoengine.Document):
# volumes = fields.ListField(field=mongoengine.EmbeddedDocumentField('Volume'))
#
# If the class is referenced by name, then the model is initialized, but
# an attempt to save an object results in the following validation error::
#
# Invalid embedded document instance provided
| """
The qiprofile Mongodb data model.
The model field choices are listed in the preferred display order,
most common to least common.
The data capture client has the following responsibility:
* Validate the data upon input as determined by the model
validation below.
* Resolve conflicts between data capture and the model, e.g. the
default value or validation.
:Note: mongoengine 0.8.7 has the following bug:
* Each mongoengine non-embedded class embedded field must specify
a class by reference rather than name, e.g.::
class SessionDetail(mongoengine.Document):
volumes = fields.ListField(field=mongoengine.EmbeddedDocumentField(Volume))
rather than::
class SessionDetail(mongoengine.Document):
volumes = fields.ListField(field=mongoengine.EmbeddedDocumentField('Volume'))
If the class is referenced by name, then the model is initialized, but
an attempt to save an object results in the following validation error::
Invalid embedded document instance provided
"""
|
Test that annotations are not inherited. | /*
* Copyright 2020 The jspecify 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.
*/
import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
@DefaultNonNull
interface CovariantReturns {
@Nullable
Object makeObject();
Lib<?> makeImplicitlyObjectBounded();
Lib<? extends @Nullable Object> makeExplicitlyObjectBounded();
interface Subtype extends CovariantReturns {
@Override
Object makeObject();
@Override
Lib<? extends Object> makeImplicitlyObjectBounded();
@Override
Lib<? extends Object> makeExplicitlyObjectBounded();
}
default void go(Subtype s) {
checkObject(s.makeObject());
checkLibOfObject(s.makeImplicitlyObjectBounded());
checkLibOfObject(s.makeExplicitlyObjectBounded());
}
void checkObject(Object o);
void checkLibOfObject(Lib<? extends Object> o);
interface Lib<T extends @Nullable Object> {}
}
| /*
* Copyright 2020 The jspecify 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.
*/
import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
@DefaultNonNull
interface CovariantReturns {
@Nullable
Object makeObject();
Lib<?> makeImplicitlyObjectBounded();
Lib<? extends @Nullable Object> makeExplicitlyObjectBounded();
interface Subtype extends CovariantReturns {
@Override
Object makeObject();
@Override
Lib<? extends Object> makeImplicitlyObjectBounded();
@Override
Lib<? extends Object> makeExplicitlyObjectBounded();
}
interface Lib<T extends @Nullable Object> {}
}
|
Add Arquillian Moco API to remote deployment | package org.jboss.arquillian.moco.client;
import org.jboss.arquillian.container.test.spi.RemoteLoadableExtension;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.moco.ReflectionHelper;
import org.jboss.arquillian.moco.api.Moco;
import org.jboss.arquillian.moco.container.MocoRemoteExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
public class MocoArchiveAppender implements AuxiliaryArchiveAppender {
@Override
public Archive<?> createAuxiliaryArchive() {
return ShrinkWrap.create(JavaArchive.class, "arquillian-moco.jar")
.addClass(ReflectionHelper.class)
.addPackage(Moco.class.getPackage())
.addPackage(MocoRemoteExtension.class.getPackage())
.addAsServiceProvider(RemoteLoadableExtension.class, MocoRemoteExtension.class);
}
}
| package org.jboss.arquillian.moco.client;
import org.jboss.arquillian.container.test.spi.RemoteLoadableExtension;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.moco.ReflectionHelper;
import org.jboss.arquillian.moco.container.MocoRemoteExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
public class MocoArchiveAppender implements AuxiliaryArchiveAppender {
@Override
public Archive<?> createAuxiliaryArchive() {
return ShrinkWrap.create(JavaArchive.class, "arquillian-moco.jar")
.addClass(ReflectionHelper.class)
.addPackage(MocoRemoteExtension.class.getPackage())
.addAsServiceProvider(RemoteLoadableExtension.class, MocoRemoteExtension.class);
}
}
|
Configure Firebase Test Lab Espresso test for MainActivity | /**
* Copyright 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.
*/
package com.google.firebase.codelab.friendlychat;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);
// Add instrumentation test here
@Test
public void verifySignUpButtonDisplayed() {
onView(ViewMatchers.withId(R.id.sign_in_button)).check(matches(isDisplayed()));
}
}
| /**
* Copyright 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.
*/
package com.google.firebase.codelab.friendlychat;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);
// Add instrumentation test here
}
|
Fix jshint warnings, some source formatting | angular.module('skjutsgruppen.factories', ['skjutsgruppen.JSONReader'])
.factory('AchievementsFactory', function (JSONReader) {
return {
getAchievements: function () {
return JSONReader.create('data/achievements.json', 'achievements', ['url']);
}
};
})
.factory('SettingsFactory', function (JSONReader) {
return {
getSettings: function() {
return JSONReader.create('data/settings.json', 'settings', ['url']);
},
updateSetting: function(settingId, newValue) {
console.log("Someone toggled the notification setting " + settingId + " and set it to " + newValue + "!");
}
};
})
.factory('MapFactory', function (JSONReader) {
return {
getCoordinates: function() {
return JSONReader.create('data/mapCoordinates.json', 'coordinates', ['url']);
}
};
});
| angular.module('skjutsgruppen.factories', ['skjutsgruppen.JSONReader'])
.factory('AchievementsFactory', function(JSONReader) {
return {
getAchievements: function() {
return JSONReader.create('data/achievements.json', 'achievements', ['url']);
}
}
})
.factory('SettingsFactory', function(JSONReader) {
return {
getSettings: function() {
return JSONReader.create('data/settings.json', 'settings', ['url']);
},
updateSetting: function(settingId, newValue) {
console.log("Someone toggled the notification setting " + settingId + " and set it to " + newValue + "!");
}
}
})
.factory('MapFactory', function(JSONReader) {
return {
getCoordinates: function() {
return JSONReader.create('data/mapCoordinates.json', 'coordinates', ['url']);
}
}
})
|
Fix compilation error on interface method override tag | /**
* Copyright 2016, RadiantBlue Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package model.job.type;
import model.job.PiazzaJobType;
import model.service.metadata.Service;
/**
* Represents the JSON Model for ingesting service metadata into Piazza for
* subsequent query, e.g. used when registering a service. This ingest allows
* subsequent searches for services.
*
*
*
*
*/
public class ServiceMetadataIngestJob implements PiazzaJobType {
public final String type = "servicemetadata-ingest";
public Service data;
public ServiceMetadataIngestJob() {
}
public String getType() {
return type;
}
public Service getData() {
return data;
}
public void setData(Service data) {
this.data = data;
}
}
| /**
* Copyright 2016, RadiantBlue Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package model.job.type;
import model.job.PiazzaJobType;
import model.service.metadata.Service;
/**
* Represents the JSON Model for ingesting service metadata into Piazza for subsequent query,
* e.g. used when registering a service. This ingest allows subsequent searches for services.
*
*
*
*/
public class ServiceMetadataIngestJob implements PiazzaJobType {
public final String type = "servicemetadata-ingest";
public Service data;
public ServiceMetadataIngestJob() {
}
@Override
public String getType() {
return type;
}
public Service getData() {
return data;
}
public void setData(Service data) {
this.data = data;
}
}
|
Rename export class for app generator | import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class AppGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
| import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class ServicesGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
|
Improve the invite_user action name. | from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(admin.ModelAdmin):
list_display = ('inviter', 'invitations_remaining')
def invite_user(modeladmin, request, queryset):
for invitation_request in queryset.all():
invitation = InvitationKey.objects.create_invitation(request.user)
invitation.send_to(invitation_request.email)
invitation_request.invited = True
invitation_request.save()
invite_user.short_description = "Invite selected invitation requests"
class InvitationRequestAdmin(admin.ModelAdmin):
list_display = ('email', 'invited')
actions = [invite_user]
admin.site.register(InvitationKey, InvitationKeyAdmin)
admin.site.register(InvitationUser, InvitationUserAdmin)
admin.site.register(InvitationRequest, InvitationRequestAdmin)
admin.site.register(InvitationCode)
| from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(admin.ModelAdmin):
list_display = ('inviter', 'invitations_remaining')
def invite_user(modeladmin, request, queryset):
for invitation_request in queryset.all():
invitation = InvitationKey.objects.create_invitation(request.user)
invitation.send_to(invitation_request.email)
invitation_request.invited = True
invitation_request.save()
invite_user.short_description = "Invite this user"
class InvitationRequestAdmin(admin.ModelAdmin):
list_display = ('email', 'invited')
actions = [invite_user]
admin.site.register(InvitationKey, InvitationKeyAdmin)
admin.site.register(InvitationUser, InvitationUserAdmin)
admin.site.register(InvitationRequest, InvitationRequestAdmin)
admin.site.register(InvitationCode)
|
Clean up variables a bit | var p5 = require('p5');
var pulsar = {};
pulsar.config = pulsarConfig;
pulsarConfig = undefined;
pulsar.sketch = function (p) {
var Receiver = require('./Receiver.js');
var receiver = new Receiver();
var Processor = require('./Processor.js');
var processor = new Processor();
var DrawingManager = require('./DrawingManager.js');
var dM = new DrawingManager(p);
p.setup = function() {
p.frameRate(30);
receiver.connect();
receiver.on('received', function(data) {
console.log("Pulsar: received: " + data);
var drawing = processor.createDrawing(data);
dM.add(drawing);
// give to drawing manager
})
p.createCanvas(p.windowWidth, p.windowHeight);
}
p.draw = function() {
p.noStroke();
p.background(0);
dM.drawAll();
p.textSize(15);
p.fill(175);
var verWidth = p.textWidth("PULSAR - v0.0.1");
p.text("PULSAR - v0.0.1", p.windowWidth - verWidth - 10, p.windowHeight - 10);
}
p.windowResized = function() {
p.resizeCanvas(p.windowWidth, p.windowHeight);
}
}
new p5(pulsar.sketch); | var p5 = require('p5');
console.log(pulsarConfig);
var sketch = function (p) {
var Receiver = require('./Receiver.js');
var receiver = new Receiver();
var Processor = require('./Processor.js');
var processor = new Processor();
var DrawingManager = require('./DrawingManager.js');
var dM = new DrawingManager(p);
p.setup = function() {
p.frameRate(30);
receiver.connect();
receiver.on('received', function(data) {
console.log("Pulsar: received: " + data);
var drawing = processor.createDrawing(data);
dM.add(drawing);
// give to drawing manager
})
p.createCanvas(p.windowWidth, p.windowHeight);
}
p.draw = function() {
p.noStroke();
p.background(0);
dM.drawAll();
p.textSize(15);
p.fill(175);
var verWidth = p.textWidth("PULSAR - v0.0.1");
p.text("PULSAR - v0.0.1", p.windowWidth - verWidth - 10, p.windowHeight - 10);
}
p.windowResized = function() {
p.resizeCanvas(p.windowWidth, p.windowHeight);
}
}
var myp5 = new p5(sketch); |
Add Art descriptions to description boxes | module.exports = {
'Filtering on search page': function (browser) {
browser
.url('http://localhost:8000/search?q=rocket')
.waitForElementVisible('body', 1000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/W/P/A/large_thumbnail_1862_0005__0001_.jpg')
.url('http://localhost:8000/search?q=calculating-machine')
.click('.searchtab:nth-of-type(4)')
.pause(2000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/I/A/A/large_thumbnail_BAB_K_62v_Calculating_Machine.jpg')
.end();
}
};
| module.exports = {
'Filtering on search page': function (browser) {
browser
.url('http://localhost:8000/search?q=rocket')
.waitForElementVisible('body', 1000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/W/P/A/large_thumbnail_1862_0005__0003_.jpg')
.url('http://localhost:8000/search?q=calculating-machine')
.click('.searchtab:nth-of-type(4)')
.pause(2000)
.waitForElementVisible('.resultcard__figure', 1000)
.assert.attributeEquals('.resultcard__figure img', 'src', 'http://smgco-images.s3.amazonaws.com/media/I/A/A/large_thumbnail_BAB_K_62v_Calculating_Machine.jpg')
.end();
}
};
|
Use call() rather than apply() to improve performance. | var ArgumentError = require('./ArgumentError');
var topiarist = require('topiarist');
function verifierMethod(verifierMethod) {
return function(arg) {
if(!this.skipVerification) {
if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.');
verifierMethod.call(this, arg);
}
if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) {
this.argsVerifier.constructor.pendingVerifier = this.argsVerifier;
}
return this.argsVerifier;
};
}
function ArgVerifier(argsVerifier, argName, argValue) {
this.argsVerifier = argsVerifier;
this.argName = argName;
this.argValue = argValue;
}
ArgVerifier.addVerifier = function(verifier) {
for(var methodName in verifier) {
ArgVerifier.prototype[methodName] = verifierMethod(verifier[methodName]);
}
};
Object.defineProperty(ArgVerifier.prototype, 'optionally', {
get: function optionally() {
if((this.argValue === undefined) || (this.argValue === null)) {
this.skipVerification = true;
}
return this;
}
});
module.exports = ArgVerifier;
| var ArgumentError = require('./ArgumentError');
var topiarist = require('topiarist');
function verifierMethod(verifier, methodName) {
return function() {
if(!this.skipVerification) {
if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.');
verifier[methodName].apply(this, arguments);
}
if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) {
this.argsVerifier.constructor.pendingVerifier = this.argsVerifier;
}
return this.argsVerifier;
};
}
function ArgVerifier(argsVerifier, argName, argValue) {
this.argsVerifier = argsVerifier;
this.argName = argName;
this.argValue = argValue;
}
ArgVerifier.addVerifier = function(verifier) {
for(var methodName in verifier) {
ArgVerifier.prototype[methodName] = verifierMethod(verifier, methodName);
}
};
Object.defineProperty(ArgVerifier.prototype, 'optionally', {
get: function optionally() {
if((this.argValue === undefined) || (this.argValue === null)) {
this.skipVerification = true;
}
return this;
}
});
module.exports = ArgVerifier;
|
Remove uuid from project name | package sourcesystem
import (
"os"
"path"
)
// VersionControl is the interface for specific
// version control integrations
type VersionControl interface {
CloneSource(repo *SourceRepository, location string) error
PullSource() error
}
// SourceControlManager is the main system for
// running source control operations
type SourceControlManager struct {
VersionControl VersionControl
}
// SystemSCM is a SCM that saves repositories
// locally on the file system
type SystemSCM SourceControlManager
// AddSource for SystemSCM will gather source code
// and then save the files to the local filesystem
func (scm SystemSCM) AddSource(repo *SourceRepository) error {
location := path.Join(os.Getenv("GOPATH"), "repos", repo.ProjectName)
err := scm.VersionControl.CloneSource(repo, location)
repo.SourceLocation = location
if err != nil {
return err
}
return nil
}
// UpdateSource for SystemSCM will find the source
// code location on the file system and update it
func (scm SystemSCM) UpdateSource(repo *SourceRepository) error {
err := scm.VersionControl.PullSource()
if err != nil {
return err
}
return nil
} | package sourcesystem
import (
"os"
"path"
uuid "github.com/satori/go.uuid"
)
// VersionControl is the interface for specific
// version control integrations
type VersionControl interface {
CloneSource(repo *SourceRepository, location string) error
PullSource() error
}
// SourceControlManager is the main system for
// running source control operations
type SourceControlManager struct {
VersionControl VersionControl
}
// SystemSCM is a SCM that saves repositories
// locally on the file system
type SystemSCM SourceControlManager
// AddSource for SystemSCM will gather source code
// and then save the files to the local filesystem
func (scm SystemSCM) AddSource(repo *SourceRepository) error {
location := createSourceFolder(repo.ProjectName)
err := scm.VersionControl.CloneSource(repo, location)
repo.SourceLocation = location
if err != nil {
return err
}
return nil
}
// UpdateSource for SystemSCM will find the source
// code location on the file system and update it
func (scm SystemSCM) UpdateSource(repo *SourceRepository) error {
err := scm.VersionControl.PullSource()
if err != nil {
return err
}
return nil
}
func createSourceFolder(project string) string {
uuid := uuid.NewV4()
sourceFolder := path.Join(os.Getenv("GOPATH"), "/repos/", project+"_"+uuid.String())
return sourceFolder
}
|
Fix for error that appears on npm run lint:fix | function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
// controls should work whether or not camera center is set to (0,0,0)
// camera(0, 0, 500, 300, 0, 0, 0, 1, 0);
}
function draw() {
background(250);
var radius = width;
orbitControl();
normalMaterial();
let scale = 200;
for (let px = -5; px < 5; px++) {
for (let pz = -5; pz < 5; pz++) {
push();
rotateX(PI);
translate(px * scale, 0, pz * scale);
if (px > 0) {
fill(255, 0, 0);
}
if (px === 0 && pz === 0) {
cone(50, 100);
} else {
cone(20, 50);
}
pop();
}
}
}
| function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
// controls should work whether or not camera center is set to (0,0,0)
// camera(0, 0, 500, 300, 0, 0, 0, 1, 0);
}
function draw() {
background(250);
var radius = width;
orbitControl();
normalMaterial();
let scale = 200;
for (let px = -5; px < 5; px++) {
for (let pz = -5; pz < 5; pz++) {
push();
rotateX(PI);
translate(px * scale, 0, pz * scale);
if (px > 0) {
fill(255, 0, 0);
}
if (px == 0 && pz == 0) {
cone(50, 100);
} else {
cone(20, 50);
}
pop();
}
}
}
|
Change documentation for directory build cache default location
+review REVIEW-6480 | /*
* Copyright 2017 the original author or 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 org.gradle.caching.local;
import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.caching.configuration.AbstractBuildCache;
/**
* Configuration object for the local directory build cache.
*
* By default, the build cache is stored in {@code GRADLE_HOME/caches}.
*
* @since 3.5
*/
@Incubating
public class DirectoryBuildCache extends AbstractBuildCache {
private Object directory;
/**
* Returns the directory to use to store the build cache.
*/
@Nullable
public Object getDirectory() {
return directory;
}
/**
* Sets the directory to use to store the build cache.
*
* The directory is evaluated as per {@link org.gradle.api.Project#file(Object)}.
*/
public void setDirectory(Object directory) {
this.directory = directory;
}
}
| /*
* Copyright 2017 the original author or 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 org.gradle.caching.local;
import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.caching.configuration.AbstractBuildCache;
/**
* Configuration object for the local directory build cache.
*
* By default, the build cache is stored in {@code GRADLE_HOME/.caches/<GRADLE_VERSION>/build-cache}.
*
* @since 3.5
*/
@Incubating
public class DirectoryBuildCache extends AbstractBuildCache {
private Object directory;
/**
* Returns the directory to use to store the build cache.
*/
@Nullable
public Object getDirectory() {
return directory;
}
/**
* Sets the directory to use to store the build cache.
*
* The directory is evaluated as per {@link org.gradle.api.Project#file(Object)}.
*/
public void setDirectory(Object directory) {
this.directory = directory;
}
}
|
Fix extra code sending after loop in rf transmitter | import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
| import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
self.rf_device.tx_code(self.code)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
|
Add minimum window size limit | const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({minWidth: 800, minHeight: 600, darkTheme: false, title: "Armonia"});
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'ui_renderer','index.html'),
protocol: 'file:',
slashes: true
}));
mainWindow.maximize();
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
}); | const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'ui_renderer','index.html'),
protocol: 'file:',
slashes: true
}));
mainWindow.maximize();
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
}); |
Remove unnecessary arguments from autograd hessian | """
Module containing functions to differentiate functions using autograd.
"""
import autograd.numpy as np
from autograd.core import grad
from ._backend import Backend
def _hessian_vector_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-vector product.
The returned function has arguments (*args, vector, **kwargs). Note,
this function will be incorporated into autograd, with name
hessian_vector_product. Once it has been this function can be
deleted."""
fun_grad = grad(fun, argnum)
def vector_dot_grad(*args, **kwargs):
args, vector = args[:-1], args[-1]
return np.tensordot(fun_grad(*args, **kwargs), vector,
axes=vector.ndim)
# Grad wrt original input.
return grad(vector_dot_grad, argnum)
class AutogradBackend(Backend):
def compute_gradient(self, objective, argument):
"""
Compute the gradient of 'objective' with respect to the first
argument and return as a function.
"""
return grad(objective)
def compute_hessian(self, objective, argument):
return _hessian_vector_product(objective)
| """
Module containing functions to differentiate functions using autograd.
"""
import autograd.numpy as np
from autograd.core import grad
from ._backend import Backend
def _hessian_vector_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-vector product.
The returned function has arguments (*args, vector, **kwargs). Note,
this function will be incorporated into autograd, with name
hessian_vector_product. Once it has been this function can be
deleted."""
fun_grad = grad(fun, argnum)
def vector_dot_grad(*args, **kwargs):
args, vector = args[:-1], args[-1]
return np.tensordot(fun_grad(*args, **kwargs), vector,
axes=vector.ndim)
# Grad wrt original input.
return grad(vector_dot_grad, argnum)
class AutogradBackend(Backend):
def compute_gradient(self, objective, argument):
"""
Compute the gradient of 'objective' with respect to the first
argument and return as a function.
"""
return grad(objective)
def compute_hessian(self, objective, argument):
return _hessian_vector_product(objective)(x, g)
|
Add focused class if placeholder length is greather than 0 | $(document).ready(function(){
function floatingLabel() {
var PARENT_CLASS = '.form-group',
INPUT_CLASS = '.form-group.floating-labels input, .form-group.floating-labels textarea',
CHZN_SELECT_CLASS = '.chzn-select';
$(document).on('focus blur', INPUT_CLASS, function (e) {
var valLength = this.value.length;
var placeholder = this.getAttribute('placeholder');
$(this).parents(PARENT_CLASS)
.toggleClass('focus', e.type === 'focus' || e.type === 'focusin')
.toggleClass('filled', valLength > 0)
.toggleClass('focused', (e.type === 'focus'||
e.type === 'focusin' ||
valLength > 0 ||
(valLength === 0 && typeof placeholder === 'string' && placeholder.length > 0)));
});
$(INPUT_CLASS).trigger('blur');
$(document).on('liszt:showing_dropdown liszt:hiding_dropdown', CHZN_SELECT_CLASS, function (e) {
$(this).parents(PARENT_CLASS)
.toggleClass('focus', e.type === 'liszt:showing_dropdown')
});
}
floatingLabel();
});
| $(document).ready(function(){
function floatingLabel() {
var PARENT_CLASS = '.form-group',
INPUT_CLASS = '.form-group.floating-labels input, .form-group.floating-labels textarea',
CHZN_SELECT_CLASS = '.chzn-select';
$(document).on('focus blur', INPUT_CLASS, function (e) {
$(this).parents(PARENT_CLASS)
.toggleClass('focus', e.type === 'focus' || e.type === 'focusin')
.toggleClass('filled', this.value.length > 0)
.toggleClass('focused', (e.type === 'focus'|| e.type === 'focusin' || this.value.length > 0 || (this.value.length === 0 && typeof this.getAttribute('placeholder') === 'string')));
});
$(INPUT_CLASS).trigger('blur');
$(document).on('liszt:showing_dropdown liszt:hiding_dropdown', CHZN_SELECT_CLASS, function (e) {
$(this).parents(PARENT_CLASS)
.toggleClass('focus', e.type === 'liszt:showing_dropdown')
});
}
floatingLabel();
});
|
Put the model results right on the MC object | module.exports = exports = MC
function MC () {
this.loading = 0
this.models = {}
this.ondone = function () {}
}
var modelLoaders = {}
MC.model = function (name, loader) {
if (MC.prototype.hasOwnProperty(name) ||
name === 'loading' ||
name === 'ondone' ||
name === 'error' ||
name === 'models') {
throw new Error('invalid model name: ' + name)
}
modelLoaders[name] = loader
return MC
}
MC.prototype.load = function (name) {
if (!modelLoaders[name]) {
throw new Error('Unknown model: ' + name)
}
if (this.error) return
var a = new Array(arguments.length)
for (var i = 1; i < arguments.length; i ++) {
a[i-1] = arguments[i]
}
a[i-1] = next.bind(this)
this.loading ++
modelLoaders[name].apply(this, a)
function next (er, data) {
if (this.error) return
this.error = er
this[name] = this.models[name] = data
this.loading --
if ((er || this.loading === 0) && this.ondone) {
this.ondone(this.error, this.models)
}
}
}
MC.prototype.end = function (cb) {
this.ondone = cb
if (this.loading === 0 || this.error) {
this.ondone(this.error, this.models)
}
}
| module.exports = exports = MC
function MC () {
this._loading = 0
this.models = {}
}
var modelLoaders = {}
MC.model = function (name, loader) {
modelLoaders[name] = loader
return MC
}
MC.prototype.load = function (name) {
if (!modelLoaders[name]) {
throw new Error('Unknown model: ' + name)
}
if (this.error) return
var a = new Array(arguments.length)
for (var i = 1; i < arguments.length; i ++) {
a[i-1] = arguments[i]
}
a[i-1] = next.bind(this)
this._loading ++
modelLoaders[name].apply(this, a)
function next (er, data) {
if (this.error) return
this.error = er
this.models[name] = data
this._loading --
if (er || this._loading === 0) {
this.ondone(this.error, this.models)
}
}
}
MC.prototype.end = function (cb) {
this.ondone = cb
if (this._loading === 0) this.ondone(this.error, this.models)
}
|
Remove unnecessary variable passing to function literal | // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package btrees
// LCA returns the lowest common ancestor in
// the binary tree t for the nodes n0, n1.
func LCA(t, n0, n1 *BTree) *BTree {
var findLCA func(t *BTree) (cnt int, ancestor *BTree)
findLCA = func(t *BTree) (cnt int, ancestor *BTree) {
if t == nil {
return 0, nil // Base case.
}
// Post-order walk.
lc, la := findLCA(t.left)
if lc == 2 {
return lc, la
}
rc, ra := findLCA(t.right)
if rc == 2 {
return rc, ra
}
cnt = lc + rc
if t == n0 {
cnt++
}
if t == n1 {
cnt++
}
if cnt == 2 {
ancestor = t
}
return cnt, ancestor
}
_, a := findLCA(t)
return a
}
| // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package btrees
// LCA returns the lowest common ancestor in
// the binary tree t for the nodes n0, n1.
func LCA(t, n0, n1 *BTree) *BTree {
var findLCA func(t, n0, n1 *BTree) (cnt int, ancestor *BTree)
findLCA = func(t, n0, n1 *BTree) (cnt int, ancestor *BTree) {
if t == nil {
return 0, nil // Base case.
}
// Post-order walk.
lc, la := findLCA(t.left, n0, n1)
if lc == 2 {
return lc, la
}
rc, ra := findLCA(t.right, n0, n1)
if rc == 2 {
return rc, ra
}
cnt = lc + rc
if t == n0 {
cnt++
}
if t == n1 {
cnt++
}
if cnt == 2 {
ancestor = t
}
return cnt, ancestor
}
_, a := findLCA(t, n0, n1)
return a
}
|
Add Classification Code to the subjects tests | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupFactoryGuy, make } from 'ember-data-factory-guy';
import { render, fillIn, click } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | doi subjects', function(hooks) {
setupRenderingTest(hooks);
setupFactoryGuy(hooks);
test('add multiple values', async function(assert) {
this.set('subject', make('subject'));
this.set('model', make('doi'));
this.set('model.subjects', [ this.subject ]);
await render(hbs`{{doi-subjects model=model}}`);
await click('#toggle-subjects');
await click('#add-subject');
await click('#add-subject');
let subjectSchemes = this.element.querySelectorAll('[data-test-subject-scheme]');
await fillIn(subjectSchemes[0],'Fields of Science and Technology (FOS)');
assert.dom(subjectSchemes[0]).hasValue('Fields of Science and Technology (FOS)');
let subjectSchemeUris = this.element.querySelectorAll('[data-test-subject-uri]');
await fillIn(subjectSchemeUris[0],'https://example.com/fos');
assert.dom(subjectSchemeUris[0]).hasValue('https://example.com/fos');
let subjectSchemeCodes = this.element.querySelectorAll('[data-test-classification-code]');
await fillIn(subjectSchemeCodes[0],'ABC123');
assert.dom(subjectSchemeCodes[0]).hasValue('ABC123');
});
});
| import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupFactoryGuy, make } from 'ember-data-factory-guy';
import { render, fillIn, click } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | doi subjects', function(hooks) {
setupRenderingTest(hooks);
setupFactoryGuy(hooks);
test('add multiple values', async function(assert) {
this.set('subject', make('subject'));
this.set('model', make('doi'));
this.set('model.subjects', [ this.subject ]);
await render(hbs`{{doi-subjects model=model}}`);
await click('#toggle-subjects');
await click('#add-subject');
await click('#add-subject');
let subjects = this.element.querySelectorAll('[data-test-subject-scheme]');
await fillIn(subjects[0],'Fields of Science and Technology (FOS)');
assert.dom(subjects[0]).hasValue('Fields of Science and Technology (FOS)');
});
});
|
Check for the name of the submodule we'd like to ignore in a more general way. | import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
# test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
if name.split('.')[1] not in ignore_packages:
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
# import submodules recursively
import_submodules(__name__)
| import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
if(name not in ignore_packages):
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
# import submodules recursively
import_submodules(__name__)
|
Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures. | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
|
Check if using chrome first | 'use strict';
/*global window: false, document: false, $:false, d3:false, toggle_overview_btn, checkIfUsingChromeLocally, addData*/
$(document).ready(function() {
checkIfUsingChromeLocally();
toggle_overview_btn(); // write overview to overview section
initTableSorter();
$("[data-toggle='tooltip']").tooltip(); //ToolTip
});
$( document ).on( "click", "td, .plot_btn", function( event ) {
if ($(this).hasClass('success') || $(this).hasClass('danger')){
var title = $(this).attr('title');
var val = title.replace(/[ \/]/g, '');
addData(this, val);
} else if ($(this).hasClass('plot_btn')){
addData(this, 'all');
}
});
function initTableSorter() {
$.tablesorter.addParser({
id: 'star_scores', // called later when init the tablesorter
is: function() {
return false; // return false so this parser is not auto detected
},
format: function(s, table, cell, cellIndex) {
var $cell = $(cell);
if (cellIndex === 1) {
return $cell.attr('data-score') || s;
}
return s;
},
parsed: false,
type: 'numeric' // Setting type of data...
});
$('table').tablesorter({
headers: {
1 : { sorter: 'star_scores' } // Telling it to use custom parser...
},
sortList: [[0,0]],
});
}
| 'use strict';
/*global window: false, document: false, $:false, d3:false, toggle_overview_btn, checkIfUsingChromeLocally, addData*/
$(document).ready(function() {
toggle_overview_btn(); // write overview to overview section
initTableSorter();
$("[data-toggle='tooltip']").tooltip(); //ToolTip
checkIfUsingChromeLocally();
});
$( document ).on( "click", "td, .plot_btn", function( event ) {
if ($(this).hasClass('success') || $(this).hasClass('danger')){
var title = $(this).attr('title');
var val = title.replace(/[ \/]/g, '');
addData(this, val);
} else if ($(this).hasClass('plot_btn')){
addData(this, 'all');
}
});
function initTableSorter() {
$.tablesorter.addParser({
id: 'star_scores', // called later when init the tablesorter
is: function() {
return false; // return false so this parser is not auto detected
},
format: function(s, table, cell, cellIndex) {
var $cell = $(cell);
if (cellIndex === 1) {
return $cell.attr('data-score') || s;
}
return s;
},
parsed: false,
type: 'numeric' // Setting type of data...
});
$('table').tablesorter({
headers: {
1 : { sorter: 'star_scores' } // Telling it to use custom parser...
},
sortList: [[0,0]],
});
}
|
Fix typos in text about NLP | /**
* Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017.
*/
import html from '../../templates/helpers';
const template = (context) => {
return new Promise((resolve) => {
resolve(html`
<h5 class="card-title">Tell us how you feel.</h5>
<div class="card-text">
<form>
<div class="form-group">
<label for="input-feel">We will try to recognize your symptoms using Natural Language Processing algorithms.</label>
<textarea placeholder="e.g. I got headache" class="form-control" id="input-feel" rows="4"></textarea>
</div>
</form>
<p>Identified observations:</p>
<ul class="list-unstyled" id="observations">
</ul>
<p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidence found in text will be marked as initial which is important to our engine. Please read more about initial evidence <a target="_blank" href="https://developer.infermedica.com/docs/diagnosis#gathering-initial-evidence">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p>
</div>
`);
});
};
export default template;
| /**
* Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017.
*/
import html from '../../templates/helpers';
const template = (context) => {
return new Promise((resolve) => {
resolve(html`
<h5 class="card-title">Tell us how you feel.</h5>
<div class="card-text">
<form>
<div class="form-group">
<label for="input-feel">We will try to recognize your symptoms using Natural Language Processing algorithms.</label>
<textarea placeholder="e.g. I got headache" class="form-control" id="input-feel" rows="4"></textarea>
</div>
</form>
<p>Identified observations:</p>
<ul class="list-unstyled" id="observations">
</ul>
<p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidences found in text will be marked as initial which is important to our engine. Please read more about initial evidences <a target="_blank">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p>
</div>
`);
});
};
export default template;
|
Add alpha to interventions block
In the Profile on the graph #234 | (function(root) {
var InterventionPlotBand = function initializeInterventionPlotBand (intervention) {
this.name = intervention.name;
this.from = InterventionPlotBand.toHighChartsDate(intervention.start_date);
this.to = InterventionPlotBand.toHighChartsDate(intervention.end_date);
}
InterventionPlotBand.toHighChartsDate = function interventionDatesToHighChartsDate (date) {
return Date.UTC(date['year'],
date['month'] - 1, // JavaScript months start with 0, Ruby months start with 1
date['day'])
}
InterventionPlotBand.prototype.toHighCharts = function interventionToHighCharts () {
return $.extend({},
InterventionPlotBand.base_options, {
from: this.from,
to: this.to,
}
);
}
InterventionPlotBand.base_options = {
color: 'rgba(248,231,28,.23)',
zIndex: 2,
}
root.InterventionPlotBand = InterventionPlotBand;
})(window)
| (function(root) {
var InterventionPlotBand = function initializeInterventionPlotBand (intervention) {
this.name = intervention.name;
this.from = InterventionPlotBand.toHighChartsDate(intervention.start_date);
this.to = InterventionPlotBand.toHighChartsDate(intervention.end_date);
}
InterventionPlotBand.toHighChartsDate = function interventionDatesToHighChartsDate (date) {
return Date.UTC(date['year'],
date['month'] - 1, // JavaScript months start with 0, Ruby months start with 1
date['day'])
}
InterventionPlotBand.prototype.toHighCharts = function interventionToHighCharts () {
return $.extend({},
InterventionPlotBand.base_options, {
from: this.from,
to: this.to,
label: { text: this.name }
}
);
}
InterventionPlotBand.base_options = {
color: '#FCFCC8',
zIndex: 2,
label: {
style: {
color: '#999999'
}
}
}
root.InterventionPlotBand = InterventionPlotBand;
})(window)
|
Adjust spacing around Group header | function controller($window, $location, toastr, currentUser) {
this.canEdit = () => currentUser.isAdmin && this.group.type !== 'builtin';
this.saveName = () => {
this.group.$save();
};
this.deleteGroup = () => {
if ($window.confirm('Are you sure you want to delete this group?')) {
this.group.$delete(() => {
$location.path('/groups').replace();
toastr.success('Group deleted successfully.');
});
}
};
}
export default function init(ngModule) {
ngModule.component('groupName', {
bindings: {
group: '<',
},
transclude: true,
template: `
<h2 class="m-t-0">
<edit-in-place editable="$ctrl.canEdit()" done="$ctrl.saveName" ignore-blanks='true' value="$ctrl.group.name"></edit-in-place>
<button class="btn btn-xs btn-danger" ng-if="$ctrl.canEdit()" ng-click="$ctrl.deleteGroup()">Delete this group</button>
</h2>
`,
replace: true,
controller,
});
}
| function controller($window, $location, toastr, currentUser) {
this.canEdit = () => currentUser.isAdmin && this.group.type !== 'builtin';
this.saveName = () => {
this.group.$save();
};
this.deleteGroup = () => {
if ($window.confirm('Are you sure you want to delete this group?')) {
this.group.$delete(() => {
$location.path('/groups').replace();
toastr.success('Group deleted successfully.');
});
}
};
}
export default function init(ngModule) {
ngModule.component('groupName', {
bindings: {
group: '<',
},
transclude: true,
template: `
<h2 class="p-l-5">
<edit-in-place editable="$ctrl.canEdit()" done="$ctrl.saveName" ignore-blanks='true' value="$ctrl.group.name"></edit-in-place>
<button class="btn btn-xs btn-danger" ng-if="$ctrl.canEdit()" ng-click="$ctrl.deleteGroup()">Delete this group</button>
</h2>
`,
replace: true,
controller,
});
}
|
:bug: Fix merging of inline+config entry | // @flow
import { PundleError, type Context } from 'pundle-api'
import type { Config, AcceptedConfig } from './types'
import readConfigFile from './readConfigFile'
import validateAndTransformConfig from './validateAndTransformConfig'
export type { Config, AcceptedConfig }
export default async function loadConfig(context: Context): Promise<Config> {
const fileConfig = await validateAndTransformConfig({
context,
config: await readConfigFile(context),
})
const inlineConfig = await validateAndTransformConfig({
context,
config: context.configInline,
})
if (typeof inlineConfig.components !== 'undefined') {
throw new PundleError('CONFIG', 'INVALID_CONFIG', 'config.components is not allowed in inline config')
}
const config = {
entry: [],
rootDirectory: fileConfig.rootDirectory,
output: {
formats: {},
rootDirectory: '',
},
components: [],
}
if (inlineConfig.entry) {
config.entry = config.entry.concat(inlineConfig.entry)
}
if (fileConfig.entry) {
config.entry = config.entry.concat(fileConfig.entry)
}
if (fileConfig.output) {
Object.assign(config.output, fileConfig.output)
}
if (typeof inlineConfig.output === 'object' && inlineConfig.output !== null) {
Object.assign(config.output, inlineConfig.output)
}
if (fileConfig.components) {
config.components = fileConfig.components.sort((a, b) => b.priority - a.priority)
}
return config
}
| // @flow
import { PundleError, type Context } from 'pundle-api'
import type { Config, AcceptedConfig } from './types'
import readConfigFile from './readConfigFile'
import validateAndTransformConfig from './validateAndTransformConfig'
export type { Config, AcceptedConfig }
export default async function loadConfig(context: Context): Promise<Config> {
const fileConfig = await validateAndTransformConfig({
context,
config: await readConfigFile(context),
})
const inlineConfig = await validateAndTransformConfig({
context,
config: context.configInline,
})
if (typeof inlineConfig.components !== 'undefined') {
throw new PundleError('CONFIG', 'INVALID_CONFIG', 'config.components is not allowed in inline config')
}
const config = {
entry: [],
rootDirectory: fileConfig.rootDirectory,
output: {
formats: {},
rootDirectory: '',
},
components: [],
}
if (fileConfig.entry) {
config.entry = config.entry.concat(fileConfig.entry)
}
if (typeof inlineConfig.entry === 'string') {
config.entry = config.entry.concat(inlineConfig.entry)
}
if (fileConfig.output) {
Object.assign(config.output, fileConfig.output)
}
if (typeof inlineConfig.output === 'object' && inlineConfig.output !== null) {
Object.assign(config.output, inlineConfig.output)
}
if (fileConfig.components) {
config.components = fileConfig.components.sort((a, b) => b.priority - a.priority)
}
return config
}
|
Update test block with new method references | package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.block.*;
import net.minecraft.item.BlockItem;
import net.minecraftforge.eventbus.api.IEventBus;
public class TestBlocks {
public static final BlockDeferredRegister BLOCKS = BlockDeferredRegister.create(TestMod.MODID);
public static final BlockRegistryObject<BasicBlock, BlockItem> BASIC = BLOCKS.register("basicblock", BasicBlock::new);
public static final BlockRegistryObject<BasicTileEntityBlock, BlockItem> BASIC_TILEENTITY = BLOCKS.register("tileentity", BasicTileEntityBlock::new);
public static final BlockRegistryObject<BasicEnergyCreatorBlock, BlockItem> BASIC_ENERGY_CREATOR = BLOCKS.register("energy_creator", BasicEnergyCreatorBlock::new);
public static final BlockRegistryObject<BasicFluidInventoryBlock, BlockItem> BASIC_FLUID_INVENTORY = BLOCKS.register("fluid_inventory", BasicFluidInventoryBlock::new);
public static void register(IEventBus bus) {
BLOCKS.register(bus);
}
}
| package info.u_team.u_team_test.init;
import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.block.*;
import net.minecraft.item.BlockItem;
import net.minecraftforge.eventbus.api.IEventBus;
public class TestBlocks {
public static final BlockDeferredRegister BLOCKS = BlockDeferredRegister.create(TestMod.MODID);
public static final BlockRegistryObject<BasicBlock, BlockItem> BASIC = BLOCKS.register("basicblock", () -> new BasicBlock("basicblock"));
public static final BlockRegistryObject<BasicTileEntityBlock, BlockItem> BASIC_TILEENTITY = BLOCKS.register("tileentity", () -> new BasicTileEntityBlock("tileentity"));
public static final BlockRegistryObject<BasicEnergyCreatorBlock, BlockItem> BASIC_ENERGY_CREATOR = BLOCKS.register("energy_creator", () -> new BasicEnergyCreatorBlock("energy_creator"));
public static final BlockRegistryObject<BasicFluidInventoryBlock, BlockItem> BASIC_FLUID_INVENTORY = BLOCKS.register("fluid_inventory", () -> new BasicFluidInventoryBlock("fluid_inventory"));
public static void register(IEventBus bus) {
BLOCKS.register(bus);
}
}
|
Revert "overly broad linter override"
This reverts commit d361a2fe55dd0a235332fd8493f35df8e638b894. | module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
plugins: ['ember'],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true,
es6: true
},
rules: {
'no-restricted-globals': [2, 'find']
},
overrides: [
// This loads our node rules
Object.assign({}, require('./-node'), {
// And applies them to all the paths that are node paths in a
// standard ember-addon
files: [
'index.js',
'testem.js',
'ember-cli-build.js',
'cardstack/**/*.js',
'config/**/*.js',
'tests/dummy/config/**/*.js',
'tests/dummy/cardstack/**/*.js'
],
excludedFiles: [
'app/**',
'addon/**',
'tests/dummy/app/**'
]
}),
// And this loads our node tests rules
Object.assign({}, require('./test'), {
files: [
'node-tests/**/*.js'
]
})
]
};
| module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
plugins: ['ember'],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true,
es6: true
},
rules: {
'no-restricted-globals': [2, 'find']
},
overrides: [
// This loads our node rules
Object.assign({}, require('./-node'), {
// And applies them to all the paths that are node paths in a
// standard ember-addon
files: [
'./index.js',
'testem.js',
'ember-cli-build.js',
'cardstack/**/*.js',
'config/**/*.js',
'tests/dummy/config/**/*.js',
'tests/dummy/cardstack/**/*.js'
],
excludedFiles: [
'app/**',
'addon/**',
'tests/dummy/app/**'
]
}),
// And this loads our node tests rules
Object.assign({}, require('./test'), {
files: [
'node-tests/**/*.js'
]
})
]
};
|
Add handler for disconnect to silence log | /*
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var container = require('rhea');
function authenticate(username, password) {
console.log('Authenticating as ' + username);
return true;
}
container.sasl_server_mechanisms.enable_plain(authenticate);
var server = container.listen({'port':process.env.LISTENPORT, 'require_sasl': true});
console.log('Listening on port ' + process.env.LISTENPORT);
container.on('connection_open', function (context) {
var authenticatedIdentity = { 'sub' : context.connection.sasl_transport.username };
var properties = context.connection.local.open.properties || {};
properties["authenticated-identity"] = authenticatedIdentity;
context.connection.local.open.properties = properties;
context.connection.close();
});
container.on('disconnected', function (context) {
});
| /*
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var container = require('rhea');
function authenticate(username, password) {
console.log('Authenticating as ' + username);
return true;
}
container.sasl_server_mechanisms.enable_plain(authenticate);
var server = container.listen({'port':process.env.LISTENPORT, 'require_sasl': true});
console.log('Listening on port ' + process.env.LISTENPORT);
container.on('connection_open', function (context) {
var authenticatedIdentity = { 'sub' : context.connection.sasl_transport.username };
var properties = context.connection.local.open.properties || {};
properties["authenticated-identity"] = authenticatedIdentity;
context.connection.local.open.properties = properties;
context.connection.close();
});
|
Write a slightly less dumb protocol? | from twisted.protocols import basic
from twisted.internet import protocol, reactor
from hubbot.moduleinterface import ModuleInterface
class HealthcheckProtocol(basic.LineReceiver):
def lineReceived(self, line):
response_body = "All is well. Ish."
self.sendLine("HTTP/1.0 200 OK".encode("UTF-8"))
self.sendLine("Content-Type: text/plain".encode("UTF-8"))
self.sendLine(f"Content-Length: {len(response_body)}\n".encode("UTF-8"))
self.transport.write(response_body)
self.transport.loseConnection()
class Healthcheck(ModuleInterface):
port = 9999
def __init__(self, bot):
self.healthcheck_server = protocol.ServerFactory()
self.healthcheck_server.protocol = HealthcheckProtocol
super().__init__(bot)
def on_load(self):
reactor.listenTCP(self.port, self.healthcheck_server)
def on_unload(self):
reactor.stopListening(self.port)
def help(self, message):
return f"Hosts an HTTP healthcheck server on port {self.port}."
| from twisted.internet import reactor, protocol
from hubbot.moduleinterface import ModuleInterface
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
self.transport.write(data)
class Healthcheck(ModuleInterface):
port = 9999
def __init__(self, bot):
self.healthcheck_server = protocol.ServerFactory()
self.healthcheck_server.protocol = Echo
super().__init__(bot)
def on_load(self):
reactor.listenTCP(self.port, self.healthcheck_server)
def on_unload(self):
reactor.stopListening(self.port)
def help(self, message):
return f"Hosts an HTTP healthcheck server on port {self.port}."
|
Adjust test cause user links now use double quotes for attributes | from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'http://test.test.lan:5000/user/pudo"' in result)
| from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u"http://test.test.lan:5000/user/pudo'" in result)
|
Make shutdown of tests gracefully | package ru.ydn.orienteer.junit;
import org.apache.wicket.util.tester.WicketTester;
import org.junit.runners.model.InitializationError;
import ru.ydn.orienteer.services.OrienteerModule;
import ru.ydn.orienteer.standalone.StartStandalone;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.util.Modules;
public class OrienteerTestRunner extends GuiceTestRunner
{
private static final Injector STATIC_INJECTOR;
static
{
System.out.println("Using embedded mode");
System.setProperty(StartStandalone.PROPERTIES_FILE_NAME, StartStandalone.class.getResource("standalone.properties").toString());
STATIC_INJECTOR = Guice.createInjector(Modules.override(new OrienteerModule()).with(new TestOrieenteerModule()));
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run() {
WicketTester wicketTester = STATIC_INJECTOR.getInstance(WicketTester.class);
wicketTester.destroy();
}
});
}
public OrienteerTestRunner(Class<?> classToRun) throws InitializationError
{
super(classToRun, STATIC_INJECTOR);
}
@Override
public Object createTest() {
//Ensure that wicket tester and corresponding application started
getInjector().getInstance(WicketTester.class);
return super.createTest();
}
}
| package ru.ydn.orienteer.junit;
import org.apache.wicket.util.tester.WicketTester;
import org.junit.runners.model.InitializationError;
import ru.ydn.orienteer.services.OrienteerModule;
import ru.ydn.orienteer.standalone.StartStandalone;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.util.Modules;
public class OrienteerTestRunner extends GuiceTestRunner
{
private static final Injector STATIC_INJECTOR;
static
{
System.out.println("Using embedded mode");
System.setProperty(StartStandalone.PROPERTIES_FILE_NAME, StartStandalone.class.getResource("standalone.properties").toString());
STATIC_INJECTOR = Guice.createInjector(Modules.override(new OrienteerModule()).with(new TestOrieenteerModule()));
}
public OrienteerTestRunner(Class<?> classToRun) throws InitializationError
{
super(classToRun, STATIC_INJECTOR);
}
@Override
public Object createTest() {
//Ensure that wicket tester and corresponding application started
getInjector().getInstance(WicketTester.class);
return super.createTest();
}
}
|
Remove unnecessary complete class name | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.internal;
import com.github.anba.es6draft.runtime.ExecutionContext;
/**
* Base class for internal exceptions
*/
@SuppressWarnings("serial")
public abstract class InternalException extends RuntimeException {
/**
* {@inheritDoc}
*/
public InternalException() {
super();
}
/**
* {@inheritDoc}
*/
public InternalException(String message) {
super(message);
}
/**
* {@inheritDoc}
*/
public InternalException(String message, Throwable cause) {
super(message, cause);
}
/**
* {@inheritDoc}
*/
public InternalException(Throwable cause) {
super(cause);
}
/**
* {@inheritDoc}
*/
protected InternalException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
/**
* Returns a {@link ScriptException} for this exception object
*/
public abstract ScriptException toScriptException(ExecutionContext cx);
}
| /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.internal;
import com.github.anba.es6draft.runtime.ExecutionContext;
/**
* Base class for internal exceptions
*/
@SuppressWarnings("serial")
public abstract class InternalException extends java.lang.RuntimeException {
/**
* {@inheritDoc}
*/
public InternalException() {
super();
}
/**
* {@inheritDoc}
*/
public InternalException(String message) {
super(message);
}
/**
* {@inheritDoc}
*/
public InternalException(String message, Throwable cause) {
super(message, cause);
}
/**
* {@inheritDoc}
*/
public InternalException(Throwable cause) {
super(cause);
}
/**
* {@inheritDoc}
*/
protected InternalException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
/**
* Returns a {@link ScriptException} for this exception object
*/
public abstract ScriptException toScriptException(ExecutionContext cx);
}
|
Use absolute value for NTP drift | package siren
import (
"fmt"
"math"
"os"
"os/exec"
"strconv"
"strings"
)
func NTP(w, f int) Status {
out, err := exec.Command("ntpq", "-c", "rv 0 offset").Output()
if err != nil {
fmt.Fprintf(os.Stdout, "\n%s: unable to determine NTP drift. %s\n", warn, err)
return warn
}
// Output: offset=72.062
floatStr := strings.Trim(string(out[7:]), "\n")
drift, err := strconv.ParseFloat(floatStr, 64)
if err != nil {
fmt.Fprintf(os.Stdout, "\n%s: unable to determine NTP drift\n", warn)
return warn
}
fmt.Fprintf(os.Stdout, "NTP drift: %0.2fms\n", drift)
drift = math.Abs(drift)
if drift >= float64(f) {
fmt.Fprintf(os.Stdout, "\n%s: NTP drift exceeds threshold (%0.2fms >= %dms)\n", fail, drift, f)
return fail
}
if drift >= float64(w) {
fmt.Fprintf(os.Stdout, "\n%s: NTP drift exceeds threshold (%0.2fms >= %dms)\n", warn, drift, w)
return warn
}
return ok
}
| package siren
import (
"fmt"
"os"
"os/exec"
"strconv"
"strings"
)
func NTP(w, f int) Status {
out, err := exec.Command("ntpq", "-c", "rv 0 offset").Output()
if err != nil {
fmt.Fprintf(os.Stdout, "\n%s: unable to determine NTP drift. %s\n", warn, err)
return warn
}
// Output: offset=72.062
floatStr := strings.Trim(string(out[7:]), "\n")
drift, err := strconv.ParseFloat(floatStr, 64)
if err != nil {
fmt.Fprintf(os.Stdout, "\n%s: unable to determine NTP drift\n", warn)
return warn
}
fmt.Fprintf(os.Stdout, "NTP drift: %0.2fms\n", drift)
if drift >= float64(f) {
fmt.Fprintf(os.Stdout, "\n%s: NTP drift exceeds threshold (%0.2fms >= %dms)\n", fail, drift, f)
return fail
}
if drift >= float64(w) {
fmt.Fprintf(os.Stdout, "\n%s: NTP drift exceeds threshold (%0.2fms >= %dms)\n", warn, drift, w)
return warn
}
return ok
}
|
Revert "removing data binding warnings"
This reverts commit df1e2ca5d05839d788c73df62681e060de9760fd. | package com.prateekj.snooper.infra;
import android.databinding.BindingAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.widget.ListView;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
public class CustomBindings {
@BindingAdapter("app:adapter")
public static void setAdapter(RecyclerView recyclerView, RecyclerView.Adapter adapter) {
recyclerView.setAdapter(adapter);
}
@BindingAdapter("app:stickyAdapter")
public static void setStickyAdapter(StickyListHeadersListView stickyHeadersListView, StickyListHeadersAdapter adapter) {
stickyHeadersListView.setAdapter(adapter);
}
@BindingAdapter("app:nestingScrollingEnabled")
public static void setNestingScrollingEnabled(StickyListHeadersListView stickyHeadersListView, boolean enabled) {
ListView listView = stickyHeadersListView.getWrappedList();
ViewCompat.setNestedScrollingEnabled(listView, enabled);
}
@BindingAdapter("app:itemDecoration")
public static void setItemDecoration(RecyclerView recyclerView, RecyclerView.ItemDecoration itemDecoration) {
recyclerView.addItemDecoration(itemDecoration);
}
}
| package com.prateekj.snooper.infra;
import android.databinding.BindingAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.widget.ListView;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
public class CustomBindings {
@BindingAdapter("adapter")
public static void setAdapter(RecyclerView recyclerView, RecyclerView.Adapter adapter) {
recyclerView.setAdapter(adapter);
}
@BindingAdapter("stickyAdapter")
public static void setStickyAdapter(StickyListHeadersListView stickyHeadersListView, StickyListHeadersAdapter adapter) {
stickyHeadersListView.setAdapter(adapter);
}
@BindingAdapter("nestingScrollingEnabled")
public static void setNestingScrollingEnabled(StickyListHeadersListView stickyHeadersListView, boolean enabled) {
ListView listView = stickyHeadersListView.getWrappedList();
ViewCompat.setNestedScrollingEnabled(listView, enabled);
}
@BindingAdapter("itemDecoration")
public static void setItemDecoration(RecyclerView recyclerView, RecyclerView.ItemDecoration itemDecoration) {
recyclerView.addItemDecoration(itemDecoration);
}
}
|
Make the code slightly clearer | import {ArrayExtensions} from './arrayextensions';
import {Letter} from './letter';
import {moveBefore, DIRECTION} from 'aurelia-dragula';
export class Welcome {
constructor() {
this.dragDirection = DIRECTION.HORIZONTAL;
this.reset();
}
get unjumbledName() {
return this.nameLetters.reduce((previous, current) => previous + current.char, '');
}
submit() {
this.nameLetters = [];
for(let i = 0; i < this.firstName.length; i++) {
this.nameLetters.push(new Letter(this.firstName.charAt(i)));
}
do {
ArrayExtensions.shuffle(this.nameLetters);
}
//If, by chance, we shuffle it to the same as the original name, keep shuffling until it no longer is
while(this.unjumbledName === this.firstName)
this.haveName = true;
}
drop(item, target, source, sibling) {
let itemId = item.dataset.id;
let siblingId = sibling ? sibling.dataset.id : null;
moveBefore(this.nameLetters, (letter) => letter.id === itemId, (letter) => letter.id === siblingId);
if (this.unjumbledName === this.firstName)
this.winner = true;
}
reset() {
this.firstName = '';
this.haveName = false;
this.winner = false;
}
}
| import {ArrayExtensions} from './arrayextensions';
import {Letter} from './letter';
import {moveBefore, DIRECTION} from 'aurelia-dragula';
export class Welcome {
constructor() {
this.dragDirection = DIRECTION.HORIZONTAL;
this.reset();
}
get unjumbledName() {
return this.nameLetters.reduce((previous, current) => previous + current.char, '');
}
submit() {
this.nameLetters = [];
for(let i = 0; i < this.firstName.length; i++) {
this.nameLetters.push(new Letter(this.firstName.charAt(i)));
}
ArrayExtensions.shuffle(this.nameLetters);
//If, by chance, we shuffle it to the same as the original name, keep shuffling until it no longer is
while(this.unjumbledName === this.firstName)
ArrayExtensions.shuffle(this.nameLetters);
this.haveName = true;
}
drop(item, target, source, sibling) {
let itemId = item.dataset.id;
let siblingId = sibling ? sibling.dataset.id : null;
moveBefore(this.nameLetters, (letter) => letter.id === itemId, (letter) => letter.id === siblingId);
if (this.unjumbledName === this.firstName)
this.winner = true;
}
reset() {
this.firstName = '';
this.haveName = false;
this.winner = false;
}
}
|
Fix handling of All() exceptions. | import colander
from colander import Invalid
class All(object):
""" Composite validator which succeeds if none of its
subvalidators raises an :class:`colander.Invalid` exception"""
def __init__(self, *validators):
self.validators = validators
def __call__(self, node, value):
for validator in self.validators:
validator(node, value)
database_format = colander.Regex('^[a-zA-Z][a-zA-Z0-9_]+[a-zA-Z0-9]$')
database_forbidden = colander.Regex('^(project|source|target|id|created_at" \
+ "|updated_at|author|author_id)$')
database_name = All(database_format, database_forbidden)
class FixedValue(object):
def __init__(self, value):
self.value = value
def serialize(self, node, appstruct):
return colander.null
def deserialize(self, node, cstruct):
return self.value
def cstruct_children(self, node, cstruct):
return []
| import re
import colander
from colander import Invalid
from grano.logic.references import ProjectRef
from grano.core import db
from grano.model import Schema, Attribute
FORBIDDEN = ['project', 'source', 'target', 'id', 'created_at', 'updated_at', 'author', 'author_id']
database_forbidden = colander.Function(lambda v: v not in FORBIDDEN, message="Reserved name")
database_format = colander.Regex('^[a-zA-Z][a-zA-Z0-9_]+[a-zA-Z0-9]$')
database_name = colander.All(database_format, database_forbidden)
class FixedValue(object):
def __init__(self, value):
self.value = value
def serialize(self, node, appstruct):
return colander.null
def deserialize(self, node, cstruct):
return self.value
def cstruct_children(self, node, cstruct):
return []
|
Fix doc test failure parsing | def parseFailDetails(failDetails):
""" Parse the line number of the doctest failure
>>> parseFailDetails("blah")
-1
"""
import re
failDetails = failDetails.split(',')
lineNo = -1
if len(failDetails) == 3:
match = re.search("line.*?(\d+)", failDetails[1])
if match is None:
return lineNo
lineNo = int(match.group(1))
return lineNo
def parseDocTestResult(docTestResStr):
""" Extract the line number and filename of the doctest failure"""
lines = docTestResStr.split("\n")
for lineNo, line in enumerate(lines):
failure = line.find("Failed example:")
if failure != -1:
failDetails = lines[lineNo - 1]
yield parseFailDetails(failDetails)
if __name__ == "__main__":
from doctest import testmod
testmod()
| def parseFailDetails(failDetails):
""" Parse the line number of the doctest failure"""
import re
failDetails = failDetails.split(',')
lineNo = -1
if len(failDetails) == 3:
match = re.search("line.*?(\d+)", failDetails[1])
if match is None:
return lineNo
lineNo = int(match.group(1))
return lineNo
def parseDocTestResult(docTestResStr):
""" Extract the line number and filename of the doctest failure"""
lines = docTestResStr.split("\n")
for lineNo, line in enumerate(lines):
failure = line.find("Failed example:")
if failure != -1:
failDetails = lines[lineNo - 1]
yield parseFailDetails(failDetails)
|
Clean up the code a little | <div class="day_cal">
<h1 class="results">
<?php
if ($dt = strtotime($context->search_query) && ($context->search_query != 'art')) {
echo 'Search results for events dated <span>'.date('F jS',$dt).'</span><a class="permalink" href="'.$context->getURL().'">(link)</a>';
} else {
echo 'Search results for "<span>'.htmlentities($context->search_query).'</span>"';
}
?>
</h1>
<?php
echo '<span class="wdn-subhead">'.$context->count().' results. <a class="permalink" href="'.$context->getURL().'">(link)</a></span>';
echo $savvy->render($context, 'EventListing.tpl.php');
?>
<p id="feeds">
<a id="icsformat" title="ics format for search results" href="<?php echo $context->getURL()?>?format=ics">ics format for search results</a>
<a id="rssformat" title="rss format for search results" href="<?php echo $context->getURL()?>?format=rss">rss format for search results</a>
</p>
</div> | <div class="day_cal">
<?php
if (is_a($context->output,'UNL_UCBCN_EventListing')) {
if ($dt = strtotime($context->query)) {
echo '<h1 class="results">Search results for events dated <span>'.date('F jS',$dt).'</span><a class="permalink" href="'.$context->url.'">(link)</a></h1>';
} else {
echo '<h1 class="results">Search results for "<span>'.htmlentities($context->query).'</span>"<a class="permalink" href="'.$context->url.'">(link)</a></h1>';
}
echo '<h3>'.count($context->output->events).' results</h3>';
}
echo $savvy->render($context->output);
echo '<p id="feeds">
<a id="icsformat" title="ics format for search results" href="'.UNL_UCBCN_Frontend::reformatURL($context->url,array('format'=>'ics')).'">ics format for search results</a>
<a id="rssformat" title="rss format for search results" href="'.UNL_UCBCN_Frontend::reformatURL($context->url,array('format'=>'rss')).'">rss format for search results</a>
</p>';
?>
</div> |
Add accessToken to profile before done | 'use strict';
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');
var passport = require('passport');
var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy;
var active = false;
module.exports = function (options) {
child.send({
options: options.dropbox
});
return {
initialize: function () {
active = true;
passport.use(new DropboxOAuth2Strategy({
clientID: options.dropbox.id,
clientSecret: options.dropbox.secret,
callbackURL: 'https://jsbin.dev/auth/dropbox/callback'
}, function (accessToken, refreshToken, profile, done) {
profile.access_token = accessToken;
done(null, profile);
}
));
}
};
};
module.exports.saveBin = function (file, fileName, user) {
if (!active) {
return;
}
child.send({
file: file,
fileName: fileName,
user: user
});
};
| 'use strict';
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');
var passport = require('passport');
var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy;
var active = false;
module.exports = function (options) {
child.send({
options: options.dropbox
});
return {
initialize: function () {
active = true;
passport.use(new DropboxOAuth2Strategy({
clientID: options.dropbox.id,
clientSecret: options.dropbox.secret,
callbackURL: 'https://jsbin.dev/auth/dropbox/callback'
}, function (accessToken, refreshToken, profile, done) {
done(null, profile);
}
));
}
};
};
module.exports.saveBin = function (file, fileName, user) {
if (!active) {
return;
}
child.send({
file: file,
fileName: fileName,
user: user
});
};
|
Fix redirect default on password reset | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
| <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
|
Move all info output of mdast(1) to stderr(4)
This changes moves all reporting output, even when not including
failure messages, from stout(4) to stderr(4).
Thus, when piping only stdout(4) from mdast(1) into a file, only
the markdown is written.
Closes GH-47. | /**
* @author Titus Wormer
* @copyright 2015 Titus Wormer
* @license MIT
* @module mdast:cli:log
* @fileoverview Log a file context on successful completion.
*/
'use strict';
/*
* Dependencies.
*/
var report = require('vfile-reporter');
/**
* Output diagnostics to stdout(4) or stderr(4).
*
* @param {CLI} context - CLI engine.
*/
function log(context) {
var files = context.files;
var applicables = files.filter(function (file) {
return file.namespace('mdast:cli').providedByUser;
});
var diagnostics = report(applicables, {
'quiet': context.quiet,
'silent': context.silent
});
if (diagnostics) {
context.stderr(diagnostics);
}
}
/*
* Expose.
*/
module.exports = log;
| /**
* @author Titus Wormer
* @copyright 2015 Titus Wormer
* @license MIT
* @module mdast:cli:log
* @fileoverview Log a file context on successful completion.
*/
'use strict';
/*
* Dependencies.
*/
var report = require('vfile-reporter');
/**
* Output diagnostics to stdout(4) or stderr(4).
*
* @param {CLI} context - CLI engine.
*/
function log(context) {
var files = context.files;
var frail = context.frail;
var applicables = files.filter(function (file) {
return file.namespace('mdast:cli').providedByUser;
});
var hasFailed = files.some(function (file) {
return file.hasFailed() || (frail && file.messages.length);
});
var diagnostics = report(applicables, {
'quiet': context.quiet,
'silent': context.silent
});
if (diagnostics) {
context[hasFailed ? 'stderr' : 'stdout'](diagnostics);
}
}
/*
* Expose.
*/
module.exports = log;
|
Fix question's 'formValuesToRequest' to handle create & update | // 1. We should deal with the fact that nullable GraphQL fields can be null in responses
// and set them to be empty strings. Same applies for any other optional property
// 2. We should convert empty string values back to undefined or null or whatever
// the API’s contract is
// 3. Inputs can export parsing and formatting helpers used here. Our internal MoneyInput
// for instance has a static MoneyInput.parseMoneyValue and MoneyInput.convertToMoneyValue
// to be used here
export const responseToFormValues = response => ({
type: response.type,
wording: response.wording,
imageUrl: response.imageUrl,
secondaryWording: response.secondaryWording,
choices: response.choices,
});
/**
* Transforms and array of choices [{ id: '1Ba', text: 'Lorem ipsum' }] into
* an object for 'choices' field in updateQuestion mutation:
* {create: [{ id: '1Ba', text: 'Lorem ipsum' }]
* {update: [{ where: { id: '1Ba' }, data: { text: 'Lorem ipsum' } }]}
* @param {Array<{id: String, text: String}>} choices - Choices array
*/
const choicesValuesToRequest = choices => {
if (choices[0].id) {
// [QuestionChoiceUpdateWithWhereUniqueNestedInput]
return { update: choices.map(({ id, text }) => ({ where: { id }, data: { text } })) };
}
// QuestionChoiceCreateInput
return { create: choices };
};
export const formValuesToRequest = values => ({
type: values.type,
wording: values.wording,
imageUrl: values.imageUrl,
secondaryWording: values.secondaryWording,
choices: values.type === 'MULTIPLE_CHOICE' ? choicesValuesToRequest(values.choices) : null,
});
| // 1. We should deal with the fact that nullable GraphQL fields can be null in responses
// and set them to be empty strings. Same applies for any other optional property
// 2. We should convert empty string values back to undefined or null or whatever
// the API’s contract is
// 3. Inputs can export parsing and formatting helpers used here. Our internal MoneyInput
// for instance has a static MoneyInput.parseMoneyValue and MoneyInput.convertToMoneyValue
// to be used here
export const responseToFormValues = response => ({
type: response.type,
wording: response.wording,
imageUrl: response.imageUrl,
secondaryWording: response.secondaryWording,
choices: response.choices,
});
export const formValuesToRequest = values => ({
type: values.type,
wording: values.wording,
imageUrl: values.imageUrl,
secondaryWording: values.secondaryWording,
// TODO: This should be configurable: 'create' and 'update'
choices: values.type === 'MULTIPLE_CHOICE' ? { create: values.choices } : undefined,
});
|
Add modified get tokens of a shop function | /*
Copyright 2020 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.gpay.virtualqueue.backendservice.repository;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.model.Token;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;
public interface VirtualQueueRepository {
public UUID createShop(CreateShopRequest createShopRequest);
public Map<UUID, Shop> getAllShops();
public List<Token> getTokensByShopId(UUID shopId);
}
| /*
Copyright 2020 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.gpay.virtualqueue.backendservice.repository;
import java.util.Map;
import java.util.UUID;
import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;
public interface VirtualQueueRepository {
public UUID createShop(CreateShopRequest createShopRequest);
public Map<UUID, Shop> getAllShops();
}
|
Fix __all__ to the current list of exported modules (must pass the
tests in test_email.py). | # Copyright (C) 2001 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)
"""A package for parsing, handling, and generating email messages.
"""
__version__ = '1.0'
__all__ = ['Encoders',
'Errors',
'Generator',
'Iterators',
'MIMEAudio',
'MIMEBase',
'MIMEImage',
'MIMEMessage',
'MIMEText',
'Message',
'Parser',
'Utils',
'message_from_string',
'message_from_file',
]
# Some convenience routines
from Parser import Parser as _Parser
from Message import Message as _Message
def message_from_string(s, _class=_Message):
return _Parser(_class).parsestr(s)
def message_from_file(fp, _class=_Message):
return _Parser(_class).parse(fp)
| # Copyright (C) 2001 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)
"""A package for parsing, handling, and generating email messages.
"""
__version__ = '1.0'
__all__ = ['Encoders',
'Errors',
'Generator',
'Image',
'Iterators',
'MIMEBase',
'Message',
'MessageRFC822',
'Parser',
'Text',
'Utils',
'message_from_string',
'message_from_file',
]
# Some convenience routines
from Parser import Parser as _Parser
from Message import Message as _Message
def message_from_string(s, _class=_Message):
return _Parser(_class).parsestr(s)
def message_from_file(fp, _class=_Message):
return _Parser(_class).parse(fp)
|
Allow passing of self rather than just globally uses it | (function (self) {
'use strict';
function fetchPonyfill(options) {
var Promise = options && options.Promise || self.Promise;
var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest;
var global = self;
return (function () {
var self = Object.create(global, {
fetch: {
value: undefined,
writable: true
}
});
// {{whatwgFetch}}
return {
fetch: self.fetch,
Headers: self.Headers,
Request: self.Request,
Response: self.Response
};
}());
}
if (typeof define === 'function' && define.amd) {
define(function () {
return fetchPonyfill;
});
} else if (typeof exports === 'object') {
module.exports = fetchPonyfill;
} else {
self.fetchPonyfill = fetchPonyfill;
}
}(typeof self === 'undefined' ? this : self));
| (function () {
'use strict';
function fetchPonyfill(options) {
var Promise = options && options.Promise || self.Promise;
var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest;
var global = self;
return (function () {
var self = Object.create(global, {
fetch: {
value: undefined,
writable: true
}
});
// {{whatwgFetch}}
return {
fetch: self.fetch,
Headers: self.Headers,
Request: self.Request,
Response: self.Response
};
}());
}
if (typeof define === 'function' && define.amd) {
define(function () {
return fetchPonyfill;
});
} else if (typeof exports === 'object') {
module.exports = fetchPonyfill;
} else {
self.fetchPonyfill = fetchPonyfill;
}
}());
|
Fix a findbugs reported warning | package com.github.cosmo0920.fluentd.flume.plugins;
import org.apache.flume.Event;
import org.komamitsu.fluency.Fluency;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
class FluencyPublisher {
private Fluency fluency;
private String tag;
public FluencyPublisher(String tag) {
this.tag = tag;
}
public void setup(String hostname, int port) throws IOException {
fluency = Fluency.defaultFluency(hostname, port, new Fluency.Config());
}
public void close() {
if (fluency != null) {
try {
fluency.close();
} catch (IOException e) {
// Do nothing.
}
}
fluency = null;
}
// TODO: JSON encoded body support.
public void send(Event event) throws IOException {
String body = new String(event.getBody(), StandardCharsets.UTF_8);
Map<String, Object> fluencyEvent = new HashMap<String, Object>();
fluencyEvent.put("message", body);
fluency.emit(tag, fluencyEvent);
}
}
| package com.github.cosmo0920.fluentd.flume.plugins;
import org.apache.flume.Event;
import org.komamitsu.fluency.Fluency;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
class FluencyPublisher {
private Fluency fluency;
private String tag;
public FluencyPublisher(String tag) {
this.tag = tag;
}
public void setup(String hostname, int port) throws IOException {
fluency = Fluency.defaultFluency(hostname, port, new Fluency.Config());
}
public void close() {
if (fluency != null) {
try {
fluency.close();
} catch (IOException e) {
// Do nothing.
}
}
fluency = null;
}
// TODO: JSON encoded body support.
public void send(Event event) throws IOException {
String body = new String(event.getBody());
Map<String, Object> fluencyEvent = new HashMap<String, Object>();
fluencyEvent.put("message", body);
fluency.emit(tag, fluencyEvent);
}
}
|
Stop an error when trying to kick no one. | <?
require_once(LIB . 'global/smr_alliance.inc');
$alliance = new SMR_ALLIANCE($player->getAllianceID(), SmrSession::$game_id);
$account_id = $_REQUEST['account_id'];
foreach ($account_id as $id)
{
if ($id == $alliance->leader_id)
create_error('You can\'t remove the leader!');
// generate list of messages that should be deleted
if ($account_id_list) $account_id_list .= ',';
$account_id_list .= $id;
$player->sendMessage($id, 2, $db->escape_string('You were kicked out of the alliance!', false));
$curr_acc =& SmrAccount::getAccount($id);
$curr_acc->log(3, 'kicked from alliance: '.$alliance->alliance_name.' by leader', 0);
}
if(empty($account_id_list))
{
create_error('You have to choose someone to remove them!');
}
$db->query('UPDATE player SET alliance_id = 0 WHERE account_id IN ('.$account_id_list.') AND ' .
'game_id = '.$player->getGameID());
$db->query('DELETE FROM player_has_alliance_role WHERE game_id = '.$player->getGameID().' AND account_id IN ('.$account_id_list.')');
forward(create_container('skeleton.php', 'alliance_roster.php'));
?> | <?
require_once(LIB . 'global/smr_alliance.inc');
$alliance = new SMR_ALLIANCE($player->getAllianceID(), SmrSession::$game_id);
$account_id = $_REQUEST['account_id'];
foreach ($account_id as $id) {
if ($id == $alliance->leader_id)
create_error('You can\'t remove the leader!');
// generate list of messages that should be deleted
if ($account_id_list) $account_id_list .= ',';
$account_id_list .= $id;
$player->sendMessage($id, 2, $db->escape_string('You were kicked out of the alliance!', false));
$curr_acc =& SmrAccount::getAccount($id);
$curr_acc->log(3, 'kicked from alliance: '.$alliance->alliance_name.' by leader', 0);
}
$db->query('UPDATE player SET alliance_id = 0 WHERE account_id IN ('.$account_id_list.') AND ' .
'game_id = '.$player->getGameID());
$db->query('DELETE FROM player_has_alliance_role WHERE game_id = '.$player->getGameID().' AND account_id IN ('.$account_id_list.')');
forward(create_container('skeleton.php', 'alliance_roster.php'));
?> |
Fix chat getting stuck up top when first render has history | const {connect} = require('react-redux'),
React = require('react');
module.exports = connect(state => ({
chat: state.chat,
}))(class Chat extends React.Component {
constructor(props) {
super(props);
this.chatRef = React.createRef();
}
getSnapshotBeforeUpdate(prevProps, prevState) {
const chat = this.chatRef.current;
if (prevProps.channel !== this.props.channel || Math.abs(chat.scrollTop - chat.scrollHeight + chat.offsetHeight) < 8) {
return -1;
}
return chat.scrollTop;
}
componentDidUpdate(prevProps, prevState, snapshot) {
const chat = this.chatRef.current;
chat.scrollTop = ~snapshot ? snapshot : chat.scrollHeight;
}
componentDidMount() {
const chat = this.chatRef.current;
chat.scrollTop = chat.scrollHeight;
}
render() {
return <div className='chatBox' style={this.props.style} ref={this.chatRef}>
{this.props.chat.get(this.props.channel)}
</div>;
}
})
| const {connect} = require('react-redux'),
React = require('react');
module.exports = connect(state => ({
chat: state.chat,
}))(class Chat extends React.Component {
constructor(props) {
super(props);
this.chatRef = React.createRef();
}
getSnapshotBeforeUpdate(prevProps, prevState) {
const chat = this.chatRef.current;
if (prevProps.channel !== this.props.channel || Math.abs(chat.scrollTop - chat.scrollHeight + chat.offsetHeight) < 8) {
return -1;
}
return chat.scrollTop;
}
componentDidUpdate(prevProps, prevState, snapshot) {
const chat = this.chatRef.current;
chat.scrollTop = ~snapshot ? snapshot : chat.scrollHeight;
}
render() {
return <div className='chatBox' style={this.props.style} ref={this.chatRef}>
{this.props.chat.get(this.props.channel)}
</div>;
}
})
|
Change to updating every 10s | // TODO: should the baseScore be stored, and updated at vote time?
// This interface should change and become more OO, this'll do for now
var Scoring = {
// re-run the scoring algorithm on a single object
updateObject: function(object) {
if(isNaN(object.score)){
object.score=0;
}
// just count the number of votes for now
var baseScore = object.votes;
// now multiply by 'age' exponentiated
// FIXME: timezones <-- set by server or is getTime() ok?
var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000);
object.score = baseScore * Math.pow(ageInHours + 2, -0.1375);
},
// rerun all the scoring -- TODO: should we check to see if the score has
// changed before saving?
updateScores: function() {
Posts.find().forEach(function(post) {
Scoring.updateObject(post);
Posts.update(post._id, {$set: {score: post.score}});
});
Comments.find().forEach(function(comment) {
Scoring.updateObject(comment);
Comments.update(comment._id, {$set: {score: comment.score}});
});
}
}
// tick every second
Meteor.Cron = new Cron(1000);
// update scores every 10 seconds
Meteor.Cron.addJob(10, function() {
Scoring.updateScores();
}) | // TODO: should the baseScore be stored, and updated at vote time?
// This interface should change and become more OO, this'll do for now
var Scoring = {
// re-run the scoring algorithm on a single object
updateObject: function(object) {
if(isNaN(object.score)){
object.score=0;
}
// just count the number of votes for now
var baseScore = object.votes;
// now multiply by 'age' exponentiated
// FIXME: timezones <-- set by server or is getTime() ok?
var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000);
object.score = baseScore * Math.pow(ageInHours + 2, -0.1375);
},
// rerun all the scoring -- TODO: should we check to see if the score has
// changed before saving?
updateScores: function() {
Posts.find().forEach(function(post) {
Scoring.updateObject(post);
Posts.update(post._id, {$set: {score: post.score}});
});
Comments.find().forEach(function(comment) {
Scoring.updateObject(comment);
Comments.update(comment._id, {$set: {score: comment.score}});
});
}
}
Meteor.Cron = new Cron();
Meteor.Cron.addJob(1, function() {
Scoring.updateScores();
}) |
[Bundle] Make getPath() less error prone by allowing both backward and forward slashes | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SecurityBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddAuthenticationProvidersPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddSecurityVotersPass;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class SecurityBundle extends Bundle
{
public function registerExtensions(ContainerBuilder $container)
{
parent::registerExtensions($container);
$container->addCompilerPass(new AddSecurityVotersPass());
$container->addCompilerPass(new AddAuthenticationProvidersPass());
}
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
protected function getPath()
{
return __DIR__;
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SecurityBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddAuthenticationProvidersPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddSecurityVotersPass;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class SecurityBundle extends Bundle
{
public function registerExtensions(ContainerBuilder $container)
{
parent::registerExtensions($container);
$container->addCompilerPass(new AddSecurityVotersPass());
$container->addCompilerPass(new AddAuthenticationProvidersPass());
}
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
public function getPath()
{
return strtr(__DIR__, '\\', '/');
}
}
|
Fix alignment in FF browser | import vars from '../../styles/vars'
export default {
container: {
color: vars.textColorInverse,
backgroundColor: 'transparent',
display: 'flex',
alignItems: 'center',
textDecoration: 'none',
fontWeight: 400,
opacity: 1,
transition: vars.transition(),
'&:hover': {
opacity: 0.7,
}
},
containerHidden: {
extend: 'container',
opacity: 0,
},
item: {
textAlign: 'center',
flexGrow: 1,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
'-ms-flex-pack': 'center', // justify-content fix for IE10
width: '50%',
maxHeight: 5, // Fix for IE10
},
text: {
},
icon: {
lineHeight: 'normal',
marginRight: 0.8,
marginTop: -0.3, // Fix for wring browser alignment
width: 1.5,
'& svg': {
width: 1.5,
},
},
iconStar: {
extend: 'icon',
fill: vars.themeColor,
},
iconGithub: {
extend: 'icon',
fill: vars.textColorInverse,
}
}
| import vars from '../../styles/vars'
export default {
container: {
color: vars.textColorInverse,
backgroundColor: 'transparent',
display: 'flex',
alignItems: 'center',
textDecoration: 'none',
fontWeight: 400,
opacity: 1,
transition: vars.transition(),
'&:hover': {
opacity: 0.7,
}
},
containerHidden: {
extend: 'container',
opacity: 0,
},
item: {
textAlign: 'center',
flexGrow: 1,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
'-ms-flex-pack': 'center', // justify-content fix for IE10
width: '50%',
padding: 0.5,
maxHeight: 5, // Fix for IE10
},
text: {
},
icon: {
lineHeight: 'normal',
marginRight: 0.8,
marginTop: -0.3, // Fix for wring browser alignment
width: 1.5,
'& svg': {
width: 1.5,
},
},
iconStar: {
extend: 'icon',
fill: vars.themeColor,
},
iconGithub: {
extend: 'icon',
fill: vars.textColorInverse,
}
}
|
Change app-level error handler to use api_client.error exceptions | # coding=utf-8
from flask import render_template
from . import main
from ..api_client.error import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_page(404)
@main.app_errorhandler(500)
def internal_server_error(e):
return _render_error_page(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_page(503, e.response)
def _render_error_page(status_code, error_message=None):
templates = {
404: "errors/404.html",
500: "errors/500.html",
503: "errors/500.html",
}
if status_code not in templates:
status_code = 500
return render_template(
templates[status_code],
error_message=error_message
), status_code
| # coding=utf-8
from flask import render_template
from . import main
from dmapiclient import APIError
@main.app_errorhandler(APIError)
def api_error_handler(e):
return _render_error_page(e.status_code)
@main.app_errorhandler(404)
def page_not_found(e):
return _render_error_page(404)
@main.app_errorhandler(500)
def internal_server_error(e):
return _render_error_page(500)
@main.app_errorhandler(503)
def service_unavailable(e):
return _render_error_page(503, e.response)
def _render_error_page(status_code, error_message=None):
templates = {
404: "errors/404.html",
500: "errors/500.html",
503: "errors/500.html",
}
if status_code not in templates:
status_code = 500
return render_template(
templates[status_code],
error_message=error_message
), status_code
|
Add debugger to stop at edge case point. | if (typeof(messages) === "undefined") {
var messages = {};
}
else {
console.error("There is already a global variable called \"messages\".");
}
function aMsg(key, message){
if (arguments.length === 2 && typeof(key) === "string" && iStr(message)) {
messages[key] = message;
}
else
if (arguments.length === 1 && typeof(key) === "object"){
var p;
for (p in key) {
aMsg(p, key[p]);
}
}
}
function gMsg(key, args){
if (!key) {
throw "No message key specified";
debugger;
}
var msg = messages[key] || key;
var n = arguments.length, msgArgs;
if (n > 2) {
msgArgs = {};
for (i = 1; i < n; i++){
msgArgs[i] = arguments[i];
}
}
else
if (n === 2) {
msgArgs = args;
if (typeof(msgArgs) !== "object") {
msgArgs = {"1": msgArgs}
}
}
var msgArg;
for (msgArg in msgArgs) {
var re = new RegExp("\\$\\{" + msgArg + "\\}", "ig");
msg = msg.replace(re, msgArgs[msgArg]);
}
return msg;
} | if (typeof(messages) === "undefined") {
var messages = {};
}
else {
console.error("There is already a global variable called \"messages\".");
}
function aMsg(key, message){
if (arguments.length === 2 && typeof(key) === "string" && iStr(message)) {
messages[key] = message;
}
else
if (arguments.length === 1 && typeof(key) === "object"){
var p;
for (p in key) {
aMsg(p, key[p]);
}
}
}
function gMsg(key, args){
if (!key) {
throw "No message key specified";
}
var msg = messages[key] || key;
var n = arguments.length, msgArgs;
if (n > 2) {
msgArgs = {};
for (i = 1; i < n; i++){
msgArgs[i] = arguments[i];
}
}
else
if (n === 2) {
msgArgs = args;
if (typeof(msgArgs) !== "object") {
msgArgs = {"1": msgArgs}
}
}
var msgArg;
for (msgArg in msgArgs) {
var re = new RegExp("\\$\\{" + msgArg + "\\}", "ig");
msg = msg.replace(re, msgArgs[msgArg]);
}
return msg;
} |
Update strings to use single quotes for jshint | (function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'projects.list': {
url: '', // No url, this state is the index of projects
templateUrl: 'app/states/projects/list/list.html',
controller: StateController,
controllerAs: 'vm',
title: 'Projects',
resolve: {
projects: resolveProjects
}
}
};
}
/** @ngInject */
function resolveProjects(Project) {
return Project.query({archived: false}).$promise;
}
/** @ngInject */
function StateController(projects, lodash) {
var vm = this;
vm.projects = projects;
vm.activate = activate;
vm.title = 'Projects';
activate();
function activate() {
vm.projects = lodash.sortBy(vm.projects, 'name');
}
}
})();
| (function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'projects.list': {
url: '', // No url, this state is the index of projects
templateUrl: 'app/states/projects/list/list.html',
controller: StateController,
controllerAs: 'vm',
title: 'Projects',
resolve: {
projects: resolveProjects
}
}
};
}
/** @ngInject */
function resolveProjects(Project) {
return Project.query({archived: false}).$promise;
}
/** @ngInject */
function StateController(projects, lodash) {
var vm = this;
vm.projects = projects;
vm.activate = activate;
vm.title = 'Projects';
activate();
function activate() {
vm.projects = lodash.sortBy(vm.projects, "name");
}
}
})();
|
Fix incorrect social redirect link | import subprocess
from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def deploy(request):
deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY')
# branch = request.POST.get('BRANCH')
commit = request.POST.get('COMMIT')
if deploy_secret_key != settings.SECRET_KEY:
return HttpResponseBadRequest('Incorrect key.')
subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
return JsonResponse({'result': 'deploy started'})
def social_redirect(request):
token, _ = Token.objects.get_or_create(user=request.user)
return redirect('http://dotateamfinder.com/finish-steam/{}'.format(token.key))
| import subprocess
from django.conf import settings
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def deploy(request):
deploy_secret_key = request.POST.get('DEPLOY_SECRET_KEY')
# branch = request.POST.get('BRANCH')
commit = request.POST.get('COMMIT')
if deploy_secret_key != settings.SECRET_KEY:
return HttpResponseBadRequest('Incorrect key.')
subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
return JsonResponse({'result': 'deploy started'})
def social_redirect(request):
token, _ = Token.objects.get_or_create(user=request.user)
return redirect('http://localhost:3000/finish-steam/{}'.format(token.key))
|
Replace module with sitemap component | <?php
/**
* @link https://github.com/himiklab/yii2-sitemap-module
* @copyright Copyright (c) 2014 HimikLab
* @license http://opensource.org/licenses/MIT MIT
*/
namespace assayerpro\sitemap\controllers;
use Yii;
use yii\web\Controller;
/**
* @author HimikLab
* @package himiklab\sitemap
*/
class DefaultController extends Controller
{
public function actionIndex()
{
/** @var \himiklab\sitemap\Sitemap $module */
$module = Yii::$app->sitemap;
if (!$sitemapData = $module->cacheProvider->get($module->cacheKey)) {
$sitemapData = $module->buildSitemap();
}
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/xml');
if ($module->enableGzip) {
$sitemapData = gzencode($sitemapData);
$headers->add('Content-Encoding', 'gzip');
$headers->add('Content-Length', strlen($sitemapData));
}
return $sitemapData;
}
}
| <?php
/**
* @link https://github.com/himiklab/yii2-sitemap-module
* @copyright Copyright (c) 2014 HimikLab
* @license http://opensource.org/licenses/MIT MIT
*/
namespace assayerpro\sitemap\controllers;
use Yii;
use yii\web\Controller;
/**
* @author HimikLab
* @package himiklab\sitemap
*/
class DefaultController extends Controller
{
public function actionIndex()
{
/** @var \himiklab\sitemap\Sitemap $module */
$module = $this->module;
if (!$sitemapData = $module->cacheProvider->get($module->cacheKey)) {
$sitemapData = $module->buildSitemap();
}
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/xml');
if ($module->enableGzip) {
$sitemapData = gzencode($sitemapData);
$headers->add('Content-Encoding', 'gzip');
$headers->add('Content-Length', strlen($sitemapData));
}
return $sitemapData;
}
}
|
Fix transitioning to results page | import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller, session) {
this._super(controller, session);
controller.set('experiment', this.controllerFor('participate.survey').get('experiment'));
controller.set('session', session);
controller.set('pastSessions', []);
},
actions: {
willTransition(transition) {
this._super(transition);
if (transition.targetName === 'participate.survey.results') {
return true;
}
var frameIndex = this.controllerFor('participate.survey.index').get('frameIndex');
var framePage = this.controllerFor('participate.survey.index').get('framePage');
if (frameIndex !== 0) {
this.replaceWith('participate.survey.index');
// Disable back button in qsort page 2, and rating-form page 1
if (!(frameIndex === 2 && framePage === 1) && frameIndex !== 3) {
this.controllerFor('participate.survey.index').set('frameIndex', frameIndex - 1);
}
// Update pages within the rating-form
if (frameIndex === 3 && framePage !== 0) {
this.controllerFor('participate.survey.index').set('framePage', framePage - 1);
}
}
}
}
});
| import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller, session) {
this._super(controller, session);
controller.set('experiment', this.controllerFor('participate.survey').get('experiment'));
controller.set('session', session);
controller.set('pastSessions', []);
},
actions: {
willTransition(transition) {
this._super(transition);
var frameIndex = this.controllerFor('participate.survey.index').get('frameIndex');
var framePage = this.controllerFor('participate.survey.index').get('framePage');
if (frameIndex !== 0) {
this.replaceWith('participate.survey.index');
// Disable back button in qsort page 2, and rating-form page 1
if (!(frameIndex === 2 && framePage === 1) && frameIndex !== 3) {
this.controllerFor('participate.survey.index').set('frameIndex', frameIndex - 1);
}
// Update pages within the rating-form
if (frameIndex === 3 && framePage !== 0) {
this.controllerFor('participate.survey.index').set('framePage', framePage - 1);
}
}
}
}
});
|
Fix a mistake.(repeated variable assign; var str = str = ...) Concentrate unnecessary line to another. | function r() {
var strings = arguments[0];
var values = Array.prototype.slice.call(arguments, 1);
// concentrate strings and interpolations
var str = strings.raw.reduce(function(prev, cur, idx) {
return prev + values[idx-1] + cur;
})
.replace(/\r\n/g, '\n');
var newlineAndTabs = str.match(/^\n[\t]*/);
if( newlineAndTabs != null ) {
var matched = newlineAndTabs[0];
str = str.replace(new RegExp(matched, 'g'), '\n').substr(1);
}
else {
var matched = str.match(/^[\t]*/)[0];
str = str.substr(matched.length).replace(new RegExp('\n'+matched, 'g'), '\n');
}
return str;
}
module.exports = r; | function r() {
var strings = arguments[0];
var values = Array.prototype.slice.call(arguments, 1);
var str = str = strings.raw.reduce(function(prev, cur, idx) {
return prev + values[idx-1] + cur;
});
str = str.replace(/\r\n/g, '\n');
var newlineAndTabs = str.match(/^\n[\t]*/);
if( newlineAndTabs != null ) {
var matched = newlineAndTabs[0];
str = str.replace(new RegExp(matched, 'g'), '\n').substr(1);
}
else {
var matched = str.match(/^[\t]*/)[0];
str = str.substr(matched.length).replace(new RegExp('\n'+matched, 'g'), '\n');
}
return str;
}
module.exports = r; |
Add python_requires to help pip | from setuptools import setup
setup(
name='pytest-flakes',
description='pytest plugin to check source code with pyflakes',
long_description=open("README.rst").read(),
license="MIT license",
version='4.0.1',
author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',
url='https://github.com/asmeurer/pytest-flakes',
python_requires='>=3.5',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Software Development :: Testing',
],
py_modules=['pytest_flakes'],
entry_points={'pytest11': ['flakes = pytest_flakes']},
install_requires=['pytest>=2.8.0', 'pyflakes'])
| from setuptools import setup
setup(
name='pytest-flakes',
description='pytest plugin to check source code with pyflakes',
long_description=open("README.rst").read(),
license="MIT license",
version='4.0.1',
author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',
url='https://github.com/asmeurer/pytest-flakes',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Software Development :: Testing',
],
py_modules=['pytest_flakes'],
entry_points={'pytest11': ['flakes = pytest_flakes']},
install_requires=['pytest>=2.8.0', 'pyflakes'])
|
Set app root path to app root | var path = require('path')
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry: './index.js',
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
},
resolve: {
root: [
path.resolve('.')
]
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract('style', 'css!less')
}
]
},
lessLoader: {
includePath: [path.resolve(__dirname, './styles')]
},
plugins: [
/* Uncomment this when ready for prod
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
*/
new ExtractTextPlugin('styles.css')
]
} | var path = require('path')
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry: './index.js',
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract('style', 'css!less')
}
]
},
lessLoader: {
includePath: [path.resolve(__dirname, './styles')]
},
plugins: [
/* Uncomment this when ready for prod
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
*/
new ExtractTextPlugin('styles.css')
]
} |
Switch optimization back to -O2 | from setuptools import setup, Extension
setup(
name='asyncpg',
version='0.0.1',
description='An asyncio PosgtreSQL driver',
classifiers=[
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Development Status :: 4 - Beta',
],
platforms=['POSIX'],
author='MagicStack Inc',
author_email='hello@magic.io',
license='MIT',
packages=['asyncpg'],
provides=['asyncpg'],
include_package_data=True,
ext_modules=[
Extension("asyncpg.protocol.protocol",
["asyncpg/protocol/record/recordobj.c",
"asyncpg/protocol/protocol.c"],
extra_compile_args=['-O2'])
]
)
| from setuptools import setup, Extension
setup(
name='asyncpg',
version='0.0.1',
description='An asyncio PosgtreSQL driver',
classifiers=[
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Development Status :: 4 - Beta',
],
platforms=['POSIX'],
author='MagicStack Inc',
author_email='hello@magic.io',
license='MIT',
packages=['asyncpg'],
provides=['asyncpg'],
include_package_data=True,
ext_modules=[
Extension("asyncpg.protocol.protocol",
["asyncpg/protocol/record/recordobj.c",
"asyncpg/protocol/protocol.c"],
extra_compile_args=['-O3'])
]
)
|
Add test to ensure extra content after <a></a> is also extracted | package nl.hsac.fitnesse.fixture.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class HtmlCleanerTest {
private final HtmlCleaner cleaner = new HtmlCleaner();
@Test
public void testCleanUrl() {
assertEquals("http://hallo.com/test", cleaner.getUrl("http://hallo.com/test"));
assertEquals("http://hallo.com/test2", cleaner.getUrl("<a href=\"http://hallo.com/test2\">Hallo</a>"));
assertEquals("http://hallo.com/test3?testparam=1", cleaner.getUrl("<a href=\"http://hallo.com/test3?testparam=1\">Hallo2</a>"));
assertEquals("http://hallo.com/test3?testparam=1¶m2=3", cleaner.getUrl("<a href=\"http://hallo.com/test3?testparam=1&param2=3\">Hallo3</a>"));
assertEquals("http://hallo.com/test2123", cleaner.getUrl("<a href=\"http://hallo.com/test2\">Hallo</a>123"));
assertNull(cleaner.getUrl(null));
}
}
| package nl.hsac.fitnesse.fixture.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class HtmlCleanerTest {
private final HtmlCleaner cleaner = new HtmlCleaner();
@Test
public void testCleanUrl() {
assertEquals("http://hallo.com/test", cleaner.getUrl("http://hallo.com/test"));
assertEquals("http://hallo.com/test2", cleaner.getUrl("<a href=\"http://hallo.com/test2\">Hallo</a>"));
assertEquals("http://hallo.com/test3?testparam=1", cleaner.getUrl("<a href=\"http://hallo.com/test3?testparam=1\">Hallo2</a>"));
assertEquals("http://hallo.com/test3?testparam=1¶m2=3", cleaner.getUrl("<a href=\"http://hallo.com/test3?testparam=1&param2=3\">Hallo3</a>"));
assertNull(cleaner.getUrl(null));
}
}
|
Include `highlight.js`-styles into less file.
Fixes bootprint/bootprint#16
This commit ensures that the styling of examples in bootprint-openapi is
visible. | var path = require('path')
// Export function to create new config (builder is passed in from outside)
module.exports = function (builder) {
var bootstrapLess = require.resolve('bootstrap/less/bootstrap.less')
return builder.merge({
handlebars: {
templates: path.resolve(__dirname, 'handlebars', 'templates'),
partials: path.resolve(__dirname, 'handlebars', 'partials'),
helpers: require.resolve('./handlebars/helpers.js'),
/**
* A preprocessor that may return a modified json before entering the rendering process.
* Access the inherited preprocessor is possible via <code>this.previous(json)</code>
* @param obj the input object
* @return a modified object or a promise for a modified object.
*/
preprocessor: function (obj) {
return obj
}
},
less: {
main: [
bootstrapLess,
require.resolve('highlight.js/styles/default.css'),
require.resolve('./less/main.less')
],
paths: [
path.dirname(bootstrapLess)
]
}
})
}
// Add "package" to be used by bootprint-doc-generator
module.exports.package = require('./package')
| var path = require('path')
// Export function to create new config (builder is passed in from outside)
module.exports = function (builder) {
var bootstrapLess = require.resolve('bootstrap/less/bootstrap.less')
return builder.merge({
handlebars: {
templates: path.resolve(__dirname, 'handlebars', 'templates'),
partials: path.resolve(__dirname, 'handlebars', 'partials'),
helpers: require.resolve('./handlebars/helpers.js'),
/**
* A preprocessor that may return a modified json before entering the rendering process.
* Access the inherited preprocessor is possible via <code>this.previous(json)</code>
* @param obj the input object
* @return a modified object or a promise for a modified object.
*/
preprocessor: function (obj) {
return obj
}
},
less: {
main: [
bootstrapLess,
require.resolve('./less/main.less')
],
paths: [
path.dirname(bootstrapLess)
]
}
})
}
// Add "package" to be used by bootprint-doc-generator
module.exports.package = require('./package')
|
Change admin path and link layout | // Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').config();
// Require keystone
var keystone = require('keystone');
// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.
keystone.init({
'name': 'Repository of Papers',
'brand': 'Repository of Papers',
'sass': 'public',
'static': 'public',
'favicon': 'public/favicon.ico',
'views': 'templates/views',
'view engine': 'pug',
'admin path': 'library',
'auto update': true,
'session': true,
'auth': true,
'user model': 'User',
});
// Load your project's Models
keystone.import('models');
// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
_: require('lodash'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable,
});
// Load your project's Routes
keystone.set('routes', require('./routes'));
// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
content: ['papers', 'authors', 'organizations'],
users: 'users',
});
// Start Keystone to connect to your database and initialise the web server
keystone.start();
| // Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').config();
// Require keystone
var keystone = require('keystone');
// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.
keystone.init({
'name': 'Repository of Papers',
'brand': 'Repository of Papers',
'sass': 'public',
'static': 'public',
'favicon': 'public/favicon.ico',
'views': 'templates/views',
'view engine': 'pug',
'auto update': true,
'session': true,
'auth': true,
'user model': 'User',
});
// Load your project's Models
keystone.import('models');
// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
_: require('lodash'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable,
});
// Load your project's Routes
keystone.set('routes', require('./routes'));
// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
users: 'users',
});
// Start Keystone to connect to your database and initialise the web server
keystone.start();
|
Remove placeholder content from online list | var UserList = React.createClass({
componentDidMount: function() {
socket.on('join', this._join);
socket.on('part', this._part);
},
render: function() {
return (
<ul id='online-list'></ul>
);
},
_join: function(username) {
if (username != myUsername) {
addOnlineUserToList(username);
}
},
_part: function(username) {
$('#online-list li span').filter(function() {
return $(this).text() == username;
}).parent().remove();
}
});
React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
| var UserList = React.createClass({
componentDidMount: function() {
socket.on('join', this._join);
socket.on('part', this._part);
},
render: function() {
return (
<ul id='online-list'>
<li>
<img src='https://avatars.githubusercontent.com/dionyziz' alt='' class='avatar' />
<span>dionyziz</span>
</li>
</ul>
);
},
_join: function(username) {
if (username != myUsername) {
addOnlineUserToList(username);
}
},
_part: function(username) {
$('#online-list li span').filter(function() {
return $(this).text() == username;
}).parent().remove();
}
});
React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
|
Fix the numpy include path used by the Cython extension
Apparently this only worked because I had numpy installed system-wide
(broke on virtualenv-only installs). | import sys
import numpy
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse",
sources=["src/nerven/epoc/_parse.pyx"],
include_dirs=[".", numpy.get_include()]),
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='sio@tesser.org',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
| import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse", ["src/nerven/epoc/_parse.pyx"])
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='sio@tesser.org',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
|
Replace sf2 form->bind by handlerequest | <?php
/*
* This file is part of the Incipio package.
*
* (c) Florian Lefevre
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mgate\SuiviBundle\Form\Type;
use Doctrine\ORM\EntityManager;
use Mgate\SuiviBundle\Entity\ClientContact;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
class ClientContactHandler
{
protected $form;
protected $request;
protected $em;
public function __construct(Form $form, Request $request, EntityManager $em)
{
$this->form = $form;
$this->request = $request;
$this->em = $em;
}
public function process()
{
if ($this->request->getMethod() == 'POST') {
$this->form->handleRequest($this->request);
if ($this->form->isValid()) {
$this->onSuccess($this->form->getData());
return true;
}
}
return false;
}
public function onSuccess(ClientContact $clientcontact)
{
$this->em->persist($clientcontact);
$this->em->flush();
}
}
| <?php
/*
* This file is part of the Incipio package.
*
* (c) Florian Lefevre
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// src/Sdz/BlogBundle/Form/ArticleHandler.php
namespace Mgate\SuiviBundle\Form\Type;
use Doctrine\ORM\EntityManager;
use Mgate\SuiviBundle\Entity\ClientContact;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
class ClientContactHandler
{
protected $form;
protected $request;
protected $em;
public function __construct(Form $form, Request $request, EntityManager $em)
{
$this->form = $form;
$this->request = $request;
$this->em = $em;
}
public function process()
{
if ($this->request->getMethod() == 'POST') {
$this->form->bind($this->request);
if ($this->form->isValid()) {
$this->onSuccess($this->form->getData());
return true;
}
}
return false;
}
public function onSuccess(ClientContact $clientcontact)
{
$this->em->persist($clientcontact);
$this->em->flush();
}
}
|
Update react template to reflect latest player changes | /*
Current state of affairs:
- Gadget must be exported to window object, modules are not supported
Proper support for modules will come later.
Currently player is built with r.js and that breaks modules.
- The name of the export on window object must equal to the "name" field in versal.json
Player will look up this name on window object, after script is downloaded and evaluated
*/
window.SampleGadget = React.createClass({
propTypes: {
gadget: React.PropTypes.shape({
// Gadget API:
//Indicates, whether the gadget is editable or not (author/learner modes)
isEditable: React.PropTypes.bool.isRequired,
// It won't do anything, if gadget is not editable.
patchProps: React.PropTypes.func.isRequired,
// Environment. Contains `sessionId` of current user and `apiUrl`
environment: React.PropTypes.object
}).isRequired,
// Gadget-specific properties
counter: React.PropTypes.number
},
getDefaultProps: function(){
return {
counter: 0
}
},
render: function(){
if(this.props.gadget.isEditable) {
return React.DOM.button({ onClick: this.increaseCounter }, this.props.counter)
} else {
return React.DOM.div(null, 'Clicks so far:' + this.props.counter)
}
},
increaseCounter: function(){
this.props.gadget.patchProps({ counter: this.props.counter + 1 })
}
})
| /*
Current state of affairs:
- Gadget must be exported to window object, modules are not supported
Proper support for modules will come later.
Currently player is built with r.js and that breaks modules.
- The name of the export on window object must equal to the "name" field in versal.json
Player will look up this name on window object, after script is downloaded and evaluated
*/
window.SampleGadget = React.createClass({
propTypes: {
// Player API:
//Indicates, whether the gadget is editable or not (author/learner modes)
isEditable: React.PropTypes.bool.isRequired,
// Use this function to persist attributes.
// Attributes will be immediately sent back in props.
// Won't do anything, if gadget is not editable.
patchAttributes: React.PropTypes.func.isRequired,
// Environment. Contains `sessionId` of current user and `apiUrl`
environment: React.PropTypes.object,
// Gadget-specific properties
counter: React.PropTypes.number
},
getDefaultProps: function(){
return {
counter: 0
}
},
render: function(){
if(this.props.isEditable) {
return React.DOM.button({ onClick: this.increaseCounter }, this.props.counter)
} else {
return React.DOM.div(null, 'Clicks so far:' + this.props.counter)
}
},
increaseCounter: function(){
this.props.patchAttributes({ counter: this.props.counter + 1 })
}
})
|
:shower: Remove unnecessary plugin using declaration | const package = require('./package.json')
module.exports = {
parser: 'babel-eslint',
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true
},
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:react/recommended',
'plugin:flowtype/recommended',
// suppress conflicted rules
'plugin:prettier/recommended',
'prettier/flowtype',
'prettier/react'
],
parserOptions: {
ecmaFeatures: {
experimentalObjectRestSpread: true,
jsx: true
},
sourceType: 'module'
},
plugins: [],
settings: {
react: {
version: package.dependencies.react
}
},
rules: {
'no-console': 'warn',
'flowtype/require-valid-file-annotation': ['warn', 'always'],
'react/no-deprecated': 'warn',
'react/prefer-stateless-function': 'error'
}
}
| const package = require('./package.json')
module.exports = {
parser: 'babel-eslint',
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true
},
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:react/recommended',
'plugin:flowtype/recommended',
// suppress conflicted rules
'plugin:prettier/recommended',
'prettier/flowtype',
'prettier/react'
],
parserOptions: {
ecmaFeatures: {
experimentalObjectRestSpread: true,
jsx: true
},
sourceType: 'module'
},
plugins: ['flowtype'],
settings: {
react: {
version: package.dependencies.react
}
},
rules: {
'no-console': 'warn',
'flowtype/require-valid-file-annotation': ['warn', 'always'],
'react/no-deprecated': 'warn',
'react/prefer-stateless-function': 'error'
}
}
|
Fix backward merge test object order | package ee.shy.core.merge;
import ee.shy.TemporaryDirectory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assume.*;
public abstract class MergerTest<T> {
@Rule
public TemporaryDirectory temporaryDirectory = new TemporaryDirectory();
protected T patchable;
protected T original;
protected T revised;
protected T patched;
protected abstract T getState(String name) throws IOException;
@Before
public void setUp() throws Exception {
patchable = getState("patchable");
original = getState("original");
revised = getState("revised");
patched = getState("patched");
assumeNotNull(patchable, original, revised, patchable);
}
@Test
public void testForwardMainMerge() throws Exception {
testMerge(patchable, original, revised, patched);
}
@Test
public void testForwardSideMerge() throws Exception {
testMerge(revised, original, patchable, patched);
}
@Test
public void testBackwardMainMerge() throws Exception {
testMerge(patchable, patched, revised, original);
}
@Test
public void testBackwardSideMerge() throws Exception {
testMerge(revised, patched, patchable, original);
}
protected abstract void testMerge(T patchable, T original, T revised, T patched) throws IOException;
}
| package ee.shy.core.merge;
import ee.shy.TemporaryDirectory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assume.*;
public abstract class MergerTest<T> {
@Rule
public TemporaryDirectory temporaryDirectory = new TemporaryDirectory();
protected T patchable;
protected T original;
protected T revised;
protected T patched;
protected abstract T getState(String name) throws IOException;
@Before
public void setUp() throws Exception {
patchable = getState("patchable");
original = getState("original");
revised = getState("revised");
patched = getState("patched");
assumeNotNull(patchable, original, revised, patchable);
}
@Test
public void testForwardMainMerge() throws Exception {
testMerge(patchable, original, revised, patched);
}
@Test
public void testForwardSideMerge() throws Exception {
testMerge(revised, original, patchable, patched);
}
@Test
public void testBackwardMainMerge() throws Exception {
testMerge(patched, revised, original, patchable);
}
@Test
public void testBackwardSideMerge() throws Exception {
testMerge(original, revised, patched, patchable);
}
protected abstract void testMerge(T patchable, T original, T revised, T patched) throws IOException;
}
|
Fix helment null ptr exception
This fixes https://github.com/webkom/lego/issues/1720 | // @flow
import * as React from 'react';
import { Helmet } from 'react-helmet';
import config from 'app/config';
import { type ComponentType, createElement } from 'react';
/**
* A higher order component that wraps the given component in
* LoadingIndicator while `props[loadingProp]` is being fetched.
*/
type Property = {
property?: string,
content?: string,
element?: string,
children?: string,
rel?: string,
href?: string
};
type PropertyGenerator = (props: Object, config?: Object) => ?Array<Property>;
export default function helmet<T>(propertyGenerator: ?PropertyGenerator) {
return (Component: ComponentType<T>) => ({
PropertyGenerator,
...props
}: T & {
propertyGenerator: ?PropertyGenerator
}) => {
const properties: ?Array<Property> =
propertyGenerator && propertyGenerator(props, config);
return (
<>
{properties && (
<Helmet>
{properties.map(({ element, children, ...props }, index) =>
createElement(
element || 'meta',
{ key: index, ...props },
children
)
)}
</Helmet>
)}
<Component {...props} />
</>
);
};
}
| // @flow
import * as React from 'react';
import { Helmet } from 'react-helmet';
import config from 'app/config';
import { type ComponentType, createElement } from 'react';
/**
* A higher order component that wraps the given component in
* LoadingIndicator while `props[loadingProp]` is being fetched.
*/
type PropertyGenerator = (
props: Object,
config?: Object
) => Array<{
property?: string,
content?: string,
element?: string,
children?: string,
rel?: string,
href?: string
}>;
export default function helmet<T>(propertyGenerator: ?PropertyGenerator) {
return (Component: ComponentType<T>) => ({
PropertyGenerator,
...props
}: T & {
propertyGenerator: PropertyGenerator
}) => [
<Helmet key="helmet">
{!!propertyGenerator &&
propertyGenerator(props, config).map(
({ element, children, ...props }, index) =>
createElement(element || 'meta', { key: index, ...props }, children)
)}
</Helmet>,
<Component key="component" {...props} />
];
}
|
refactor: Rewrite pickDownloads as Ramda function | import R from 'ramda';
import { NpmConfig, httpsGetPromise } from './helpers';
const addVersionProp = (val, key, obj) => obj[key] = { 'version': removeCaret(val) };
const removeCaret = R.replace(/\^/, '');
const isNotPrivate = R.compose(R.not, R.prop('private'));
const filterPrivate = R.filter(isNotPrivate);
const pickProps = R.curry(R.pick);
const deeplyMerge = (obj1, obj2) => {
return R.keys(obj1).reduce((result, key) => {
result[key] = R.merge(obj1[key], obj2[key]);
return result;
}, {});
};
export const addNode = (obj) => {
obj.node = {
name : 'Node.js',
url : 'https://nodejs.org',
version : process.versions.node,
description : 'A JavaScript runtime ✨🐢🚀✨',
downloads : 10000000 // A fake number since Node isn't downloaded on npm
};
return obj;
};
export const pickDownloads = R.map(pickProps(['downloads']));
export const curriedMerge = R.curry(deeplyMerge);
export const formatVersionsAndFilterPrivate = R.compose(R.mapObjIndexed(addVersionProp), filterPrivate);
export const getNpmData = R.compose(httpsGetPromise, NpmConfig);
| import R from 'ramda';
import { NpmConfig, httpsGetPromise } from './helpers';
const addVersionProp = (val, key, obj) => obj[key] = { 'version': removeCaret(val) };
const removeCaret = R.replace(/\^/, '');
const isNotPrivate = R.compose(R.not, R.prop('private'));
const filterPrivate = R.filter(isNotPrivate);
const deeplyMerge = (obj1, obj2) => {
return R.keys(obj1).reduce((result, key) => {
result[key] = R.merge(obj1[key], obj2[key]);
return result;
}, {});
};
export const pickDownloads = (obj) => {
return R.keys(obj).reduce((result, key) => {
result[key] = R.pick(['downloads'], obj[key]);
return result;
}, {});
};
export const addNode = (obj) => {
obj.node = {
name : 'Node.js',
url : 'https://nodejs.org',
version : process.versions.node,
description : 'A JavaScript runtime ✨🐢🚀✨',
downloads : 10000000 // A fake number since Node isn't downloaded on npm
};
return obj;
};
export const curriedMerge = R.curry(deeplyMerge);
export const formatVersionsAndFilterPrivate = R.compose(R.mapObjIndexed(addVersionProp), filterPrivate);
export const getNpmData = R.compose(httpsGetPromise, NpmConfig);
|
Add "new" constructor wrapper to Polynomial. | (function(define) {'use strict';
define(function(require) {
// creates a polynomial function from the array of coefficients
// for example, if the function is ax^3 + bx^2 + cx + d
// the array is [a, b, c, d], that is, the array indexing is
// the reverse of the usual coefficient indexing
function Polynomial(coefs) {
if (coefs instanceof Polynomial) { return coefs; }
this.coefs = coefs;
}
Polynomial.new = function(coefs) {
return new Polynomial(coefs);
};
Polynomial.prototype.evalAt = function evalAt(x) {
return this.coefs.reduce(function(acc, coef) {
return acc * x + coef;
}, 0);
};
return Polynomial;
});
}(typeof define === 'function' && define.amd ? define : function(factory) {
'use strict';
module.exports = factory(require);
}));
| (function(define) {'use strict';
define(function(require) {
// creates a polynomial function from the array of coefficients
// for example, if the function is ax^3 + bx^2 + cx + d
// the array is [a, b, c, d], that is, the array indexing is
// the reverse of the usual coefficient indexing
function Polynomial(coefs) {
if (coefs instanceof Polynomial) { return coefs; }
this.coefs = coefs;
}
Polynomial.prototype.evalAt = function evalAt(x) {
return this.coefs.reduce(function(acc, coef) {
return acc * x + coef;
}, 0);
};
return Polynomial;
});
}(typeof define === 'function' && define.amd ? define : function(factory) {
'use strict';
module.exports = factory(require);
}));
|
Fix compilation after updating mvdan/sh | package execext
import (
"context"
"errors"
"io"
"os"
"strings"
"mvdan.cc/sh/interp"
"mvdan.cc/sh/syntax"
)
// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
Context context.Context
Command string
Dir string
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
var (
// ErrNilOptions is returned when a nil options is given
ErrNilOptions = errors.New("execext: nil options given")
)
// RunCommand runs a shell command
func RunCommand(opts *RunCommandOptions) error {
if opts == nil {
return ErrNilOptions
}
p, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), "")
if err != nil {
return err
}
environ := opts.Env
if len(environ) == 0 {
environ = os.Environ()
}
env, err := interp.EnvFromList(environ)
if err != nil {
return err
}
r := interp.Runner{
Context: opts.Context,
Dir: opts.Dir,
Env: env,
Exec: interp.DefaultExec,
Open: interp.OpenDevImpls(interp.DefaultOpen),
Stdin: opts.Stdin,
Stdout: opts.Stdout,
Stderr: opts.Stderr,
}
if err = r.Reset(); err != nil {
return err
}
return r.Run(p)
}
| package execext
import (
"context"
"errors"
"io"
"strings"
"mvdan.cc/sh/interp"
"mvdan.cc/sh/syntax"
)
// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
Context context.Context
Command string
Dir string
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
var (
// ErrNilOptions is returned when a nil options is given
ErrNilOptions = errors.New("execext: nil options given")
)
// RunCommand runs a shell command
func RunCommand(opts *RunCommandOptions) error {
if opts == nil {
return ErrNilOptions
}
p, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), "")
if err != nil {
return err
}
r := interp.Runner{
Context: opts.Context,
Dir: opts.Dir,
Env: opts.Env,
Exec: interp.DefaultExec,
Open: interp.OpenDevImpls(interp.DefaultOpen),
Stdin: opts.Stdin,
Stdout: opts.Stdout,
Stderr: opts.Stderr,
}
if err = r.Reset(); err != nil {
return err
}
return r.Run(p)
}
|
Include jQuery in Jasmine specs | /**
* jasmine
* =======
*
* Test settings
*
* Link: https://github.com/gruntjs/grunt-contrib-jasmine
*/
'use strict';
module.exports = function (grunt) {
return {
dist: {
src: [
'<%= pkg.config.src %>/scripts/core.js',
'<%= pkg.config.src %>/scripts/event.js',
'<%= pkg.config.src %>/scripts/class.js',
'<%= pkg.config.src %>/scripts/base.js',
'<%= pkg.config.src %>/scripts/svg.js',
'<%= pkg.config.src %>/scripts/charts/line.js',
'<%= pkg.config.src %>/scripts/charts/bar.js',
'<%= pkg.config.src %>/scripts/charts/pie.js'
],
options: {
specs: '<%= pkg.config.test %>/spec/**/spec-*.js',
helpers: '<%= pkg.config.test %>/spec/**/helper-*.js',
vendor: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'
],
phantomjs: {
'ignore-ssl-errors': true
}
}
}
};
};
| /**
* jasmine
* =======
*
* Test settings
*
* Link: https://github.com/gruntjs/grunt-contrib-jasmine
*/
'use strict';
module.exports = function (grunt) {
return {
dist: {
src: [
'<%= pkg.config.src %>/scripts/core.js',
'<%= pkg.config.src %>/scripts/event.js',
'<%= pkg.config.src %>/scripts/class.js',
'<%= pkg.config.src %>/scripts/base.js',
'<%= pkg.config.src %>/scripts/svg.js',
'<%= pkg.config.src %>/scripts/charts/line.js',
'<%= pkg.config.src %>/scripts/charts/bar.js',
'<%= pkg.config.src %>/scripts/charts/pie.js'
],
options: {
specs: '<%= pkg.config.test %>/spec/**/spec-*.js',
helpers: '<%= pkg.config.test %>/spec/**/helper-*.js',
phantomjs: {
'ignore-ssl-errors': true
}
}
}
};
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.