text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Replace logo to top box | 'use strict';
const template = require('../views/index.hbs');
const Logo = require('./components/Logo.js');
const CurrentWeather = require('./pages/CurrentWeather.js');
const ForecastWeather = require('./pages/ForecastWeather.js');
const Search = require('./components/Search.js');
const ErrorPage = require('./pages/ErrorPage.js');
class App {
constructor() {
this._render();
}
_render() {
let container = document.querySelector('.app-container');
container.innerHTML = template();
let logo = new Logo();
container.querySelector('.top').appendChild(logo.container);
let currentWeather = new CurrentWeather();
container.querySelector('.show-box').appendChild(currentWeather.container);
let forecastWeather = new ForecastWeather();
container.querySelector('.show-box').appendChild(forecastWeather.container);
let search = new Search(logo, currentWeather, forecastWeather);
container.querySelector('.app').appendChild(search.container);
let errorPage = new ErrorPage();
container.querySelector('.show-box').appendChild(errorPage.container);
}
}
module.exports = App;
| 'use strict';
const template = require('../views/index.hbs');
const Logo = require('./components/Logo.js');
const CurrentWeather = require('./pages/CurrentWeather.js');
const ForecastWeather = require('./pages/ForecastWeather.js');
const Search = require('./components/Search.js');
const ErrorPage = require('./pages/ErrorPage.js');
class App {
constructor() {
this._render();
}
_render() {
let container = document.querySelector('.app-container');
container.innerHTML = template();
let logo = new Logo();
container.querySelector('.show-box').appendChild(logo.container);
let currentWeather = new CurrentWeather();
container.querySelector('.show-box').appendChild(currentWeather.container);
let forecastWeather = new ForecastWeather();
container.querySelector('.show-box').appendChild(forecastWeather.container);
let search = new Search(logo, currentWeather, forecastWeather);
container.querySelector('.app').appendChild(search.container);
let errorPage = new ErrorPage();
container.querySelector('.show-box').appendChild(errorPage.container);
}
}
module.exports = App;
|
Make sure print frame is hidden |
function file_editor()
{
this.editable = true;
this.printable = true;
this.init = function(ed, mode, href)
{
this.href = href;
this.editor = ace.edit(ed);
this.session = this.editor.getSession();
this.editor.focus();
this.editor.setReadOnly(true);
this.session.setMode('ace/mode/' + mode);
};
// switch editor into read-write mode
this.enable = function()
{
this.editor.setReadOnly(false);
};
// switch editor into read-only mode
this.disable = function()
{
this.editor.setReadOnly(true);
};
this.getContent = function()
{
return this.editor.getValue();
};
// print file content
this.print = function()
{
// There's no print function in Ace Editor
// it's also not possible to print the page as is
// we'd copy the content to a hidden iframe
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = function() { iframe.focus(); iframe.contentWindow.print(); };
iframe.src = this.href + '&force-type=text/plain';
document.body.appendChild(iframe);
};
}
|
function file_editor()
{
this.editable = true;
this.printable = true;
this.init = function(ed, mode, href)
{
this.href = href;
this.editor = ace.edit(ed);
this.session = this.editor.getSession();
this.editor.focus();
this.editor.setReadOnly(true);
this.session.setMode('ace/mode/' + mode);
};
// switch editor into read-write mode
this.enable = function()
{
this.editor.setReadOnly(false);
};
// switch editor into read-only mode
this.disable = function()
{
this.editor.setReadOnly(true);
};
this.getContent = function()
{
return this.editor.getValue();
};
// print file content
this.print = function()
{
// There's no print function in Ace Editor
// it's also not possible to print the page as is
// we'd copy the content to a hidden iframe
var iframe = document.createElement('iframe');
iframe.onload = function() { iframe.focus(); iframe.contentWindow.print(); };
iframe.src = this.href + '&force-type=text/plain';
document.body.appendChild(iframe);
};
}
|
Enable extending classes to access fields. | /**
* Copyright (C) 2009-2017 Simonsoft Nordic AB
*
* 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 se.simonsoft.cms.item.command;
import se.simonsoft.cms.item.CmsItemId;
public class ExternalCommand {
protected CmsItemId itemId;
protected String action;
protected String jsonargs = null;
public ExternalCommand(CmsItemId itemId, String action, String jsonArgs) {
this.itemId = itemId;
this.action = action;
this.jsonargs = jsonArgs;
}
public String getAction() {
return action;
}
public CmsItemId getItemId() {
return itemId;
}
public <T> T getArgs(Class<T> argumentsWrapperClass) {
// TODO: Parse jsonargs into the requested type.
return null;
}
}
| /**
* Copyright (C) 2009-2017 Simonsoft Nordic AB
*
* 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 se.simonsoft.cms.item.command;
import se.simonsoft.cms.item.CmsItemId;
public class ExternalCommand {
private CmsItemId itemId;
private String action;
private String jsonargs = null;
public ExternalCommand(CmsItemId itemId, String action, String jsonArgs) {
this.itemId = itemId;
this.action = action;
this.jsonargs = jsonArgs;
}
public String getAction() {
return action;
}
public CmsItemId getItemId() {
return itemId;
}
public <T> T getArgs(Class<T> argumentsWrapperClass) {
// TODO: Parse jsonargs into the requested type.
return null;
}
}
|
Test script to work out the method for creating tasks | """
Copyright 2016 EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from pycompss.api.parameter import *
from pycompss.api.task import task
def main(x):
from pycompss.api.api import compss_wait_on
print "Main process:"
results = []
for i in x:
results.append(print_time(i))
results = compss_wait_on(results)
print results
@task(x = IN, returns = int)
def print_time(x):
import time
x = time.time()
return x
if __name__ == "__main__":
y = range(10)
main(y)
| """
Copyright 2016 EMBL-European Bioinformatics Institute
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 argparse, time
from pycompss.api.task import task
from pycompss.api.parameter import *
#class process_test:
#
# def __init__(self):
# self.ready = True
@task(x = IN)
def main(x):
print time.time(), x
y = range(1)
#pt = process_test()
map(main, y)
|
Add ContentKeywordRouter to vumi.dispatchers API. | """The vumi.dispatchers API."""
__all__ = ["BaseDispatchWorker", "BaseDispatchRouter", "SimpleDispatchRouter",
"TransportToTransportRouter", "ToAddrRouter",
"FromAddrMultiplexRouter", "UserGroupingRouter",
"ContentKeywordRouter"]
from vumi.dispatchers.base import (BaseDispatchWorker, BaseDispatchRouter,
SimpleDispatchRouter,
TransportToTransportRouter, ToAddrRouter,
FromAddrMultiplexRouter,
UserGroupingRouter, ContentKeywordRouter)
| """The vumi.dispatchers API."""
__all__ = ["BaseDispatchWorker", "BaseDispatchRouter", "SimpleDispatchRouter",
"TransportToTransportRouter", "ToAddrRouter",
"FromAddrMultiplexRouter", "UserGroupingRouter"]
from vumi.dispatchers.base import (BaseDispatchWorker, BaseDispatchRouter,
SimpleDispatchRouter,
TransportToTransportRouter, ToAddrRouter,
FromAddrMultiplexRouter,
UserGroupingRouter)
|
Support for log_delay for all tasks | import logging
import time
class BaseTask(object):
TASK_API_VERSION = 1
def __init__(self, bot, config):
"""
:param bot:
:type bot: pokemongo_bot.PokemonGoBot
:param config:
:return:
"""
self.bot = bot
self.config = config
self._validate_work_exists()
self.logger = logging.getLogger(type(self).__name__)
self.enabled = config.get('enabled', True)
self.last_log_time = time.time()
self.initialize()
def _validate_work_exists(self):
method = getattr(self, 'work', None)
if not method or not callable(method):
raise NotImplementedError('Missing "work" method')
def emit_event(self, event, sender=None, level='info', formatted='', data={}):
if not sender:
sender=self
# Print log only if X seconds are passed from last log
if (time.time() - self.last_log_time) > self.config.get('log_delay', 0):
self.last_log_time = time.time()
self.bot.event_manager.emit(
event,
sender=sender,
level=level,
formatted=formatted,
data=data
)
def initialize(self):
pass
| import logging
class BaseTask(object):
TASK_API_VERSION = 1
def __init__(self, bot, config):
"""
:param bot:
:type bot: pokemongo_bot.PokemonGoBot
:param config:
:return:
"""
self.bot = bot
self.config = config
self._validate_work_exists()
self.logger = logging.getLogger(type(self).__name__)
self.enabled = config.get('enabled', True)
self.initialize()
def _validate_work_exists(self):
method = getattr(self, 'work', None)
if not method or not callable(method):
raise NotImplementedError('Missing "work" method')
def emit_event(self, event, sender=None, level='info', formatted='', data={}):
if not sender:
sender=self
self.bot.event_manager.emit(
event,
sender=sender,
level=level,
formatted=formatted,
data=data
)
def initialize(self):
pass
|
Update nooitaf:colors dependency to 1.1.2_1 | Package.describe({
name: 'konecty:methods-middleware',
summary: 'Add more power to Meteor.methods with methods-middleware',
version: '1.2.1',
git: 'https://github.com/Konecty/methods-middleware.git'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use('coffeescript');
api.use('underscore');
api.use('nooitaf:colors@1.1.2_1');
api.addFiles('konecty:methods-middleware.coffee', ['server']);
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('konecty:methods-middleware');
api.use('coffeescript');
api.use('nooitaf:colors@0.0.2');
api.addFiles('konecty:methods-middleware-tests.coffee');
});
| Package.describe({
name: 'konecty:methods-middleware',
summary: 'Add more power to Meteor.methods with methods-middleware',
version: '1.2.0',
git: 'https://github.com/Konecty/methods-middleware.git'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use('coffeescript');
api.use('underscore');
api.use('nooitaf:colors@0.0.2');
api.addFiles('konecty:methods-middleware.coffee', ['server']);
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('konecty:methods-middleware');
api.use('coffeescript');
api.use('nooitaf:colors@0.0.2');
api.addFiles('konecty:methods-middleware-tests.coffee');
});
|
Update tests for new API routes | import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"template_key": "iw", "text_lines": ["test", "deployment"]}
response = requests.post(f"{url}/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
| import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/api/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
Send message only to one device if its alias was specified. | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids(alias):
devices = Device.objects.filter(active=True)
if alias:
devices = devices.filter(alias=alias)
reg_ids = [device.registration_id for device in devices]
return reg_ids
def send(data, collapse_key=None, to=None):
reg_ids = get_reg_ids(to)
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)
def send_message(title, body, alias=None):
data = {
'type': 'message',
'title': title,
'text': body
}
send(data, to=alias) | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)
def send_message(title, body):
data = {
'type': 'message',
'title': title,
'text': body
}
send(data) |
Enable searching the company id | var express = require('express');
var router = express.Router();
var HttpError = require('./errors').HttpError;
/*
* GET /
* [page = 0]
* [key = ""]: on empty, it will search all company
* Show 25 results per page
*/
router.get('/search', function(req, res, next) {
var search = req.query.key || "";
var page = req.query.page || 0;
var q;
if (search == "") {
q = {};
} else {
q = {
$or: [
{name: new RegExp("^" + search)},
{id: search},
]
};
}
var collection = req.db.collection('companies');
collection.find(q).skip(25 * page).limit(25).toArray().then(function(results) {
res.send(results);
}).catch(function(err) {
next(new HttpError("Internal Server Error", 500));
});
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var HttpError = require('./errors').HttpError;
/*
* GET /
* [page = 0]
* [key = ""]: on empty, it will search all company
* Show 25 results per page
*/
router.get('/search', function(req, res, next) {
var search = req.query.key || "";
var page = req.query.page || 0;
var q;
if (search == "") {
q = {};
} else {
q = {name: new RegExp("^" + search)};
}
var collection = req.db.collection('companies');
collection.find(q).skip(25 * page).limit(25).toArray().then(function(results) {
res.send(results);
}).catch(function(err) {
next(new HttpError("Internal Server Error", 500));
});
});
module.exports = router;
|
Fix blade extension for 5.4 | <?php
namespace Pyaesone17\ActiveState;
use Illuminate\Support\ServiceProvider;
class ActiveStateServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
\Blade::directive('activeCheck', function($expression) {
return "<?php echo Active::check($expression) ; ?>";
});
\Blade::directive('ifActiveUrl', function($expression) {
return "<?php if(Active::checkBoolean($expression)): ?>";
});
\Blade::directive('endIfActiveUrl', function($expression) {
return '<?php endif; ?>';
});
$this->publishes([
__DIR__.'/config/active.php' => config_path('active.php'),
], 'config');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('active-state', function ($app) {
return new \Pyaesone17\ActiveState\Active();
});
$this->mergeConfigFrom(
__DIR__.'/config/active.php', 'active'
);
}
}
| <?php
namespace Pyaesone17\ActiveState;
use Illuminate\Support\ServiceProvider;
class ActiveStateServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
\Blade::directive('activeCheck', function($expression) {
return "<?php echo Active::check{$expression} ; ?>";
});
\Blade::directive('ifActiveUrl', function($expression) {
return "<?php if(Active::checkBoolean{$expression}): ?>";
});
\Blade::directive('endIfActiveUrl', function($expression) {
return '<?php endif; ?>';
});
$this->publishes([
__DIR__.'/config/active.php' => config_path('active.php'),
], 'config');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('active-state', function ($app) {
return new \Pyaesone17\ActiveState\Active();
});
$this->mergeConfigFrom(
__DIR__.'/config/active.php', 'active'
);
}
}
|
Replace deprecated share() method for Laravel 5.4 compatibility | <?php
namespace Larapi;
use Illuminate\Support\ServiceProvider;
class LarapiServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bind('larapi', function ($app) {
return new Larapi;
});
$this->app->booting(function(){
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Larapi', 'Larapi\Facades\Larapi');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('larapi');
}
}
| <?php
namespace Larapi;
use Illuminate\Support\ServiceProvider;
class LarapiServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['larapi'] = $this->app->share(function($app){
return new Larapi;
});
$this->app->booting(function(){
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Larapi', 'Larapi\Facades\Larapi');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('larapi');
}
} |
Set default light intensity to 1.0 | /** Default scene sets is a scene that has automatically created camera node. */
var DefaultScene=Scene.extend({
init: function() {
this._super();
// Create default camera node and add camera component to it
this.root.name="Root";
this.cameraNode=new Node("Camera");
this.cameraComponent=this.cameraNode.addComponent(new PerspectiveCamera());
this.cameraComponent.aspect=false; // Forces PerspectiveCamera to autodetect aspect ratio
this.camera=this.cameraComponent.camera; ///< Main camera used for rendering scene. Beware! This is not camera component meaning that its view matrix gets overwritten by camera component each frame
this.root.addNode(this.cameraNode);
this.lightNode=new Node("Light");
this.light=new Light();
this.light.color= new Color(1, 1, 1, 1);
this.light.intensity = 1.0;
this.light.setLightDirection(vec3.fromValues(0.9, 1.0, 0.9));
this.lightNode.addComponent(this.light);
this.root.addNode(this.lightNode);
}
}); | /** Default scene sets is a scene that has automatically created camera node. */
var DefaultScene=Scene.extend({
init: function() {
this._super();
// Create default camera node and add camera component to it
this.root.name="Root";
this.cameraNode=new Node("Camera");
this.cameraComponent=this.cameraNode.addComponent(new PerspectiveCamera());
this.cameraComponent.aspect=false; // Forces PerspectiveCamera to autodetect aspect ratio
this.camera=this.cameraComponent.camera; ///< Main camera used for rendering scene. Beware! This is not camera component meaning that its view matrix gets overwritten by camera component each frame
this.root.addNode(this.cameraNode);
this.lightNode=new Node("Light");
this.light=new Light();
this.light.color= new Color(1, 1, 0.98, 1);
this.light.intensity = 1.15;
this.light.setLightDirection(vec3.fromValues(0.9, 1.0, 0.9));
this.lightNode.addComponent(this.light);
this.root.addNode(this.lightNode);
}
}); |
Add eslint-plugin-html to config file | module.exports = {
plugins: [
'html'
],
'env': {
'commonjs': true,
'es6': true,
'node': true,
'browser': true,
'jest': true,
'mocha': true,
'jasmine': true,
},
'extends': 'eslint:recommended',
'parser': 'babel-eslint',
'parserOptions': {
'sourceType': 'module'
},
'rules': {
'no-console': 0,
'max-len': ['error', 80],
'no-unused-vars': ['error', {
'argsIgnorePattern': '^_',
'varsIgnorePattern': '^_'
}],
quotes: ['error', 'single', {
allowTemplateLiterals: true,
}],
}
};
| module.exports = {
'env': {
'commonjs': true,
'es6': true,
'node': true,
'browser': true,
'jest': true,
'mocha': true,
'jasmine': true,
},
'extends': 'eslint:recommended',
'parser': 'babel-eslint',
'parserOptions': {
'sourceType': 'module'
},
'rules': {
'no-console': 0,
'max-len': ['error', 80],
'no-unused-vars': ['error', {
'argsIgnorePattern': '^_',
'varsIgnorePattern': '^_'
}],
quotes: ['error', 'single', {
allowTemplateLiterals: true,
}],
}
};
|
Fix usage of new LaunchScreen API in Todos | Router.configure({
// we use the appBody template to define the layout for the entire app
layoutTemplate: 'appBody',
// the appNotFound template is used for unknown routes and missing lists
notFoundTemplate: 'appNotFound',
// show the appLoading template whilst the subscriptions below load their data
loadingTemplate: 'appLoading',
// wait on the following subscriptions before rendering the page to ensure
// the data it's expecting is present
waitOn: function() {
return [
Meteor.subscribe('publicLists'),
Meteor.subscribe('privateLists')
];
}
});
if (Meteor.isClient) {
var launchScreenHandler = LaunchScreen.hold();
}
Router.map(function() {
this.route('join');
this.route('signin');
this.route('listsShow', {
path: '/lists/:_id',
// subscribe to todos before the page is rendered but don't wait on the
// subscription, we'll just render the items as they arrive
onBeforeAction: function () {
this.todosHandle = Meteor.subscribe('todos', this.params._id);
},
data: function () {
return Lists.findOne(this.params._id);
},
action: function () {
this.render();
launchScreenHandler.release();
}
});
this.route('home', {
path: '/',
action: function() {
Router.go('listsShow', Lists.findOne());
}
});
});
if (Meteor.isClient) {
Router.onBeforeAction('loading', {except: ['join', 'signin']});
Router.onBeforeAction('dataNotFound', {except: ['join', 'signin']});
}
| Router.configure({
// we use the appBody template to define the layout for the entire app
layoutTemplate: 'appBody',
// the appNotFound template is used for unknown routes and missing lists
notFoundTemplate: 'appNotFound',
// show the appLoading template whilst the subscriptions below load their data
loadingTemplate: 'appLoading',
// wait on the following subscriptions before rendering the page to ensure
// the data it's expecting is present
waitOn: function() {
return [
Meteor.subscribe('publicLists'),
Meteor.subscribe('privateLists')
];
}
});
if (Meteor.isClient)
LaunchScreen.hold();
Router.map(function() {
this.route('join');
this.route('signin');
this.route('listsShow', {
path: '/lists/:_id',
// subscribe to todos before the page is rendered but don't wait on the
// subscription, we'll just render the items as they arrive
onBeforeAction: function () {
this.todosHandle = Meteor.subscribe('todos', this.params._id);
},
data: function () {
return Lists.findOne(this.params._id);
},
action: function () {
this.render();
LaunchScreen.release();
}
});
this.route('home', {
path: '/',
action: function() {
Router.go('listsShow', Lists.findOne());
}
});
});
if (Meteor.isClient) {
Router.onBeforeAction('loading', {except: ['join', 'signin']});
Router.onBeforeAction('dataNotFound', {except: ['join', 'signin']});
}
|
Deployment: Add host to environment variables | const path = require('path'),
env = process.env.NODE_ENV || 'development';
require('dotenv').config({ silent: true });
const config = {
development: {
port: 5432,
db: {
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
options: {
host: process.env.DB_HOST,
dialect: 'postgres',
logging: false,
pool: {
max: 100,
min: 0,
idle: 10000
}
}
}
}
};
module.exports = config[env];
| const path = require('path'),
env = process.env.NODE_ENV || 'development';
require('dotenv').config({ silent: true });
const config = {
development: {
port: 5432,
db: {
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
options: {
host: '127.0.0.1',
dialect: 'postgres',
logging: false,
pool: {
max: 100,
min: 0,
idle: 10000
}
}
}
}
};
module.exports = config[env];
|
Add setting for heapdump folder and change default folder to the app folder (instead of plugin) | 'use strict';
// Load modules
var Path = require('path');
var HeapDump = require('heapdump');
var Hoek = require('hoek');
var Utils = require('./utils');
// Declare internals
var internals = {
initialized: false,
defaults: {
logPath: Path.join(Path.dirname(process.mainModule.filename), 'poop.log'),
heapdumpFolder: Path.join(Path.dirname(process.mainModule.filename)),
writeStreamOptions: { flags: 'w' }
}
};
module.exports.register = function (server, options, next) {
var settings = Hoek.applyToDefaults(internals.defaults, options || {});
if (internals.initialized) {
return next();
}
internals.initialized = true;
process.once('uncaughtException', function (err) {
HeapDump.writeSnapshot(Path.join(settings.heapdumpFolder, Date.now() + '.heapsnapshot'));
Utils.log(err, {
logPath: settings.logPath,
writeStreamOptions: settings.writeStreamOptions
}, function () {
process.exit(1);
});
});
process.on('SIGUSR1', function () {
HeapDump.writeSnapshot(Path.join(settings.heapdumpFolder, Date.now() + '.heapsnapshot'));
});
return next();
};
module.exports.register.attributes = {
pkg: require('../package.json')
};
| 'use strict';
// Load modules
var Path = require('path');
var HeapDump = require('heapdump');
var Hoek = require('hoek');
var Utils = require('./utils');
// Declare internals
var internals = {
initialized: false,
defaults: {
logPath: Path.join(__dirname, '..', 'poop.log'),
writeStreamOptions: { flags: 'w' }
}
};
module.exports.register = function (server, options, next) {
var settings = Hoek.applyToDefaults(internals.defaults, options || {});
if (internals.initialized) {
return next();
}
internals.initialized = true;
process.once('uncaughtException', function (err) {
HeapDump.writeSnapshot();
Utils.log(err, {
logPath: settings.logPath,
writeStreamOptions: settings.writeStreamOptions
}, function () {
process.exit(1);
});
});
process.on('SIGUSR1', function () {
HeapDump.writeSnapshot();
});
return next();
};
module.exports.register.attributes = {
pkg: require('../package.json')
};
|
[build] Add libbz2-dev dependency for PinPlay | #!/usr/bin/env python
import sys, os
# list of (packagename, filename)
DEPENDENCIES = [
('zlib1g-dev / zlib-devel', '/usr/include/zlib.h'),
('libbz2-dev / bzip2-devel', '/usr/include/bzlib.h'),
('g++ / gcc-c++', '/usr/bin/g++'),
('wget', '/usr/bin/wget'),
('libsqlite3-dev / sqlite-devel', '/usr/include/sqlite3.h'),
]
if os.environ.get('BOOST_INCLUDE', ''):
DEPENDENCIES += [
('boost headers to %s' % os.environ['BOOST_INCLUDE'], '%(BOOST_INCLUDE)s/boost/lexical_cast.hpp' % os.environ),
]
else:
DEPENDENCIES += [
('libboost-dev / boost-devel', '/usr/include/boost/lexical_cast.hpp'),
]
ALTERNATIVES = [
('/usr/lib', '/usr/lib/x86_64-linux-gnu'),
('/usr/lib', '/usr/lib64'),
]
missing = False
def find_file(filename):
if os.path.exists(filename):
return True
for pattern, replacement in ALTERNATIVES:
if os.path.exists(filename.replace(pattern, replacement)):
return True
return False
for package, filename in DEPENDENCIES:
if not find_file(filename):
print '*** Please install package %s' % package
missing = True
if missing:
sys.exit(1)
else:
sys.exit(0)
| #!/usr/bin/env python
import sys, os
# list of (packagename, filename)
DEPENDENCIES = [
('zlib1g-dev / zlib-devel', '/usr/include/zlib.h'),
('g++ / gcc-c++', '/usr/bin/g++'),
('wget', '/usr/bin/wget'),
('libsqlite3-dev / sqlite-devel', '/usr/include/sqlite3.h'),
]
if os.environ.get('BOOST_INCLUDE', ''):
DEPENDENCIES += [
('boost headers to %s' % os.environ['BOOST_INCLUDE'], '%(BOOST_INCLUDE)s/boost/lexical_cast.hpp' % os.environ),
]
else:
DEPENDENCIES += [
('libboost-dev / boost-devel', '/usr/include/boost/lexical_cast.hpp'),
]
ALTERNATIVES = [
('/usr/lib', '/usr/lib/x86_64-linux-gnu'),
('/usr/lib', '/usr/lib64'),
]
missing = False
def find_file(filename):
if os.path.exists(filename):
return True
for pattern, replacement in ALTERNATIVES:
if os.path.exists(filename.replace(pattern, replacement)):
return True
return False
for package, filename in DEPENDENCIES:
if not find_file(filename):
print '*** Please install package %s' % package
missing = True
if missing:
sys.exit(1)
else:
sys.exit(0)
|
Make the fields private and make the ctor protected (need a create
method) | package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;
public class BlockDeferredRegister {
private final DeferredRegister<Block> blocks;
protected BlockDeferredRegister(String modid) {
blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
}
public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
final RegistryObject<B> block = blocks.register(name, supplier);
final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);
return new BlockRegistryObject<B, I>(block, item);
}
public void register(IEventBus bus) {
blocks.register(bus);
}
}
| package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;
public class BlockDeferredRegister {
public final DeferredRegister<Block> blocks;
public BlockDeferredRegister(String modid) {
blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
}
public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
final RegistryObject<B> block = blocks.register(name, supplier);
final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);
return new BlockRegistryObject<B, I>(block, item);
}
public void register(IEventBus bus) {
blocks.register(bus);
}
}
|
Use more accurate name for clarity in measuring | package com.flipboard.bottomsheet.commons;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* An ImageView that keeps a 1:1 aspect ratio
*/
final class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@SuppressWarnings("UnnecessaryLocalVariable")
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int bothDimensionsSpec = widthMeasureSpec;
super.onMeasure(bothDimensionsSpec, bothDimensionsSpec);
}
}
| package com.flipboard.bottomsheet.commons;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* An ImageView that keeps a 1:1 aspect ratio
*/
final class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@SuppressWarnings("SuspiciousNameCombination")
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
|
Rename sendTileEntityUpdatePacket to something more fitting | /*
* Copyright 2014 Lukas Tenbrink
*
* 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 ivorius.ivtoolkit.network;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraft.tileentity.TileEntity;
/**
* Created by lukas on 25.09.14.
*/
public class IvNetworkHelperClient
{
@Deprecated
public static <ETileEntity extends TileEntity & ClientEventHandler> void sendTileEntityUpdatePacket(ETileEntity tileEntity, String context, SimpleNetworkWrapper network, Object... params)
{
sendTileEntityEventPacket(tileEntity, context, network, params);
}
public static <ETileEntity extends TileEntity & ClientEventHandler> void sendTileEntityEventPacket(ETileEntity tileEntity, String context, SimpleNetworkWrapper network, Object... params)
{
if (!(tileEntity.getWorldObj().isRemote))
throw new UnsupportedOperationException();
network.sendToServer(PacketTileEntityClientEvent.packetEntityData(tileEntity, context, params));
}
}
| /*
* Copyright 2014 Lukas Tenbrink
*
* 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 ivorius.ivtoolkit.network;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraft.tileentity.TileEntity;
/**
* Created by lukas on 25.09.14.
*/
public class IvNetworkHelperClient
{
public static <ETileEntity extends TileEntity & ClientEventHandler> void sendTileEntityUpdatePacket(ETileEntity tileEntity, String context, SimpleNetworkWrapper network, Object... params)
{
if (!(tileEntity.getWorldObj().isRemote))
throw new UnsupportedOperationException();
network.sendToServer(PacketTileEntityClientEvent.packetEntityData(tileEntity, context, params));
}
}
|
Fix minor issue in remote push
We need to open the file and then parse it as json | import json,httplib
config_data = json.load(open('conf/net/ext_service/parse.json'))
silent_push_msg = {
"where": {
"deviceType": "ios"
},
"data": {
# "alert": "The Mets scored! The game is now tied 1-1.",
"content-available": 1,
"sound": "",
}
}
parse_headers = {
"X-Parse-Application-Id": config_data["emission_id"],
"X-Parse-REST-API-Key": config_data["emission_key"],
"Content-Type": "application/json"
}
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/push', json.dumps(silent_push_msg), parse_headers)
result = json.loads(connection.getresponse().read())
print result
| import json,httplib
config_file = open('conf/net/ext_service/parse.json')
silent_push_msg = {
"where": {
"deviceType": "ios"
},
"data": {
# "alert": "The Mets scored! The game is now tied 1-1.",
"content-available": 1,
"sound": "",
}
}
parse_headers = {
"X-Parse-Application-Id": config_file["emission_id"],
"X-Parse-REST-API-Key": config_file["emission_key"],
"Content-Type": "application/json"
}
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/push', json.dumps(silent_push_msg), parse_headers)
result = json.loads(connection.getresponse().read())
print result
|
Change entrypoint name from 'progressiveCactus' to 'cactus' | from setuptools import setup, find_packages
import os
import subprocess
os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil")
versionFile = "src/cactus/shared/version.py"
if os.path.exists(versionFile):
os.remove(versionFile)
git_commit = subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0]
with open(versionFile, 'w') as versionFH:
versionFH.write("cactus_commit = '%s'" % git_commit)
setup(
name="progressiveCactus",
version="1.0",
author="Benedict Paten",
package_dir = {'': 'src'},
packages=find_packages(where='src'),
include_package_data=True,
package_data={'cactus': ['*_config.xml']},
# We use the __file__ attribute so this package isn't zip_safe.
zip_safe=False,
install_requires=[
'subprocess32',
'psutil',
'networkx'],
entry_points={
'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
| from setuptools import setup, find_packages
import os
import subprocess
os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil")
versionFile = "src/cactus/shared/version.py"
if os.path.exists(versionFile):
os.remove(versionFile)
git_commit = subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0]
with open(versionFile, 'w') as versionFH:
versionFH.write("cactus_commit = '%s'" % git_commit)
setup(
name="progressiveCactus",
version="1.0",
author="Benedict Paten",
package_dir = {'': 'src'},
packages=find_packages(where='src'),
include_package_data=True,
package_data={'cactus': ['*_config.xml']},
# We use the __file__ attribute so this package isn't zip_safe.
zip_safe=False,
install_requires=[
'subprocess32',
'psutil',
'networkx'],
entry_points={
'console_scripts': ['progressiveCactus = cactus.progressive.cactus_progressive:main']},)
|
Remove requirement to use Illuminate\Support\Fluent
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Foundation\Services\Validation;
use Orchestra\Support\Validator;
class UserAccount extends Validator {
/**
* List of rules.
*
* @var array
*/
protected $rules = array(
'email' => array('required', 'email'),
'fullname' => array('required'),
);
/**
* List of events.
*
* @var array
*/
protected $events = array(
'orchestra.validate: user.account',
);
/**
* On register scenario.
*
* @access protected
* @return void
*/
protected function onRegister()
{
$this->rules['email'] = array('required', 'email', 'unique:users,email');
}
/**
* On update password scenario.
*
* @access protected
* @return void
*/
protected function onChangePassword()
{
$this->setRules(array(
'current_password' => array('required'),
'new_password' => array('required', 'different:current_password'),
'confirm_password' => array('same:new_password'),
));
$this->events = array();
}
}
| <?php namespace Orchestra\Foundation\Services\Validation;
use Illuminate\Support\Fluent;
use Orchestra\Support\Validator;
class UserAccount extends Validator {
/**
* List of rules.
*
* @var array
*/
protected $rules = array(
'email' => array('required', 'email'),
'fullname' => array('required'),
);
/**
* List of events.
*
* @var array
*/
protected $events = array(
'orchestra.validate: user.account',
);
/**
* On register scenario.
*
* @access protected
* @return void
*/
protected function onRegister()
{
$this->rules['email'] = array('required', 'email', 'unique:users,email');
}
/**
* On update password scenario.
*
* @access protected
* @return void
*/
protected function onChangePassword()
{
$this->setRules(array(
'current_password' => array('required'),
'new_password' => array('required', 'different:current_password'),
'confirm_password' => array('same:new_password'),
));
$this->events = array();
}
}
|
Add --extensions-in-dev-mode to the Binder dev mode | lab_command = ' '.join([
'jupyter',
'lab',
'--dev-mode',
'--debug',
'--extensions-in-dev-mode',
'--no-browser',
'--port={port}',
'--ServerApp.ip=127.0.0.1',
'--ServerApp.token=""',
'--ServerApp.base_url={base_url}lab-dev',
# Disable dns rebinding protection here, since our 'Host' header
# is not going to be localhost when coming from hub.mybinder.org
'--ServerApp.allow_remote_access=True'
])
c.ServerProxy.servers = {
'lab-dev': {
'command': [
'/bin/bash', '-c',
# Redirect all logs to a log file
f'{lab_command} >jupyterlab-dev.log 2>&1'
],
'timeout': 60,
'absolute_url': True
}
}
c.NotebookApp.default_url = '/lab-dev'
import logging
c.NotebookApp.log_level = logging.DEBUG
| lab_command = ' '.join([
'jupyter',
'lab',
'--dev-mode',
'--debug',
'--no-browser',
'--port={port}',
'--ServerApp.ip=127.0.0.1',
'--ServerApp.token=""',
'--ServerApp.base_url={base_url}lab-dev',
# Disable dns rebinding protection here, since our 'Host' header
# is not going to be localhost when coming from hub.mybinder.org
'--ServerApp.allow_remote_access=True'
])
c.ServerProxy.servers = {
'lab-dev': {
'command': [
'/bin/bash', '-c',
# Redirect all logs to a log file
f'{lab_command} >jupyterlab-dev.log 2>&1'
],
'timeout': 60,
'absolute_url': True
}
}
c.NotebookApp.default_url = '/lab-dev'
import logging
c.NotebookApp.log_level = logging.DEBUG
|
Stop double-calling the callback function | var Person = require('./person');
function incomingMessage(botId, message) {
return message.type === 'message' // check it's a message
&& Boolean(message.text) // check message has some content
&& Boolean(message.user) // check there is a user set
&& message.user !== botId; // check message is not from this bot
}
function directMessage(message) {
// check it's a direct message - direct message channels start with 'D'
return typeof message.channel === 'string' && message.channel[0] === 'D';
}
function channelMessageForMe(botId, message) {
return typeof message.channel === 'string' // check it's a string
&& message.channel[0] === 'C' // channel messages start with 'C'
&& message.text.startsWith('<@' + botId + '>:'); // check it's for me
}
function createResponse(message, callback) {
if (message.text.startsWith('person')) {
var person = new Person(message.text.substring(7));
person.getDetails(callback);
} else {
// if nothing else, just echo back the message
callback('Echo: ' + message.text);
}
}
module.exports = {
incomingMessage: incomingMessage,
directMessage: directMessage,
channelMessageForMe: channelMessageForMe,
createResponse: createResponse
};
| var Person = require('./person');
function incomingMessage(botId, message) {
return message.type === 'message' // check it's a message
&& Boolean(message.text) // check message has some content
&& Boolean(message.user) // check there is a user set
&& message.user !== botId; // check message is not from this bot
}
function directMessage(message) {
// check it's a direct message - direct message channels start with 'D'
return typeof message.channel === 'string' && message.channel[0] === 'D';
}
function channelMessageForMe(botId, message) {
return typeof message.channel === 'string' // check it's a string
&& message.channel[0] === 'C' // channel messages start with 'C'
&& message.text.startsWith('<@' + botId + '>:'); // check it's for me
}
function createResponse(message, callback) {
var response = 'Echo: ' + message.text;
if (message.text.startsWith('person')) {
var person = new Person(message.text.substring(7));
person.getDetails(callback);
}
callback(response);
}
module.exports = {
incomingMessage: incomingMessage,
directMessage: directMessage,
channelMessageForMe: channelMessageForMe,
createResponse: createResponse
};
|
Add pep8 as a build dependency. | #!/usr/bin/env python
from setuptools import setup, find_packages
PROJECT = 'overalls'
VERSION = '0.1'
AUTHOR = 'Simon Cross'
AUTHOR_EMAIL = 'hodgestar@gmail.com'
DESC = "Coveralls coverage uploader."
setup(
name=PROJECT,
version=VERSION,
description=DESC,
long_description=open('README.rst').read(),
author=AUTHOR,
author_email=AUTHOR_EMAIL,
packages=find_packages(),
scripts=[
'scripts/overalls',
],
requires=[
'requests',
],
build_requires=[
'pep8',
'pytest',
'pytest-cov',
'pytest-pep8',
'mock',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
PROJECT = 'overalls'
VERSION = '0.1'
AUTHOR = 'Simon Cross'
AUTHOR_EMAIL = 'hodgestar@gmail.com'
DESC = "Coveralls coverage uploader."
setup(
name=PROJECT,
version=VERSION,
description=DESC,
long_description=open('README.rst').read(),
author=AUTHOR,
author_email=AUTHOR_EMAIL,
packages=find_packages(),
scripts=[
'scripts/overalls',
],
requires=[
'requests',
],
build_requires=[
'pytest',
'pytest-cov',
'pytest-pep8',
'mock',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
],
)
|
Remove old transport forcing code from the basic auth test | <?php
class RequestsTest_Auth_Basic extends PHPUnit_Framework_TestCase {
public static function transportProvider() {
$transports = array(
array('Requests_Transport_fsockopen'),
array('Requests_Transport_cURL'),
);
return $transports;
}
/**
* @dataProvider transportProvider
*/
public function testUsingArray($transport) {
$options = array(
'auth' => array('user', 'passwd'),
'transport' => $transport,
);
$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
$this->assertEquals(200, $request->status_code);
$result = json_decode($request->body);
$this->assertEquals(true, $result->authenticated);
$this->assertEquals('user', $result->user);
}
/**
* @dataProvider transportProvider
*/
public function testUsingInstantiation($transport) {
$options = array(
'auth' => new Requests_Auth_Basic(array('user', 'passwd')),
'transport' => $transport,
);
$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
$this->assertEquals(200, $request->status_code);
$result = json_decode($request->body);
$this->assertEquals(true, $result->authenticated);
$this->assertEquals('user', $result->user);
}
} | <?php
Requests::$transport = 'Requests_Transport_fsockopen';
class RequestsTest_Auth_Basic extends PHPUnit_Framework_TestCase {
public static function transportProvider() {
$transports = array(
array('Requests_Transport_fsockopen'),
array('Requests_Transport_cURL'),
);
return $transports;
}
/**
* @dataProvider transportProvider
*/
public function testUsingArray($transport) {
$options = array(
'auth' => array('user', 'passwd'),
'transport' => $transport,
);
$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
$this->assertEquals(200, $request->status_code);
$result = json_decode($request->body);
$this->assertEquals(true, $result->authenticated);
$this->assertEquals('user', $result->user);
}
/**
* @dataProvider transportProvider
*/
public function testUsingInstantiation($transport) {
$options = array(
'auth' => new Requests_Auth_Basic(array('user', 'passwd')),
'transport' => $transport,
);
$request = Requests::get('http://httpbin.org/basic-auth/user/passwd', array(), $options);
$this->assertEquals(200, $request->status_code);
$result = json_decode($request->body);
$this->assertEquals(true, $result->authenticated);
$this->assertEquals('user', $result->user);
}
} |
Migrate to python 3, django 3.2 | from setuptools import setup, find_packages
setup(
name='gu-django-filebrowser-no-grappelli',
version='3.1.33',
description='Media-Management with the Django Admin-Interface. Without django-grappelli requirement.',
author='Patrick Kranzlmueller',
author_email='patrick@vonautomatisch.at',
url='https://github.com/hu-django/filebrowser-no-grappelli',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
| from setuptools import setup, find_packages
setup(
name='gu-django-filebrowser-no-grappelli',
version='3.1.32',
description='Media-Management with the Django Admin-Interface. Without django-grappelli requirement.',
author='Patrick Kranzlmueller',
author_email='patrick@vonautomatisch.at',
url='https://github.com/agushuley/gu-django-filebrowser-no-grappelli',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
Use a factory instead of creating an HTMLValidator inline. | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2',
name: 'HTMLValidator',
extends: 'foam.u2.DefaultValidator',
axioms: [ foam.pattern.Singleton.create() ],
methods: [
function sanitizeText(text) {
// TODO: validate text
return text;
}
]
});
// An Element which does not escape HTML content
foam.CLASS({
package: 'foam.u2',
name: 'HTMLElement',
extends: 'foam.u2.Element',
requires: [ 'foam.u2.HTMLValidator' ],
exports: [ 'validator as elementValidator' ],
properties: [
{
class: 'Proxy',
of: 'foam.u2.DefaultValidator',
name: 'validator',
factory: function() { return this.HTMLValidator.create() }
}
]
});
| /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2',
name: 'HTMLValidator',
extends: 'foam.u2.DefaultValidator',
axioms: [ foam.pattern.Singleton.create() ],
methods: [
function sanitizeText(text) {
// TODO: validate text
return text;
}
]
});
// An Element which does not escape HTML content
foam.CLASS({
package: 'foam.u2',
name: 'HTMLElement',
extends: 'foam.u2.Element',
exports: [ 'validator as elementValidator' ],
properties: [
{
class: 'Proxy',
of: 'foam.u2.DefaultValidator',
name: 'validator',
value: foam.u2.HTMLValidator.create()
}
]
});
|
fix: Use --disabled class for disabled switch | import {PlainViewModel} from './mdc-knockout-base'
export default class SwitchViewModel extends PlainViewModel {
extend () {
if (!this.attrs['id']) {
this.attrs['id'] = this.randomPrefixed('switch-auto-id');
}
}
defaultParams () {
return {
label: '',
disable: false
}
}
static template () {
return template;
}
}
const template =
`<div class="mdc-switch" data-bind="
css: {
'mdc-switch--disabled': disable
}
">
<input type="checkbox" class="mdc-switch__native-control" data-bind="
mdc-bindings: bindings,
attr: attrs,
disable: disable
" />
<div class="mdc-switch__background">
<div class="mdc-switch__knob"></div>
</div>
</div>
<label class="mdc-switch-label" data-bind="
attr: {
for: attrs.id
},
text: label
"></label>
`;
| import {PlainViewModel} from './mdc-knockout-base'
export default class SwitchViewModel extends PlainViewModel {
extend () {
if (!this.attrs['id']) {
this.attrs['id'] = this.randomPrefixed('switch-auto-id');
}
}
defaultParams () {
return {
label: ''
}
}
static template () {
return template;
}
}
const template =
`<div class="mdc-switch">
<input type="checkbox" class="mdc-switch__native-control" data-bind="
mdc-bindings: bindings,
attr: attrs
" />
<div class="mdc-switch__background">
<div class="mdc-switch__knob"></div>
</div>
</div>
<label class="mdc-switch-label" data-bind="
attr: {
for: attrs.id
},
text: label
"></label>
`;
|
Update lead adviser success message | const { find, get } = require('lodash')
const { Order } = require('../../../models')
async function editLeadAssignee (req, res, next) {
const adviserId = req.body.adviserId
const orderId = req.body.orderId
const returnUrl = req.body.returnUrl || req.header('Referer')
if (!adviserId || !orderId) {
return res.redirect(returnUrl)
}
try {
const allAssignees = await Order.getAssignees(req.session.token, orderId)
const assignees = allAssignees.map(assignee => {
return Object.assign(assignee, {
is_lead: assignee.adviser.id === adviserId,
})
})
const leadAdviser = find(assignees, { adviser: { id: adviserId } })
await Order.saveAssignees(req.session.token, orderId, assignees)
req.flash('success', `Lead adviser in the market set to ${get(leadAdviser, 'adviser.name')}`)
res.redirect(returnUrl)
} catch (error) {
next(error)
}
}
module.exports = editLeadAssignee
| const { find, get } = require('lodash')
const { Order } = require('../../../models')
async function editLeadAssignee (req, res, next) {
const adviserId = req.body.adviserId
const orderId = req.body.orderId
const returnUrl = req.body.returnUrl || req.header('Referer')
if (!adviserId || !orderId) {
return res.redirect(returnUrl)
}
try {
const allAssignees = await Order.getAssignees(req.session.token, orderId)
const assignees = allAssignees.map(assignee => {
return Object.assign(assignee, {
is_lead: assignee.adviser.id === adviserId,
})
})
const leadAdviser = find(assignees, { adviser: { id: adviserId } })
await Order.saveAssignees(req.session.token, orderId, assignees)
req.flash('success', `Lead post adviser set to ${get(leadAdviser, 'adviser.name')}`)
res.redirect(returnUrl)
} catch (error) {
next(error)
}
}
module.exports = editLeadAssignee
|
Use DI extension base class from DI component | <?php
namespace Yolo\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Extension\Extension;
class ServiceControllerExtension extends Extension
{
public function load(array $config, ContainerBuilder $container)
{
$container
->register('controller_resolver.service', 'Yolo\DependencyInjection\ServiceControllerResolver')
->setArguments([
new Reference('controller_resolver.decorated'),
new Reference('service_container'),
])
->addTag('controller_resolver.decorator', []);
}
}
| <?php
namespace Yolo\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class ServiceControllerExtension extends Extension
{
public function load(array $config, ContainerBuilder $container)
{
$container
->register('controller_resolver.service', 'Yolo\DependencyInjection\ServiceControllerResolver')
->setArguments([
new Reference('controller_resolver.decorated'),
new Reference('service_container'),
])
->addTag('controller_resolver.decorator', []);
}
}
|
Update exception msg and add suiteName hint | package de.retest.recheck.persistence;
import de.retest.recheck.TestCaseFinder;
/**
* The default implementation that derives test suite and test case name from the test class and test method, working
* for both JUnit and TestNG.
*/
public class ClassAndMethodBasedNamingStrategy implements NamingStrategy {
@Override
public String getSuiteName() {
return TestCaseFinder.getInstance() //
.findTestCaseClassNameInStack() //
.orElseThrow( () -> new IllegalStateException( "Couldn't identify test class in call stack.\n"
+ "This is needed to dynamically name the Golden Master files.\n "
+ "Please call `suiteName(\"name\")` in RecheckImpl with RecheckOptions, giving an explicit name, "
+ "or instantiate it in a method, and provide a different NamingStrategy." ) );
}
@Override
public String getTestName() {
return TestCaseFinder.getInstance() //
.findTestCaseMethodNameInStack() //
.orElseThrow( () -> new IllegalStateException( "Couldn't identify test method in call stack.\n"
+ "This is needed to dynamically name the Golden Master files.\n"
+ "Please call `startTest(\"name\")`, giving an explicit name, "
+ "or instantiate RecheckImpl with RecheckOptions, and provide a different NamingStrategy." ) );
}
}
| package de.retest.recheck.persistence;
import de.retest.recheck.TestCaseFinder;
/**
* The default implementation that derives test suite and test case name from the test class and test method, working
* for both JUnit and TestNG.
*/
public class ClassAndMethodBasedNamingStrategy implements NamingStrategy {
@Override
public String getSuiteName() {
return TestCaseFinder.getInstance() //
.findTestCaseClassNameInStack() //
.orElseThrow( () -> new IllegalStateException( "Couldn't identify test class in call stack.\n"
+ "This is needed to dynamically name the Golden Master files.\n "
+ "Please instantiate RecheckImpl with RecheckOptions, and provide a different FileNamerStrategy." ) );
}
@Override
public String getTestName() {
return TestCaseFinder.getInstance() //
.findTestCaseMethodNameInStack() //
.orElseThrow( () -> new IllegalStateException( "Couldn't identify test method in call stack.\n"
+ "This is needed to dynamically name the Golden Master files.\n"
+ "Please call `startTest(\"name\")`, giving an explicit name, "
+ "or instantiate RecheckImpl with RecheckOptions, and provide a different FileNamerStrategy." ) );
}
}
|
Add return type for abstract style id getter | <?php
/**
* Abstract Stylesheet
*
* @package GrottoPress\Jentil\Setups\Styles
* @since 0.6.0
*
* @author GrottoPress <info@grottopress.com>
* @author N Atta Kusi Adusei
*/
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Styles;
use GrottoPress\Jentil\Setups\AbstractSetup;
use GrottoPress\Getter\Getter;
/**
* Abstract Stylesheet
*
* @since 0.6.0
*/
abstract class AbstractStyle extends AbstractSetup
{
/**
* Handle
*
* @since 0.6.0
* @access protected
*
* @var string
*/
protected $id;
/**
* Get handle
*
* @since 0.6.0
* @access protected
*/
protected function getID(): string
{
return $this->id;
}
/**
* Run setup
*
* @since 0.6.0
* @access public
*/
public function run()
{
\add_action('wp_enqueue_scripts', [$this, 'enqueue']);
}
/**
* Enqueue/dequeue stylesheet
*
* @since 0.6.0
* @access public
*
* @action wp_enqueue_scripts
*/
abstract public function enqueue();
}
| <?php
/**
* Abstract Stylesheet
*
* @package GrottoPress\Jentil\Setups\Styles
* @since 0.6.0
*
* @author GrottoPress <info@grottopress.com>
* @author N Atta Kusi Adusei
*/
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Styles;
use GrottoPress\Jentil\Setups\AbstractSetup;
use GrottoPress\Getter\Getter;
/**
* Abstract Stylesheet
*
* @since 0.6.0
*/
abstract class AbstractStyle extends AbstractSetup
{
/**
* Handle
*
* @since 0.6.0
* @access protected
*
* @var string
*/
protected $id;
/**
* Get handle
*
* @since 0.6.0
* @access protected
*/
protected function getID()
{
return $this->id;
}
/**
* Run setup
*
* @since 0.6.0
* @access public
*/
public function run()
{
\add_action('wp_enqueue_scripts', [$this, 'enqueue']);
}
/**
* Enqueue/dequeue stylesheet
*
* @since 0.6.0
* @access public
*
* @action wp_enqueue_scripts
*/
abstract public function enqueue();
}
|
Exit if RCP_Member class doesn't exist. | <?php
/**
* Plugin Name: Restrict Content Pro - Restrict WooCommerce Shop Archive
* Description: Restricts access to the WooCommerce shop archive, using the settings specified in the "Restrict this Content" metabox.
* Version: 1.0
* Author: Restrict Content Pro team
* License: GPL2
*/
/**
* Restricts access to the WooCommerce shop archive according to the settings specified in the metabox.
* If the current user doesn't have access, they're redirected to the specified redirect URL in Restrict > Settings > Misc.
*
* @since 1.0
* @return void
*/
function ag_rcp_redirect_woocommerce_shop() {
if ( ! function_exists( 'is_shop' ) || ! is_shop() || ! class_exists( 'RCP_Member' ) ) {
return;
}
global $rcp_options;
$shop_page_id = wc_get_page_id( 'shop' );
$member = new RCP_Member( get_current_user_id() );
if ( $member->can_access( $shop_page_id ) ) {
return;
}
if( isset( $rcp_options['redirect_from_premium'] ) ) {
$redirect = get_permalink( $rcp_options['redirect_from_premium'] );
} else {
$redirect = home_url();
}
wp_redirect( $redirect ); exit;
}
add_action( 'template_redirect', 'ag_rcp_redirect_woocommerce_shop', 999 ); | <?php
/**
* Plugin Name: Restrict Content Pro - Restrict WooCommerce Shop Archive
* Description: Restricts access to the WooCommerce shop archive, using the settings specified in the "Restrict this Content" metabox.
* Version: 1.0
* Author: Restrict Content Pro team
* License: GPL2
*/
/**
* Restricts access to the WooCommerce shop archive according to the settings specified in the metabox.
* If the current user doesn't have access, they're redirected to the specified redirect URL in Restrict > Settings > Misc.
*
* @since 1.0
* @return void
*/
function ag_rcp_redirect_woocommerce_shop() {
if ( ! function_exists( 'is_shop' ) || ! is_shop() ) {
return;
}
global $rcp_options;
$shop_page_id = wc_get_page_id( 'shop' );
$member = new RCP_Member( get_current_user_id() );
if ( $member->can_access( $shop_page_id ) ) {
return;
}
if( isset( $rcp_options['redirect_from_premium'] ) ) {
$redirect = get_permalink( $rcp_options['redirect_from_premium'] );
} else {
$redirect = home_url();
}
wp_redirect( $redirect ); exit;
}
add_action( 'template_redirect', 'ag_rcp_redirect_woocommerce_shop', 999 ); |
Allow OTP creation without user ID | /*
* Copyright 2021 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.powerauth.lib.nextstep.model.response;
import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.OtpStatus;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* Response object used for creating an OTP.
*
* @author Roman Strobl, roman.strobl@wultra.com
*/
@Data
public class CreateOtpResponse {
@NotNull
private String otpName;
private String userId;
@NotNull
private String otpId;
@NotNull
private String otpValue;
@NotNull
private OtpStatus otpStatus;
}
| /*
* Copyright 2021 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.powerauth.lib.nextstep.model.response;
import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.OtpStatus;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* Response object used for creating an OTP.
*
* @author Roman Strobl, roman.strobl@wultra.com
*/
@Data
public class CreateOtpResponse {
@NotNull
private String otpName;
@NotNull
private String userId;
@NotNull
private String otpId;
@NotNull
private String otpValue;
@NotNull
private OtpStatus otpStatus;
}
|
Fix error in previous commit | package com.ui;
import com.ui.TelemetryListener;
import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.FontMetrics;
public class DataLabel extends JLabel implements TelemetryListener{
private String label;
private String suffix;
private double data;
private int maxWidth;
private void updateText(){
StringBuilder out = new StringBuilder();
out.append(label);
out.append((data >= 0)? " " : "-");
out.append(String.format("%f", Math.abs(data)));
out.append(suffix);
int finalWidth = Math.min(out.length(), maxWidth);
setText(out.substring(0,finalWidth));
}
public DataLabel(String prefix, double dat, String units){
label = prefix;
data = dat;
suffix = units;
maxWidth = Integer.MAX_VALUE;
updateText();
}
public DataLabel(String prefix, String units){
this(prefix, 0.0, units);
}
public DataLabel(String prefix){
this(prefix, 0.0, "");
}
public void setMaxLength(int ml){
maxWidth = ml;
}
public void update(double data){
this.data = data;
updateText();
}
public void setLabel(String prefix){
label = prefix;
updateText();
}
public void setUnits(String units){
suffix = units;
updateText();
}
public double getData(){
return data;
}
}
| package com.ui;
import com.ui.TelemetryListener;
import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.FontMetrics;
public class DataLabel extends JLabel implements TelemetryListener{
private String label;
private String suffix;
private double data;
private int maxWidth;
private void updateText(){
StringBuilder out = new StringBuilder();
out.append(label);
out.append((data >= 0)? " " : "-");
out.append(String.format("%f", Math.abs(data)));
out.append(suffix);
int finalWidth = Math.min(out.length(), maxWidth);
setText(disp);
}
public DataLabel(String prefix, double dat, String units){
label = prefix;
data = dat;
suffix = units;
maxWidth = Integer.MAX_VALUE;
updateText();
}
public DataLabel(String prefix, String units){
this(prefix, 0.0, units);
}
public DataLabel(String prefix){
this(prefix, 0.0, "");
}
public void setMaxLength(int ml){
maxWidth = ml;
}
public void update(double data){
this.data = data;
updateText();
}
public void setLabel(String prefix){
label = prefix;
updateText();
}
public void setUnits(String units){
suffix = units;
updateText();
}
public double getData(){
return data;
}
}
|
Modify crawler to save name of user who contributed an entry |
#6y7LtOjoNEfe72g62kZfwtFHMWkQ8XsZvcQ8xZDe
import praw
outfile = open('temp.js', 'w')
credentials = open('credentials', 'r')
client_id = credentials.readline().strip(' \t\n\r')
client_secret = credentials.readline().strip(' \t\n\r')
startId = 466
reddit = praw.Reddit(client_id=client_id, client_secret=client_secret, user_agent='atlas_bot')
for submission in reddit.subreddit('placeAtlas').new(limit=1000):
#print(dir(submission))
if(submission.link_flair_text == "New Entry"):
text = submission.selftext
text = text.replace("\"id\": 0,", "\"id\": 0,\n\t\t\"submitted_by\": \""+submission.author.name+"\",")
text = text.replace("\"id\": 0", "\"id\": "+str(startId))
startId = startId + 1
outfile.write(text+",")
print("written "+submission.title)
else:
print("skipped "+submission.title)
|
#6y7LtOjoNEfe72g62kZfwtFHMWkQ8XsZvcQ8xZDe
import praw
outfile = open('temp.js', 'w')
credentials = open('credentials', 'r')
client_id = credentials.readline().strip(' \t\n\r')
client_secret = credentials.readline().strip(' \t\n\r')
startId = 466
reddit = praw.Reddit(client_id=client_id, client_secret=client_secret, user_agent='atlas_bot')
for submission in reddit.subreddit('placeAtlas').new(limit=1000):
if(submission.link_flair_text == "New Entry"):
text = submission.selftext
text = text.replace("\"id\": 0", "\"id\": "+str(startId))
startId = startId + 1
outfile.write(text+",")
print("written "+submission.title)
else:
print("skipped "+submission.title)
|
Move the Controller Classes to be the class name resolution and the method passed as an array for routes | <?php
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\PromoListingController;
use App\Http\Controllers\WildCardController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Individual promo view route
Route::get('{any?}view/{title}-{id}', [PromoListingController::class, 'show'])
->where(['any' => '.*', 'title' => '.+', 'id' => '\d+']);
// Profile view
Route::get('{any?}profile/{accessid?}', [ProfileController::class, 'show'])
->where(['any' => '.*', 'accessid' => '[a-zA-Z]{2}\d{4}']);
// News listing by topic
Route::get('{any?}'.config('base.news_listing_route').'/'.config('base.news_topic_route').'/{slug}', config('base.news_controller').'@index')
->where(['any' => '.*', 'slug' => '.+']);
// News view
Route::get('{any?}'.config('base.news_view_route').'/{slug}-{id}', config('base.news_controller').'@show')
->where(['any' => '.*', 'slug' => '.+', 'id' => '\d+']);
// The wild card route is a catch all route that tries to resolve the requests path to a json file
Route::match(['get', 'post'], '{path}', [WildCardController::class, 'index'])
->where('path', '.*');
| <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Individual promo view route
Route::get('{any?}view/{title}-{id}', 'PromoListingController@show')
->where(['any' => '.*', 'title' => '.+', 'id' => '\d+']);
// Profile view
Route::get('{any?}profile/{accessid?}', 'ProfileController@show')
->where(['any' => '.*', 'accessid' => '[a-zA-Z]{2}\d{4}']);
// News listing by topic
Route::get('{any?}'.config('base.news_listing_route').'/'.config('base.news_topic_route').'/{slug}', config('base.news_controller').'@index')
->where(['any' => '.*', 'slug' => '.+']);
// News view
Route::get('{any?}'.config('base.news_view_route').'/{slug}-{id}', config('base.news_controller').'@show')
->where(['any' => '.*', 'slug' => '.+', 'id' => '\d+']);
// The wild card route is a catch all route that tries to resolve the requests path to a json file
Route::match(['get', 'post'], '{path}', 'WildCardController@index')
->where('path', '.*');
|
Fix memory issue during Artwork::cursor() call [WEB-1893]
https://github.com/laravel/framework/issues/14919 | <?php
namespace App\Console\Commands\Report;
use App\Library\Slug;
use App\Models\Collections\Artwork;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use PDO;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class ReportNetx extends BaseCommand
{
protected $signature = 'report:netx';
protected $description = 'Show artworks that have NetX images';
public function handle()
{
// https://github.com/laravel/framework/issues/14919
DB::connection()->getPdo()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$artworks = Artwork::query()
->whereHas('assets', function (Builder $query) {
$query->whereNotNull('netx_uuid');
})
->orderBy('pageviews', 'desc')
->limit(100);
foreach ($artworks->cursor() as $artwork) {
$this->info('https://nocache.staging.artic.edu/artworks/' . $artwork->citi_id . '/' . Slug::getUtf8Slug($artwork->title));
}
}
}
| <?php
namespace App\Console\Commands\Report;
use App\Library\Slug;
use App\Models\Collections\Artwork;
use Illuminate\Database\Eloquent\Builder;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class ReportNetx extends BaseCommand
{
protected $signature = 'report:netx';
protected $description = 'Show artworks that have NetX images';
public function handle()
{
$artworks = Artwork::query()
->whereHas('assets', function (Builder $query) {
$query->whereNotNull('netx_uuid');
})
->orderBy('pageviews', 'desc')
->limit(100);
foreach ($artworks->cursor() as $artwork) {
$this->info('https://nocache.staging.artic.edu/artworks/' . $artwork->citi_id . '/' . Slug::getUtf8Slug($artwork->title));
}
}
}
|
Fix Sqlite FTS5 compatibility check
As per https://github.com/wagtail/wagtail/issues/7798#issuecomment-1021544265 - the direct query against the sqlite3 library will fail with sqlite3.OperationalError, not django.db.OperationalError. | import sqlite3
from django.db import OperationalError
def fts5_available():
# based on https://stackoverflow.com/a/36656216/1853523
if sqlite3.sqlite_version_info < (3, 19, 0):
# Prior to version 3.19, SQLite doesn't support FTS5 queries with
# column filters ('{column_1 column_2} : query'), which the sqlite
# fulltext backend needs
return False
tmp_db = sqlite3.connect(':memory:')
try:
tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);')
except sqlite3.OperationalError:
return False
finally:
tmp_db.close()
return True
def fts_table_exists():
from wagtail.search.models import SQLiteFTSIndexEntry
try:
# ignore result of query; we are only interested in the query failing,
# not the presence of index entries
SQLiteFTSIndexEntry.objects.exists()
except OperationalError:
return False
return True
| import sqlite3
from django.db import OperationalError
def fts5_available():
# based on https://stackoverflow.com/a/36656216/1853523
if sqlite3.sqlite_version_info < (3, 19, 0):
# Prior to version 3.19, SQLite doesn't support FTS5 queries with
# column filters ('{column_1 column_2} : query'), which the sqlite
# fulltext backend needs
return False
tmp_db = sqlite3.connect(':memory:')
try:
tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);')
except OperationalError:
return False
finally:
tmp_db.close()
return True
def fts_table_exists():
from wagtail.search.models import SQLiteFTSIndexEntry
try:
# ignore result of query; we are only interested in the query failing,
# not the presence of index entries
SQLiteFTSIndexEntry.objects.exists()
except OperationalError:
return False
return True
|
Refactor code using es6 es6 syntax | module.exports = {
up(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
| 'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
}; |
lint: Remove settings exemption for possibly undefined star imports.
Signed-off-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com> | import argparse
from typing import List
from zulint.linters import run_pyflakes
def check_pyflakes(files: List[str], options: argparse.Namespace) -> bool:
suppress_patterns = [
("scripts/lib/pythonrc.py", "imported but unused"),
# Intentionally imported by zerver/lib/webhooks/common.py
('', "'zerver.lib.exceptions.UnexpectedWebhookEventType' imported but unused"),
# Our ipython startup pythonrc file intentionally imports *
("scripts/lib/pythonrc.py",
" import *' used; unable to detect undefined names"),
("settings.py", "settings import *' used; unable to detect undefined names"),
("settings.py", "'from .prod_settings_template import *' used; unable to detect undefined names"),
("settings.py", "settings.*' imported but unused"),
("settings.py", "'.prod_settings_template.*' imported but unused"),
# Sphinx adds `tags` specially to the environment when running conf.py.
("docs/conf.py", "undefined name 'tags'"),
]
if options.full:
suppress_patterns = []
return run_pyflakes(files, options, suppress_patterns)
| import argparse
from typing import List
from zulint.linters import run_pyflakes
def check_pyflakes(files: List[str], options: argparse.Namespace) -> bool:
suppress_patterns = [
("scripts/lib/pythonrc.py", "imported but unused"),
# Intentionally imported by zerver/lib/webhooks/common.py
('', "'zerver.lib.exceptions.UnexpectedWebhookEventType' imported but unused"),
# Our ipython startup pythonrc file intentionally imports *
("scripts/lib/pythonrc.py",
" import *' used; unable to detect undefined names"),
("settings.py", "settings import *' used; unable to detect undefined names"),
("settings.py", "'from .prod_settings_template import *' used; unable to detect undefined names"),
("settings.py", "may be undefined, or defined from star imports"),
("settings.py", "settings.*' imported but unused"),
("settings.py", "'.prod_settings_template.*' imported but unused"),
# Sphinx adds `tags` specially to the environment when running conf.py.
("docs/conf.py", "undefined name 'tags'"),
]
if options.full:
suppress_patterns = []
return run_pyflakes(files, options, suppress_patterns)
|
Disable Hapi debugging only for tests | 'use strict';
const Hapi = require('hapi');
const Mongoose = require('mongoose');
const MONGODB_URI = process.env.MONGOLAB_URI || process.env.MONGODB_URI;
const HTTP_PORT = process.env.PORT || 3000;
const server = new Hapi.Server({
debug: module.parent ? false : undefined,
});
server.connection({port: HTTP_PORT});
const routes = require('./routes');
server.route(routes);
if (!module.parent) {
Mongoose.connect(MONGODB_URI, (err) => {
if (err) {
console.error('Failed to connect to MongoDB:', MONGODB_URI);
} else {
console.log('Connected to MongoDB:', MONGODB_URI);
}
})
server.start(() => {
console.log('Server started at', server.info.uri);
});
}
module.exports = server;
| 'use strict';
const Hapi = require('hapi');
const Mongoose = require('mongoose');
const MONGODB_URI = process.env.MONGOLAB_URI || process.env.MONGODB_URI;
const HTTP_PORT = process.env.PORT || 3000;
const server = new Hapi.Server({
debug: false
});
server.connection({port: HTTP_PORT});
const routes = require('./routes');
server.route(routes);
if (!module.parent) {
Mongoose.connect(MONGODB_URI, (err) => {
if (err) {
console.error('Failed to connect to MongoDB:', MONGODB_URI);
} else {
console.log('Connected to MongoDB:', MONGODB_URI);
}
})
server.start(() => {
console.log('Server started at', server.info.uri);
});
}
module.exports = server;
|
Add more spaces to twitter js code. | 'use strict';
(function(app) {
app.directive('twitterBtn', [function() {
var link = function() {
!function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js = d.createElement(s);
js.id = id;
js.src = p+'://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js,fjs);
}
}(document, 'script', 'twitter-wjs');
};
return {
restrict: 'A',
link: link,
templateUrl: '/angular/views/twitter-button.html'
};
}]);
})(timer.app); | 'use strict';
(function(app) {
app.directive('twitterBtn', [function() {
var link = function() {
!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src=p+'://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js,fjs);
}
}(document, 'script', 'twitter-wjs');
};
return {
restrict: 'A',
link: link,
templateUrl: '/angular/views/twitter-button.html'
};
}]);
})(timer.app); |
Change "list" to "menu" in directive name | 'use strict';
/**
* @ngdoc directive
* @name eeh-navigation-menu
* @restrict AE
*
* @description
* This directive allows for the creation of a framework-agnostic menu.
* It is possible to add a directive that adds behavior to, or otherwise manipulates, this directive.
* Third party jQuery menu plugins, such as Superfish and MetisMenu, can easily be used to style and add behavior to the
* menu that this directive generates.
*
* @param {string} menuName Sets the name of the menu that the directive will render.
*/
var MenuDirective = function (eehNavigation) {
return {
restrict: 'AE',
templateUrl: 'template/eeh-navigation/menu/eeh-navigation-menu.html',
scope: {
menuName: '='
},
link: function (scope) {
scope.iconBaseClass = function () {
return eehNavigation.iconBaseClass();
};
scope.$watch(eehNavigation.menuItems, function () {
if (angular.isUndefined(scope.menuName)) {
return;
}
scope.menuItems = eehNavigation.menuItemTree(scope.menuName);
});
}
};
};
angular.module('eehNavigation').directive('eehNavigationMenu', MenuDirective);
| 'use strict';
/**
* @ngdoc directive
* @name eeh-navigation-menu
* @restrict AE
*
* @description
* This directive allows for the creation of a framework-agnostic menu.
* It is possible to add a directive that adds behavior to, or otherwise manipulates, this directive.
* Third party jQuery menu plugins, such as Superfish and MetisMenu, can easily be used to style and add behavior to the
* menu that this directive generates.
*
* @param {string} menuName Sets the name of the menu that the directive will render.
*/
var ListDirective = function (eehNavigation) {
return {
restrict: 'AE',
templateUrl: 'template/eeh-navigation/menu/eeh-navigation-menu.html',
scope: {
menuName: '='
},
link: function (scope) {
scope.iconBaseClass = function () {
return eehNavigation.iconBaseClass();
};
scope.$watch(eehNavigation.menuItems, function () {
if (angular.isUndefined(scope.menuName)) {
return;
}
scope.menuItems = eehNavigation.menuItemTree(scope.menuName);
});
}
};
};
angular.module('eehNavigation').directive('eehNavigationList', ListDirective);
|
Support for DRF 3.0 and above
See http://www.django-rest-framework.org/topics/3.0-announcement/ | from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_representation(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
| from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_native(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
|
Drop support for reacct_representation property | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.serializers.json import DjangoJSONEncoder
from django_react_templatetags.mixins import RepresentationMixin
def json_encoder_cls_factory(context):
class ReqReactRepresentationJSONEncoder(ReactRepresentationJSONEncoder):
context = None
ReqReactRepresentationJSONEncoder.context = context
return ReqReactRepresentationJSONEncoder
class ReactRepresentationJSONEncoder(DjangoJSONEncoder):
'''
Custom json encoder that adds support for RepresentationMixin
'''
def default(self, o):
if isinstance(o, RepresentationMixin):
args = [self.context if hasattr(self, 'context') else None]
args = [x for x in args if x is not None]
return o.to_react_representation(*args)
return super(ReactRepresentationJSONEncoder, self).default(o)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.serializers.json import DjangoJSONEncoder
from django_react_templatetags.mixins import RepresentationMixin
def json_encoder_cls_factory(context):
class ReqReactRepresentationJSONEncoder(ReactRepresentationJSONEncoder):
context = None
ReqReactRepresentationJSONEncoder.context = context
return ReqReactRepresentationJSONEncoder
class ReactRepresentationJSONEncoder(DjangoJSONEncoder):
'''
Custom json encoder that adds support for RepresentationMixin
'''
def default(self, o):
if isinstance(o, RepresentationMixin):
# Allow backwards compability with react_representation prop
if not hasattr(o, 'to_react_representation'):
return o.react_representation
args = [self.context if hasattr(self, 'context') else None]
args = [x for x in args if x is not None]
return o.to_react_representation(*args)
return super(ReactRepresentationJSONEncoder, self).default(o)
|
oci: Remove empty mount option slice for FreeBSD
Mount options are marked `json:omitempty`. An empty slice in the default
object caused TestWithSpecFromFile to fail.
Signed-off-by: Samuel Karp <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@samuelkarp.com> | /*
Copyright The containerd 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 oci
import (
specs "github.com/opencontainers/runtime-spec/specs-go"
)
func defaultMounts() []specs.Mount {
return []specs.Mount{
{
Destination: "/dev",
Type: "devfs",
Source: "devfs",
Options: []string{"ruleset=4"},
},
{
Destination: "/dev/fd",
Type: "fdescfs",
Source: "fdescfs",
},
}
}
| /*
Copyright The containerd 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 oci
import (
specs "github.com/opencontainers/runtime-spec/specs-go"
)
func defaultMounts() []specs.Mount {
return []specs.Mount{
{
Destination: "/dev",
Type: "devfs",
Source: "devfs",
Options: []string{"ruleset=4"},
},
{
Destination: "/dev/fd",
Type: "fdescfs",
Source: "fdescfs",
Options: []string{},
},
}
}
|
Add `_become_staff` method to AccountsTestCase. | from factory import fuzzy
from django.contrib.auth import get_user_model
from django.test import TestCase
class AccountsTestCase(TestCase):
def setUp(self):
super(AccountsTestCase, self).setUp()
self.password = fuzzy.FuzzyText(length=16)
self.new_password = fuzzy.FuzzyText(length=16)
user_model = get_user_model()
self.user = user_model.objects.get_or_create(
username="test",
email="example@example.com",
first_name="Test",
last_name="User",
)[0]
self.user.set_password(self.password)
self.user.save()
def _become_staff(self):
"""Make this testcase's user a staff user."""
self.user.is_staff = True
self.user.is_superuser = False
self.user.save()
def _become_superuser(self):
"""Make this testcase's user a superuser."""
self.user.is_superuser = True
self.user.save()
| from factory import fuzzy
from django.contrib.auth import get_user_model
from django.test import TestCase
class AccountsTestCase(TestCase):
def setUp(self):
super(AccountsTestCase, self).setUp()
self.password = fuzzy.FuzzyText(length=16)
self.new_password = fuzzy.FuzzyText(length=16)
user_model = get_user_model()
self.user = user_model.objects.get_or_create(
username="test",
email="example@example.com",
first_name="Test",
last_name="User",
)[0]
self.user.set_password(self.password)
self.user.save()
def _become_superuser(self):
"""Make this testcase's user a superuser."""
self.user.is_superuser = True
self.user.save()
|
Create relay for gear shifter, set relay values | package com.saintsrobotics.frc;
import edu.wpi.first.wpilibj.Relay;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// Motors
public static final int LEFT_MOTOR_1 = 1;
public static final int LEFT_MOTOR_2 = 2;
public static final int RIGHT_MOTOR_1 = 3;
public static final int RIGHT_MOTOR_2 = 4;
// Relays
public static final int PICKUP_RELAY = 1;
public static final Relay.Direction PICKUP_RELAY_DIRECTION =
Relay.Direction.kBoth;
public static final int SHOOTER_RELAY = 2;
public static final Relay.Direction SHOOTER_RELAY_DIRECTION =
Relay.Direction.kBoth;
public static final int GEAR_SHIFTER_RELAY = 3;
public static final Relay.Direction GEAR_SHIFTER_RELAY_DIRECTION =
Relay.Direction.kBoth;
}
| package com.saintsrobotics.frc;
import edu.wpi.first.wpilibj.Relay;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// Motors
public static final int LEFT_MOTOR_1 = 1;
public static final int LEFT_MOTOR_2 = 2;
public static final int RIGHT_MOTOR_1 = 3;
public static final int RIGHT_MOTOR_2 = 4;
// Relays
public static final int PICKUP_RELAY = 5;
public static final Relay.Direction PICKUP_RELAY_DIRECTION = Relay.Direction.kBoth;
public static final int SHOOTER_RELAY = 6;
public static final Relay.Direction SHOOTER_RELAY_DIRECTION = Relay.Direction.kBoth;
}
|
Fix displaying a spinner more then once | // -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';
var trexDirectives = angular.module('trex.directives', []);
trexDirectives.directive('trexLoading', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var options = scope.$eval(attrs.trexLoading);
var spinner = new Spinner(options);
scope.$on('$destroy', function () {
spinner.stop();
})
scope.$watch(attrs.loading, function(value) {
if (!value) {
spinner.stop();
}
else {
spinner.spin();
element.append(spinner.el);
}
});
}
}
});
| // -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';
var trexDirectives = angular.module('trex.directives', []);
trexDirectives.directive('trexLoading', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var options = scope.$eval(attrs.trexLoading);
var spinner = new Spinner(options).spin();
element.append(spinner.el);
scope.$on('$destroy', function () {
spinner.stop();
})
scope.$watch(attrs.loading, function(value) {
if (!value) {
spinner.stop();
}
});
}
}
});
|
Use 2 spaces for deeply nested objects | 'use strict';
/**
* Sets up the routes.
* @param {object} app - Express app
*/
module.exports.setup = function (app) {
/**
* @swagger
* /:
* get:
* responses:
* 200:
* description: hello world
*/
app.get('/', rootHandler);
/**
* @swagger
* /login:
* post:
* responses:
* 200:
* description: login
*/
app.post('/login', loginHandler);
};
function rootHandler(req, res) {
res.send('Hello World!');
}
function loginHandler(req, res) {
var user = {};
user.username = req.param('username');
user.password = req.param('password');
res.json(user);
}
| 'use strict';
/**
* Sets up the routes.
* @param {object} app - Express app
*/
module.exports.setup = function (app) {
/**
* @swagger
* /:
* get:
* responses:
* 200:
* description: hello world
*/
app.get('/', rootHandler);
/**
* @swagger
* /login:
* post:
* responses:
* 200:
* description: login
*/
app.get('/login', loginHandler);
};
function rootHandler(req, res) {
res.send('Hello World!');
}
function loginHandler(req, res) {
var user = {};
user.username = req.param('username');
user.password = req.param('password');
res.json(user);
}
|
Fix error handling in server | #!/usr/bin/env python3
import sys
import time
import glob
import serial
import psutil
CPU_INTERVAL = 0.5
CONNECT_TIMEOUT = 2
BAUD = 4800
def update_loop(conn):
while True:
load = psutil.cpu_percent(interval=CPU_INTERVAL)
scaled_load = int(load * 10)
message = str(scaled_load).encode('ascii')
conn.write(message)
def connect_serial():
devices = glob.glob('/dev/ttyUSB?')
if not devices:
raise IOError()
conn = serial.Serial(devices[0], BAUD)
# wtf
conn.baudrate = 300
conn.baudrate = BAUD
return conn
def main():
while True:
try:
with connect_serial() as conn:
update_loop(conn)
except IOError:
print('Connection failed! Retrying in %d seconds...'
% CONNECT_TIMEOUT, file=sys.stderr)
time.sleep(CONNECT_TIMEOUT)
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import sys
import time
import glob
import serial
import psutil
CPU_INTERVAL = 0.5
CONNECT_TIMEOUT = 2
BAUD = 4800
def update_loop(conn):
while True:
load = psutil.cpu_percent(interval=CPU_INTERVAL)
scaled_load = int(load * 10)
message = str(scaled_load).encode('ascii')
conn.write(message)
def connect_serial(DEVICE, BAUD):
conn = serial.Serial(DEVICE, BAUD)
# wtf
conn.baudrate = 300
conn.baudrate = BAUD
return conn
def main():
while True:
try:
with connect_serial(glob.glob('/dev/ttyUSB?')[0], BAUD) as conn:
update_loop(conn)
except IOError:
print('Connection with %s failed! Retrying in %d seconds...'
% (DEVICE, CONNECT_TIMEOUT), file=sys.stderr)
time.sleep(CONNECT_TIMEOUT)
if __name__ == '__main__':
main()
|
Debug song of the week | import sys
import random
from pytz import timezone
from datetime import datetime
import pytz
from libs import post_text
import spotipy
import os
from spotipy.oauth2 import SpotifyClientCredentials
'''
sadness_texts = [line.strip() for line in open('list of saddness.txt')]
central = timezone('US/Central')
now = datetime.now(tz=pytz.utc)
'''
username = os.environ.get("USERNAME")
client_id = os.environ.get("SPOTIPY_CLIENT_ID")
client_secret = os.environ.get("SPOTIPY_CLIENT_SECRET")
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
results = sp.user_playlist(username, sys.argv[2], 'tracks,next')
tracks = results['tracks']
all_tracks = tracks['items']
while tracks['next']:
tracks = sp.next(tracks)
all_tracks += tracks['items']
random_track = random.choice(all_tracks)
if(datetime.datetime.today().weekday() == 0):
post_text(u'\U0001F3B5\U0001F4C5: ' + random_track['track']['name'] + ' - ' + random_track['track']['artists'][0]['name'] + ' ' + random_track['track']['external_urls']['spotify'], sys.argv[1])
else:
post_text(datetime.datetime.today().weekday(), sys.argv[1])
| import sys
import random
from pytz import timezone
from datetime import datetime
import pytz
from libs import post_text
import spotipy
import os
from spotipy.oauth2 import SpotifyClientCredentials
'''
sadness_texts = [line.strip() for line in open('list of saddness.txt')]
central = timezone('US/Central')
now = datetime.now(tz=pytz.utc)
'''
username = os.environ.get("USERNAME")
client_id = os.environ.get("SPOTIPY_CLIENT_ID")
client_secret = os.environ.get("SPOTIPY_CLIENT_SECRET")
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
results = sp.user_playlist(username, sys.argv[2], 'tracks,next')
tracks = results['tracks']
all_tracks = tracks['items']
while tracks['next']:
tracks = sp.next(tracks)
all_tracks += tracks['items']
random_track = random.choice(all_tracks)
if(datetime.datetime.today().weekday() == 0):
post_text(u'\U0001F3B5\U0001F4C5: ' + random_track['track']['name'] + ' - ' + random_track['track']['artists'][0]['name'] + ' ' + random_track['track']['external_urls']['spotify'], sys.argv[1])
|
Replace usage of deprecated TreeTraverser | /*
* 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.facebook.presto.sql.util;
import com.facebook.presto.sql.tree.Node;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import java.util.stream.Stream;
import static com.google.common.collect.Streams.stream;
import static java.util.Objects.requireNonNull;
public final class AstUtils
{
public static boolean nodeContains(Node node, Node subNode)
{
requireNonNull(node, "node is null");
requireNonNull(subNode, "subNode is null");
return preOrder(node)
.anyMatch(childNode -> childNode == subNode);
}
public static Stream<Node> preOrder(Node node)
{
return stream(
Traverser.forTree((SuccessorsFunction<Node>) Node::getChildren)
.depthFirstPreOrder(requireNonNull(node, "node is null")));
}
private AstUtils() {}
}
| /*
* 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.facebook.presto.sql.util;
import com.facebook.presto.sql.tree.Node;
import com.google.common.collect.TreeTraverser;
import java.util.stream.Stream;
import static com.google.common.collect.Iterables.unmodifiableIterable;
import static java.util.Objects.requireNonNull;
public class AstUtils
{
public static boolean nodeContains(Node node, Node subNode)
{
requireNonNull(node, "node is null");
requireNonNull(subNode, "subNode is null");
return preOrder(node)
.anyMatch(childNode -> childNode == subNode);
}
public static Stream<Node> preOrder(Node node)
{
return TreeTraverser.using((Node n) -> unmodifiableIterable(n.getChildren()))
.preOrderTraversal(requireNonNull(node, "node is null"))
.stream();
}
private AstUtils() {}
}
|
Remove irrelevant documentation from MopPositionUpdateEvent | package org.apollo.game.model.event.impl;
import org.apollo.game.model.Position;
import org.apollo.game.model.entity.Mob;
import org.apollo.game.model.event.Event;
/**
* An {@link Event} created when a Mob's Position is being updated.
*
* @author Major
*/
public final class MobPositionUpdateEvent extends Event {
/**
* The Mob whose position is being updated.
*/
private final Mob mob;
/**
* The next Position of the Mob.
*/
private final Position next;
/**
* Creates the MobPositionUpdateEvent.
*
* @param mob The {@link Mob} whose Position is being updated.
* @param next The next {@link Position} of the Mob.
*/
public MobPositionUpdateEvent(Mob mob, Position next) {
this.mob = mob;
this.next = next;
}
/**
* Gets the {@link Mob} being moved.
*
* @return The Mob.
*/
public Mob getMob() {
return mob;
}
/**
* Gets the {@link Position} this {@link Mob} is being moved to.
*
* @return The Position.
*/
public Position getNext() {
return next;
}
} | package org.apollo.game.model.event.impl;
import org.apollo.game.model.Position;
import org.apollo.game.model.entity.Mob;
import org.apollo.game.model.event.Event;
/**
* An {@link Event} created when a Mob's Position is being updated.
* <p>
* This Event intentionally ignores the result of execution - it should not be possible for a plugin to prevent this
* Event from happening, only to listen for it.
*
* @author Major
*/
public final class MobPositionUpdateEvent extends Event {
/**
* The Mob whose position is being updated.
*/
private final Mob mob;
/**
* The next Position of the Mob.
*/
private final Position next;
/**
* Creates the MobPositionUpdateEvent.
*
* @param mob The {@link Mob} whose Position is being updated.
* @param next The next {@link Position} of the Mob.
*/
public MobPositionUpdateEvent(Mob mob, Position next) {
this.mob = mob;
this.next = next;
}
/**
* Gets the {@link Mob} being moved.
*
* @return The Mob.
*/
public Mob getMob() {
return mob;
}
/**
* Gets the {@link Position} this {@link Mob} is being moved to.
*
* @return The Position.
*/
public Position getNext() {
return next;
}
} |
Fix the error caused by missing default constructor that is used when copying components internally. | /*
* Copyright 2013 MovingBlocks
*
* 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.terasology.cities;
import org.terasology.cities.settlements.Settlement;
import org.terasology.entitySystem.Component;
/**
* Indicates a settlement.
*/
public final class SettlementComponent implements Component {
public Settlement settlement;
public SettlementComponent() {
}
public SettlementComponent(Settlement settlement) {
this.settlement = settlement;
}
}
| /*
* Copyright 2013 MovingBlocks
*
* 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.terasology.cities;
import org.terasology.cities.settlements.Settlement;
import org.terasology.entitySystem.Component;
/**
* Indicates a settlement.
*/
public final class SettlementComponent implements Component {
public Settlement settlement;
public SettlementComponent(Settlement settlement) {
this.settlement = settlement;
}
}
|
Change absolute import to relative | from __future__ import print_function
import random
from . import print_header
def play_match(game, players, verbose=True):
"""Plays a match between the given players"""
if verbose:
print(game)
while not game.is_over():
cur_player = players[game.cur_player()]
move = cur_player.choose_move(game.copy())
game.make_move(move)
if verbose:
print(game)
def play_series(game, players, n_matches=100):
"""
Plays a series of 'n_matches' of a 'game' between
the given 'players'.
"""
print_header('Series')
print('Game:', game.name)
print('Players:', players)
print('No. Matches: %d\n' % n_matches)
counters = {'W': 0, 'L': 0, 'D': 0}
for n_match in range(1, n_matches + 1):
print('Match %d/%d:' % (n_match, n_matches), end=' ')
new_game = game.copy()
play_match(new_game, players, verbose=False)
outcomes = new_game.outcomes()
counters[outcomes[0]] += 1
print(outcomes)
print('\nOutcomes:', counters)
| from __future__ import print_function
import random
from capstone.util import print_header
def play_match(game, players, verbose=True):
"""Plays a match between the given players"""
if verbose:
print(game)
while not game.is_over():
cur_player = players[game.cur_player()]
move = cur_player.choose_move(game.copy())
game.make_move(move)
if verbose:
print(game)
def play_series(game, players, n_matches=100):
"""
Plays a series of 'n_matches' of a 'game' between
the given 'players'.
"""
print_header('Series')
print('Game:', game.name)
print('Players:', players)
print('No. Matches: %d\n' % n_matches)
counters = {'W': 0, 'L': 0, 'D': 0}
for n_match in range(1, n_matches + 1):
print('Match %d/%d:' % (n_match, n_matches), end=' ')
new_game = game.copy()
play_match(new_game, players, verbose=False)
outcomes = new_game.outcomes()
counters[outcomes[0]] += 1
print(outcomes)
print('\nOutcomes:', counters)
|
Fix case in function names to be PEP8 compatible |
import logging
from version import __version__
logger = logging.getLogger(__name__)
logger.debug('Loading %s ver %s' % (__name__, __version__))
# Actions represents the available textual items that can be passed to main
# to drive dispatch. These should be all lower case, no spaces or underscores.
actions = [
'collect',
'update',
'testignore', # Allows the bin app to be run without calling into here.
]
def get_data_for_game(game):
pass
def get_data_for_games(games=[]):
for game in games:
get_data_for_game(game)
def get_games(active=True, beginning=None, end=None):
"""
Return a tuple of games. Updates gets finished games to check for updated stats,
if False (default) it returns active games. beginning and end allow you set a range
for the search, with no end indicating until the time.
"""
def main(action='collect'):
"""
The main entry point for the application
"""
logger.debug('Dispatching action %s' % action)
# By default, we collect info on current games
if action == 'collect':
get_data_for_games(get_games(active=True))
# Otherwise we can look to update finished games
elif action == 'update':
get_data_for_games(get_games(active=False))
elif action in actions:
raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action)
else:
raise ValueError('Unknown action "%s"' % action)
|
import logging
from version import __version__
logger = logging.getLogger(__name__)
logger.debug('Loading %s ver %s' % (__name__, __version__))
# Actions represents the available textual items that can be passed to main
# to drive dispatch. These should be all lower case, no spaces or underscores.
actions = [
'collect',
'update',
'testignore', # Allows the bin app to be run without calling into here.
]
def GetDataForGame(game):
pass
def GetDataForGames(games=[]):
for game in games:
GetDataForGame(game)
def GetGames(active=True, beginning=None, end=None):
"""
Return a tuple of games. Updates gets finished games to check for updated stats,
if False (default) it returns active games. beginning and end allow you set a range
for the search, with no end indicating until the time.
"""
def main(action='collect'):
"""
The main entry point for the application
"""
logger.debug('Dispatching action %s' % action)
# By default, we collect info on current games
if action == 'collect':
GetDataForGames(GetGames(active=True))
# Otherwise we can look to update finished games
elif action == 'update':
GetDataForGames(GetGames(active=False))
elif action in actions:
raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action)
else:
raise ValueError('Unknown action "%s"' % action)
|
Use radix.MaybeNil for detecting if something doesn't exist in the cache | package redis
import (
"github.com/DMarby/picsum-photos/cache"
"github.com/mediocregopher/radix/v3"
)
// Provider implements a redis cache
type Provider struct {
pool *radix.Pool
}
// New returns a new Provider instance
func New(address string, poolSize int) (*Provider, error) {
// Use the default pool, which has a 10 second timeout
pool, err := radix.NewPool("tcp", address, poolSize)
if err != nil {
return nil, err
}
return &Provider{
pool: pool,
}, nil
}
// Get returns an object from the cache if it exists
func (p *Provider) Get(key string) (data []byte, err error) {
mn := radix.MaybeNil{Rcv: &data}
err = p.pool.Do(radix.Cmd(&mn, "GET", key))
if err != nil {
return nil, err
}
if mn.Nil {
return nil, cache.ErrNotFound
}
return
}
// Set adds an object to the cache
func (p *Provider) Set(key string, data []byte) (err error) {
return p.pool.Do(radix.FlatCmd(nil, "SET", key, data))
}
// Shutdown shuts down the cache
func (p *Provider) Shutdown() {
p.pool.Close()
}
| package redis
import (
"github.com/DMarby/picsum-photos/cache"
"github.com/mediocregopher/radix/v3"
)
// Provider implements a redis cache
type Provider struct {
pool *radix.Pool
}
// New returns a new Provider instance
func New(address string, poolSize int) (*Provider, error) {
// Use the default pool, which has a 10 second timeout
pool, err := radix.NewPool("tcp", address, poolSize)
if err != nil {
return nil, err
}
return &Provider{
pool: pool,
}, nil
}
// Get returns an object from the cache if it exists
func (p *Provider) Get(key string) (data []byte, err error) {
err = p.pool.Do(radix.Cmd(&data, "GET", key))
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, cache.ErrNotFound
}
return
}
// Set adds an object to the cache
func (p *Provider) Set(key string, data []byte) (err error) {
return p.pool.Do(radix.FlatCmd(nil, "SET", key, data))
}
// Shutdown shuts down the cache
func (p *Provider) Shutdown() {
p.pool.Close()
}
|
Remove old class declaration and ensure store exists. | /**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import classnames from 'classnames';
import ErrorIcon from '../../../svg/error.svg';
const { useSelect } = Data;
/*
* A single module. Keeps track of its own active state and settings.
*/
export default function ModuleSettingsWarning( {
slug,
// context,
} ) {
// @TODO: Resolver only runs once per set of args, so we are working around
// this to rerun after modules are loaded.
// Once #1769 is resolved, we can remove the call to getModules,
// and remove the !! modules cache busting param.
const modules = useSelect( ( select ) => select( CORE_MODULES )?.getModules() );
const requirementsStatus = useSelect( ( select ) => select( CORE_MODULES )?.getCheckRequirementsStatus( slug, !! modules ) );
if ( requirementsStatus === null ) {
return null;
}
return (
<div
className={ classnames( 'googlesitekit-settings-module-warning', 'googlesitekit-settings-module-warning--modules-list' ) } >
<ErrorIcon height="20" width="23" /> { requirementsStatus }
</div>
);
}
| /**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import classnames from 'classnames';
import ErrorIcon from '../../../svg/error.svg';
const { useSelect } = Data;
/**
* A single module. Keeps track of its own active state and settings.
*/
/*
class ModuleSettingsWarning extends Component {
render() {
return null;
}
}
export default withFilters( 'googlesitekit.ModuleSettingsWarning' )( ModuleSettingsWarning );
*/
export default function ModuleSettingsWarning( {
slug,
// context,
} ) {
// @TODO: Resolver only runs once per set of args, so we are working around
// this to rerun after modules are loaded.
// Once #1769 is resolved, we can remove the call to getModules,
// and remove the !! modules cache busting param.
const modules = useSelect( ( select ) => select( CORE_MODULES ).getModules() );
const requirementsStatus = useSelect( ( select ) => select( CORE_MODULES ).getCheckRequirementsStatus( slug, !! modules ) );
if ( requirementsStatus === null ) {
return null;
}
return (
<div
className={ classnames( 'googlesitekit-settings-module-warning', 'googlesitekit-settings-module-warning--modules-list' ) } >
<ErrorIcon height="20" width="23" /> { requirementsStatus }
</div>
);
}
|
Use internal player history instead of emitted status | import PlayerController from './PlayerController'
import { connect } from 'react-redux'
import { ensureState } from 'redux-optimistic-ui'
import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue'
import {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
} from '../../modules/player'
import { playerVisualizerError } from '../../modules/playerVisualizer'
const mapActionCreators = {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
playerVisualizerError,
}
const mapStateToProps = (state) => {
const { player, playerVisualizer, prefs } = state
const queue = ensureState(state.queue)
return {
cdgAlpha: player.cdgAlpha,
cdgSize: player.cdgSize,
historyJSON: player.historyJSON,
isAtQueueEnd: player.isAtQueueEnd,
isErrored: player.isErrored,
isPlaying: player.isPlaying,
isPlayingNext: player.isPlayingNext,
isQueueEmpty: queue.result.length === 0,
isReplayGainEnabled: prefs.isReplayGainEnabled,
isWebGLSupported: player.isWebGLSupported,
mp4Alpha: player.mp4Alpha,
queue: getOrderedQueue(state),
queueId: player.queueId,
volume: player.volume,
visualizer: playerVisualizer,
}
}
export default connect(mapStateToProps, mapActionCreators)(PlayerController)
| import PlayerController from './PlayerController'
import { connect } from 'react-redux'
import { ensureState } from 'redux-optimistic-ui'
import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue'
import {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
} from '../../modules/player'
import { playerVisualizerError } from '../../modules/playerVisualizer'
const mapActionCreators = {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
playerVisualizerError,
}
const mapStateToProps = (state) => {
const { player, playerVisualizer, prefs } = state
const queue = ensureState(state.queue)
return {
cdgAlpha: player.cdgAlpha,
cdgSize: player.cdgSize,
historyJSON: state.status.historyJSON, // @TODO use state.player instead?
isAtQueueEnd: player.isAtQueueEnd,
isErrored: player.isErrored,
isPlaying: player.isPlaying,
isPlayingNext: player.isPlayingNext,
isQueueEmpty: queue.result.length === 0,
isReplayGainEnabled: prefs.isReplayGainEnabled,
isWebGLSupported: player.isWebGLSupported,
mp4Alpha: player.mp4Alpha,
queue: getOrderedQueue(state),
queueId: player.queueId,
volume: player.volume,
visualizer: playerVisualizer,
}
}
export default connect(mapStateToProps, mapActionCreators)(PlayerController)
|
Fix test for Python 3 | from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from myshop.models.polymorphic.product import Product
from myshop.models.manufacturer import Manufacturer
class ProductSelectViewTest(TestCase):
def setUp(self):
manufacturer = Manufacturer.objects.create(name="testmanufacturer")
Product.objects.create(product_name="testproduct1", order=1, manufacturer=manufacturer)
def test_finds_product_case_insensitive(self):
response = self.client.get(reverse('shop:select-product') + "?term=Prod")
data = json.loads(response.content.decode("utf-8"))
self.assertEqual(data['count'], 1)
self.assertEqual(data['results'][0]['text'], "testproduct1")
def test_bogus_query_finds_nothing(self):
response = self.client.get(reverse('shop:select-product') + "?term=whatever")
data = json.loads(response.content.decode("utf-8"))
self.assertEqual(data['count'], 0)
| from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from myshop.models.polymorphic.product import Product
from myshop.models.manufacturer import Manufacturer
class ProductSelectViewTest(TestCase):
def setUp(self):
manufacturer = Manufacturer.objects.create(name="testmanufacturer")
Product.objects.create(product_name="testproduct1", order=1, manufacturer=manufacturer)
def test_finds_product_case_insensitive(self):
response = self.client.get(reverse('shop:select-product') + "?term=Prod")
data = json.loads(response.content)
self.assertEqual(data['count'], 1)
self.assertEqual(data['results'][0]['text'], "testproduct1")
def test_bogus_query_finds_nothing(self):
response = self.client.get(reverse('shop:select-product') + "?term=whatever")
data = json.loads(response.content)
self.assertEqual(data['count'], 0)
|
Fix middleware not overriding if flag not set | 'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
if (!opts) opts = {};
function minifier(req, res, next) {
if (opts.override === false) {
res.renderMin = function (view, renderOpts) {
this.render(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
}
} else {
res.oldRender = res.render;
res.render = function (view, renderOpts) {
this.oldRender(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
};
}
return next();
}
return (minifier);
}
module.exports = minifyHTML; | 'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
if (!opts) opts = {};
function minifier(req, res, next) {
if (opts.override !== true) {
res.renderMin = function (view, renderOpts) {
this.render(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
}
} else {
res.oldRender = res.render;
res.render = function (view, renderOpts) {
this.oldRender(view, renderOpts, function (err, html) {
if (err) throw err;
html = minify(html, opts.htmlMinifier);
res.send(html);
});
};
}
return next();
}
return (minifier);
}
module.exports = minifyHTML; |
Fix rollup for lazy load image | import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'src/main-aot.js',
dest: 'dist/build.js', // output a single application bundle
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
// Skip certain warnings
// should intercept ... but doesn't in some rollup versions
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
// console.warn everything else
console.warn( warning.message );
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: [
'node_modules/rxjs/**',
'node_modules/ng-lazyload-image/**'
]
}),
uglify()
]
};
| import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'src/main-aot.js',
dest: 'dist/build.js', // output a single application bundle
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
// Skip certain warnings
// should intercept ... but doesn't in some rollup versions
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
// console.warn everything else
console.warn( warning.message );
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: 'node_modules/rxjs/**',
}),
uglify()
]
};
|
Fix incorrect signature for get_customer_ids function
Change-Id: Ib44af3ac6437ad9fa4cbfd9fda9b055b7eff4547 | # Copyright 2022 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.import proto
from .query_editor import QuerySpecification
from .query_executor import AdsReportFetcher
def get_customer_ids(ads_client, customer_id):
query = """
SELECT customer_client.id FROM customer_client
WHERE customer_client.manager = FALSE
"""
query_specification = QuerySpecification(query).generate()
report_fetcher = AdsReportFetcher(ads_client, customer_id)
return report_fetcher.fetch(query_specification)
| # Copyright 2022 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.import proto
from .query_editor import QuerySpecification
from .query_executor import AdsReportFetcher
def get_customer_ids(ads_client, customer_id):
query = """
SELECT customer_client.id FROM customer_client
WHERE customer_client.manager = FALSE
"""
query_specification = QuerySpecification(query).generate()
report_fetcher = AdsReportFetcher(ads_client)
return report_fetcher.fetch(query_specification, customer_id)
|
Use unit test.TestCase instead of SimpleTestCase | from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(unittest.TestCase):
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
| from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.management import create_anonymous_user
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(SimpleTestCase):
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
|
Use node binary defined by user environment | #!/usr/bin/env node
"use strict";
var child_process = require("child_process");
process.chdir(__dirname + "/src")
child_process.execFile("find", ["-type", "f"], function(err, stdout, stderr){
var files = stdout.split("\n");
files.pop();
files.forEach(function(path, i){
files[i] = path.slice(2);
});
files.splice(0, 0, "../pixi.js");
child_process.execFile("mkcjs", files, function(err, stdout, stderr){
if (stdout || stderr) console.log(stdout, stderr);
child_process.execFile("uglifyjs", ["../pixi.js", "--screw-ie8", "-mco", "../pixi.min.js"], function(err, stdout, stderr){
if (stdout || stderr) console.log(stdout, stderr);
process.exit();
});
});
});
| #!/usr/bin/node
"use strict";
var child_process = require("child_process");
process.chdir(__dirname + "/src")
child_process.execFile("find", ["-type", "f"], function(err, stdout, stderr){
var files = stdout.split("\n");
files.pop();
files.forEach(function(path, i){
files[i] = path.slice(2);
});
files.splice(0, 0, "../pixi.js");
child_process.execFile("mkcjs", files, function(err, stdout, stderr){
if (stdout || stderr) console.log(stdout, stderr);
child_process.execFile("uglifyjs", ["../pixi.js", "--screw-ie8", "-mco", "../pixi.min.js"], function(err, stdout, stderr){
if (stdout || stderr) console.log(stdout, stderr);
process.exit();
});
});
}); |
Make twig options an input param | <?php
namespace SlaxWeb\View;
class View
{
public $view = "";
public $viewData = [];
protected $_loader = null;
protected $_twig = null;
protected $_rendered = false;
public function __construct(array $data = [], array $options = ["cache" => TWIGCACHE])
{
$this->_loader = new \Twig_Loader_Filesystem(TEMPLATEPATH);
$this->_twig = new \Twig_Environment($this->_loader, $options);
$this->view = $this->_getViewClass($this) . ".html";
$this->viewData = $data;
}
public function __destruct()
{
if ($this->_rendered === false) {
echo $this->_twig->render($this->view, $this->viewData);
}
}
public function render()
{
$this->_rendered = true;
return $this->_twig->render($this->view, $this->viewData);
}
protected function _getViewClass($obj)
{
$classname = get_class($obj);
if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
$classname = $matches[1];
}
return $classname;
}
}
| <?php
namespace SlaxWeb\View;
class View
{
public $view = "";
public $viewData = [];
protected $_loader = null;
protected $_twig = null;
protected $_rendered = false;
public function __construct(array $data = [])
{
$this->_loader = new \Twig_Loader_Filesystem(TEMPLATEPATH);
$this->_twig = new \Twig_Environment($this->_loader, ["cache" => TWIGCACHE]);
$this->view = $this->_getViewClass($this) . ".html";
$this->viewData = $data;
}
public function __destruct()
{
if ($this->_rendered === false) {
echo $this->_twig->render($this->view, $this->viewData);
}
}
public function render()
{
$this->_rendered = true;
return $this->_twig->render($this->view, $this->viewData);
}
protected function _getViewClass($obj)
{
$classname = get_class($obj);
if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
$classname = $matches[1];
}
return $classname;
}
}
|
Fix pin button active state | import Component from 'flarum/component';
import icon from 'flarum/helpers/icon';
/**
The back/pin button group in the top-left corner of Flarum's interface.
*/
export default class BackButton extends Component {
view() {
var history = app.history;
var pane = app.pane;
return m('div.back-button', {
className: this.props.className || '',
onmouseenter: pane && pane.show.bind(pane),
onmouseleave: pane && pane.onmouseleave.bind(pane),
config: this.onload.bind(this)
}, history.canGoBack() ? m('div.btn-group', [
m('button.btn.btn-default.btn-icon.back', {onclick: history.back.bind(history)}, icon('chevron-left icon-glyph')),
pane && pane.active ? m('button.btn.btn-default.btn-icon.pin'+(pane.pinned ? '.active' : ''), {onclick: pane.togglePinned.bind(pane)}, icon('thumb-tack icon-glyph')) : '',
]) : (this.props.drawer ? [
m('button.btn.btn-default.btn-icon.drawer-toggle', {onclick: this.toggleDrawer.bind(this)}, icon('reorder icon-glyph'))
] : ''));
}
onload(element, isInitialized, context) {
context.retain = true;
}
toggleDrawer() {
$('body').toggleClass('drawer-open');
}
}
| import Component from 'flarum/component';
import icon from 'flarum/helpers/icon';
/**
The back/pin button group in the top-left corner of Flarum's interface.
*/
export default class BackButton extends Component {
view() {
var history = app.history;
var pane = app.pane;
return m('div.back-button', {
className: this.props.className || '',
onmouseenter: pane && pane.show.bind(pane),
onmouseleave: pane && pane.onmouseleave.bind(pane),
config: this.onload.bind(this)
}, history.canGoBack() ? m('div.btn-group', [
m('button.btn.btn-default.btn-icon.back', {onclick: history.back.bind(history)}, icon('chevron-left icon-glyph')),
pane && pane.active ? m('button.btn.btn-default.btn-icon.pin'+(pane.active ? '.active' : ''), {onclick: pane.togglePinned.bind(pane)}, icon('thumb-tack icon-glyph')) : '',
]) : (this.props.drawer ? [
m('button.btn.btn-default.btn-icon.drawer-toggle', {onclick: this.toggleDrawer.bind(this)}, icon('reorder icon-glyph'))
] : ''));
}
onload(element, isInitialized, context) {
context.retain = true;
}
toggleDrawer() {
$('body').toggleClass('drawer-open');
}
}
|
Use jquery's document.ready instead of our custom asynchronous loader. | /*======================================================================
* Exhibit auto-create
* Code to automatically create the database, load the data links in
* <head>, and then to create an exhibit if there's no ex:ondataload
* handler on the body element.
*
* You can avoid running this code by adding the URL parameter
* autoCreate=false when you include exhibit-api.js.
*======================================================================
*/
Exhibit.autoCreate = function() {
if (Exhibit.params.autoCreate) {
var fDone = function() {
window.exhibit = Exhibit.create();
window.exhibit.configureFromDOM();
};
try {
var s = Exhibit.getAttribute(document.body, "ondataload");
if (s != null && typeof s == "string" && s.length > 0) {
fDone = function() {
var f = eval(s);
if (typeof f == "function") {
f.call();
}
}
}
} catch (e) {
// silent
}
window.database = Exhibit.Database.create();
window.database.loadDataLinks(fDone);
}
}
SimileAjax.jQuery(document).ready(Exhibit.autoCreate);
| /*======================================================================
* Exhibit auto-create
* Code to automatically create the database, load the data links in
* <head>, and then to create an exhibit if there's no ex:ondataload
* handler on the body element.
*
* You can avoid running this code by adding the URL parameter
* autoCreate=false when you include exhibit-api.js.
*======================================================================
*/
SimileAjax.jQuery(document).ready(function() {
var fDone = function() {
window.exhibit = Exhibit.create();
window.exhibit.configureFromDOM();
};
try {
var s = Exhibit.getAttribute(document.body, "ondataload");
if (s != null && typeof s == "string" && s.length > 0) {
fDone = function() {
var f = eval(s);
if (typeof f == "function") {
f.call();
}
}
}
} catch (e) {
// silent
}
var fLoadSubmissions = function() {
window.database.loadSubmissionLinks(fDone);
};
Exhibit.Authentication.authenticate();
window.database = Exhibit.Database.create();
window.database.loadDataLinks(fLoadSubmissions);
});
|
Make sure report is part of the job dict
To get around failures like this for now:
https://travis-ci.org/frictionlessdata/goodtables.io/builds/179121528
This should definitely be investigated and fixed as part of #33 | from goodtablesio import services
# Module API
def get_job(job_id):
"""Get job by identifier.
Args:
job_id (str): job identifier
Returns:
dict: job result if job was found, None otherwise
"""
result = services.database['jobs'].find_one(job_id=job_id)
if not result:
return None
# TODO: we need to store the status in the DB as we can no longer rely on
# the job id being the same one used by a celery task
status = 'Not Implemented'
# TODO: this should not be needed after #33
if 'report' not in result:
result['report'] = None
if 'finished' not in result:
result['finished'] = None
return {'status': status, 'result': result}
def get_job_ids():
"""Get all job identifiers.
Returns:
str[]: list of job identifiers
"""
return [r['job_id']
for r in
services.database['jobs'].find(order_by=['-created'])]
| from goodtablesio import services
# Module API
def get_job(job_id):
"""Get job by identifier.
Args:
job_id (str): job identifier
Returns:
dict: job result if job was found, None otherwise
"""
result = services.database['jobs'].find_one(job_id=job_id)
if not result:
return None
# TODO: we need to store the status in the DB as we can no longer rely on
# the job id being the same one used by a celery task
status = 'Not Implemented'
return {'status': status, 'result': result}
def get_job_ids():
"""Get all job identifiers.
Returns:
str[]: list of job identifiers
"""
return [r['job_id']
for r in
services.database['jobs'].find(order_by=['-created'])]
|
Allow to override a registered Node class. | import { Registry } from '../util'
/*
Registry for Nodes.
@class NodeRegistry
@extends util/Registry
*/
class NodeRegistry extends Registry {
/**
Register a Node class.
@param {Class} nodeClass
*/
register(nodeClazz) {
var type = nodeClazz.prototype.type
if ( typeof type !== 'string' || type === '' ) {
throw new Error( 'Node names must be strings and must not be empty')
}
if (!( nodeClazz.prototype._isNode)) {
throw new Error( 'Nodes must be subclasses of Substance.Data.Node' )
}
if (this.contains(type)) {
// throw new Error('Node class is already registered: ' + type)
console.error('Node class is already registered. Overriding. ', type)
this.remove(type)
}
this.add(type, nodeClazz)
}
}
export default NodeRegistry
| import { Registry } from '../util'
/*
Registry for Nodes.
@class NodeRegistry
@extends util/Registry
*/
class NodeRegistry extends Registry {
/**
Register a Node class.
@param {Class} nodeClass
*/
register(nodeClazz) {
var type = nodeClazz.prototype.type
if ( typeof type !== 'string' || type === '' ) {
console.error('#### nodeClazz', nodeClazz)
throw new Error( 'Node names must be strings and must not be empty')
}
if ( !( nodeClazz.prototype._isNode) ) {
throw new Error( 'Nodes must be subclasses of Substance.Data.Node' )
}
if (this.contains(type)) {
throw new Error('Node class is already registered: ' + type)
}
this.add(type, nodeClazz)
}
}
export default NodeRegistry
|
Add default values for username and passwd and add a TODO. | #!/bin/python3
""" This script contains functions for the REST client.
Author: Julien Delplanque
"""
import http.client
import json
def get_pacman_pkgs_to_update(ip: str, username: str=None, passwd: str=None):
""" Get the list of packages from the REST server hosted by
the raspberry pi.
TODO implement login.
Keyword arguments:
ip - the ip of the raspberry pi
username - your username
passwd - your password
"""
conn = http.client.HTTPConnection(ip+":5000")
conn.request("GET", "/pkgtoupdate")
response = conn.getresponse()
j = json.loads(response.read().decode("utf-8"))
return j.get("pacman")
def get_sensors_data(ip: str, username: str=None, passwd: str=None):
""" Get the list of sensors data from the REST server hosted by
the raspberry pi.
TODO implement login.
Keyword arguments:
ip - the ip of the raspberry pi
username - your username
passwd - your password
"""
conn = http.client.HTTPConnection(ip+":5000")
conn.request("GET", "/sensors")
response = conn.getresponse()
return json.loads(response.read().decode("utf-8"))
| #!/bin/python3
""" This script contains functions for the REST client.
Author: Julien Delplanque
"""
import http.client
import json
def get_pacman_pkgs_to_update(ip: str, username: str, passwd: str):
""" Get the list of packages from the REST server hosted by
the raspberry pi.
Keyword arguments:
ip - the ip of the raspberry pi
username - your username
passwd - your password
"""
conn = http.client.HTTPConnection(ip+":5000")
conn.request("GET", "/pkgtoupdate")
response = conn.getresponse()
j = json.loads(response.read().decode("utf-8"))
return j.get("pacman")
def get_sensors_data(ip: str, username: str, passwd: str):
""" Get the list of sensors data from the REST server hosted by
the raspberry pi.
Keyword arguments:
ip - the ip of the raspberry pi
username - your username
passwd - your password
"""
conn = http.client.HTTPConnection(ip+":5000")
conn.request("GET", "/sensors")
response = conn.getresponse()
return json.loads(response.read().decode("utf-8"))
|
Update AudioChannel to create new oscillator for each note in playSong | var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = null;
this.gain = this.context.createGain();
this.gain.connect(this.context.destination);
var args = args ? args : {};
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wave : "triangle";
this.volume = args.gain ? args.gain : 0.2;
}
AudioChannel.prototype.setNodes = function() {
if(this.oscill) {
this.oscill.stop();
}
this.oscill = this.context.createOscillator();
this.oscill.connect(this.gain);
this.oscill.frequency.value = this.frequency;
this.oscill.type = this.wave;
this.gain.gain.value = this.volume;
this.oscill.start();
};
AudioChannel.prototype.playSong = function(song) {
var playNextNote = function(song) {
this.frequency = noteToFreq(song[0].note, song[0].octave);
this.setNodes();
if(song[1]) {
setTimeout(playNextNote.bind(this, song.slice(1)), song[0].length);
}
else {
setTimeout(function() {
this.oscill.stop();
}.bind(this), song[0].length);
}
}.bind(this);
playNextNote(song);
};
| var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
var args = args ? args : {};
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wave : "triangle";
this.volume = args.gain ? args.gain : 0.2;
}
AudioChannel.prototype.setNodes = function() {
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
this.oscill.connect(this.gain);
this.gain.connect(this.context.destination);
this.oscill.frequency.value = this.frequency;
this.oscill.type = this.wave;
this.gain.gain.value = this.volume;
};
AudioChannel.prototype.playSong = function(song) {
this.setNodes();
this.oscill.start();
var playNextNote = function(song) {
this.oscill.frequency.value = noteToFreq(song[0].note, song[0].octave);
if(song[1]) {
setTimeout(playNextNote.bind(this, song.slice(1)), song[0].length);
}
else {
setTimeout(function() {
this.oscill.stop();
}.bind(this), song[0].length);
}
}.bind(this);
playNextNote(song);
};
|
Increment version number to 0.2.5 | __version__ = '0.2.5'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
| __version__ = '0.2.4'
# This list defines all the modules that will be loaded if a user invokes
# from climLab import *
# totally out of date!
#__all__ = ["constants", "thermo", "orbital_table",
# "long_orbital_table", "insolation", "ebm",
# "column", "convadj"]
#from climlab import radiation
# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
#from climlab.model import ebm, column
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.process.process import Process, process_like, get_axes
from climlab.process.time_dependent_process import TimeDependentProcess
from climlab.process.implicit import ImplicitProcess
from climlab.process.diagnostic import DiagnosticProcess
from climlab.process.energy_budget import EnergyBudget
|
Add missing path name attribute | package svn
import (
"encoding/xml"
"github.com/pkg/errors"
)
type Log struct {
XMLName xml.Name `xml:"log"`
Entries []LogEntry `xml:"logentry"`
}
type LogEntry struct {
*Commit
XMLName xml.Name `xml:"logentry"`
Paths []Path `xml:"paths>path"`
Message string `xml:"msg"`
}
type Path struct {
XMLName xml.Name `xml:"path"`
TextModifications bool `xml:"text-mods,attr"`
Kind string `xml:"kind,attr"`
CopyFromPath *string `xml:"copyfrom-path,attr,omitempty"`
CopyFromRevision *int `xml:"copyfrom-rev,attr,omitempty"`
Action string `xml:"action,attr"`
PropertyModifications bool `xml:"prop-mods,attr"`
Name string `xml:",chardata"`
}
func GetLog(address string) (*Log, error) {
log := Log{}
if err := Execute(&log, "log", "--xml", "--verbose", address); err != nil {
return nil, errors.Wrapf(err, "failed to get log for %s", address)
}
return &log, nil
}
| package svn
import (
"encoding/xml"
"github.com/pkg/errors"
)
type Log struct {
XMLName xml.Name `xml:"log"`
Entries []LogEntry `xml:"logentry"`
}
type LogEntry struct {
*Commit
XMLName xml.Name `xml:"logentry"`
Paths []Path `xml:"paths>path"`
Message string `xml:"msg"`
}
type Path struct {
XMLName xml.Name `xml:"path"`
TextModifications bool `xml:"text-mods,attr"`
Kind string `xml:"kind,attr"`
CopyFromPath *string `xml:"copyfrom-path,attr,omitempty"`
CopyFromRevision *int `xml:"copyfrom-rev,attr,omitempty"`
Action string `xml:"action,attr"`
PropertyModifications bool `xml:"prop-mods,attr"`
}
func GetLog(address string) (*Log, error) {
log := Log{}
if err := Execute(&log, "log", "--xml", "--verbose", address); err != nil {
return nil, errors.Wrapf(err, "failed to get log for %s", address)
}
return &log, nil
}
|
Use word-wrap and overflow-wrap since word-wrap is not supported in Chrome et al | export default function() {
return function({ addUtilities, variants }) {
addUtilities(
{
'.break-normal': {
// For IE 11, remove 'word-wrap' when we have a 'modern' mode
'word-wrap': 'normal',
'overflow-wrap': 'normal',
'word-break': 'normal',
},
'.break-words': {
// For IE 11, remove 'word-wrap' when we have a 'modern' mode
'word-wrap': 'break-word',
'overflow-wrap': 'break-word',
},
'.break-all': { 'word-break': 'break-all' },
'.truncate': {
overflow: 'hidden',
'text-overflow': 'ellipsis',
'white-space': 'nowrap',
},
},
variants('wordBreak')
)
}
}
| export default function() {
return function({ addUtilities, variants, target }) {
const wrapPropertyName = target('wordBreak') === 'ie11' ? 'word-wrap' : 'overflow-wrap'
addUtilities(
{
'.break-normal': {
[wrapPropertyName]: 'normal',
'word-break': 'normal',
},
'.break-words': { [wrapPropertyName]: 'break-word' },
'.break-all': { 'word-break': 'break-all' },
'.truncate': {
overflow: 'hidden',
'text-overflow': 'ellipsis',
'white-space': 'nowrap',
},
},
variants('wordBreak')
)
}
}
|
Fix out of bounds exception when danger zone is larger than the board | package com.srs.tetris.bob.evaluator;
import com.srs.tetris.bob.Position;
import com.srs.tetris.game.BitBoard;
/**
* Gives a high
*/
public class DangerZoneEvaluator implements PositionEvaluator {
private int dangerZoneSize;
private double exponent;
public DangerZoneEvaluator(int dangerZoneSize, double exponent) {
this.dangerZoneSize = dangerZoneSize;
this.exponent = exponent;
}
@Override
public Score evaluate(Position position) {
BitBoard board = position.getBoard();
int height = 0;
int dangerZoneSize = Math.min(board.getHeight(), this.dangerZoneSize);
for (int y = 0; y < dangerZoneSize; y++) {
if (!board.isLineEmpty(y)) {
height = dangerZoneSize - y;
break;
}
}
return new ScalarScore(Math.pow(height, exponent));
}
}
| package com.srs.tetris.bob.evaluator;
import com.srs.tetris.bob.Position;
import com.srs.tetris.game.BitBoard;
/**
* Gives a high
*/
public class DangerZoneEvaluator implements PositionEvaluator {
private int dangerZoneSize;
private double exponent;
public DangerZoneEvaluator(int dangerZoneSize, double exponent) {
this.dangerZoneSize = dangerZoneSize;
this.exponent = exponent;
}
@Override
public Score evaluate(Position position) {
BitBoard board = position.getBoard();
int height = 0;
for (int y = 0; y < dangerZoneSize; y++) {
if (!board.isLineEmpty(y)) {
height = dangerZoneSize - y;
break;
}
}
return new ScalarScore(Math.pow(height, exponent));
}
}
|
Fix dependency cmis_web -> cmis_field | # -*- coding: utf-8 -*-
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': "CMIS Web interface",
'summary': """
Embeddable CMIS Web components""",
'author': 'ACSONE SA/NV',
'website': "http://alfodoo.org",
'category': 'Uncategorized',
'version': '9.0.1.0.0',
'license': 'AGPL-3',
'depends': [
'web',
'cmis_field'
],
'qweb': [
"static/src/xml/*.xml",
],
'data': [
'views/cmis_web.xml'
],
}
| # -*- coding: utf-8 -*-
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': "CMIS Web interface",
'summary': """
Embeddable CMIS Web components""",
'author': 'ACSONE SA/NV',
'website': "http://alfodoo.org",
'category': 'Uncategorized',
'version': '9.0.1.0.0',
'license': 'AGPL-3',
'depends': [
'web',
'cmis'
],
'qweb': [
"static/src/xml/*.xml",
],
'data': [
'views/cmis_web.xml'
],
}
|
Ch05: Create URL pattern for Tag Detail. | """suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from organizer.views import homepage, tag_detail
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', homepage),
url(r'^tag/(?P<slug>[\w\-]+)/$',
tag_detail,
),
]
| """suorganizer URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from organizer.views import homepage
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', homepage),
]
|
Add a function to log http requests | package goanna
import (
"bytes"
"log"
"net/http"
"runtime/debug"
"strings"
"time"
)
const LogRequestTemplate = `
----------------------------------------------------------------------
%s
Url: %s
Method: %s
Timestamp: %s
Request Headers:
%s
Request Body:
%s
Stack trace:
%s
----------------------------------------------------------------------
`
var Logger *log.Logger
// LogRequest logs a goanna request
func LogRequest(r *Request, v ...string) {
serializedHeaders := bytes.Buffer{}
r.Header.Write(&serializedHeaders)
printf := log.Printf
if Logger != nil {
printf = Logger.Printf
}
printf(
LogRequestTemplate,
strings.Join(v, " "),
r.URL.String(),
r.Method,
time.Now(),
serializedHeaders.String(),
string(r.BodyData()),
debug.Stack(),
)
}
// LogHttpRequest logs a http request
func LogHttpRequest(r *http.Request, v ...string) {
serializedHeaders := bytes.Buffer{}
r.Header.Write(&serializedHeaders)
printf := log.Printf
if Logger != nil {
printf = Logger.Printf
}
printf(
LogRequestTemplate,
strings.Join(v, " "),
r.URL.String(),
r.Method,
time.Now(),
serializedHeaders.String(),
"<hidden>",
debug.Stack(),
)
}
| package goanna
import (
"bytes"
"log"
"runtime/debug"
"strings"
"time"
)
const LogRequestTemplate = `
----------------------------------------------------------------------
%s
Url: %s
Method: %s
Timestamp: %s
Request Headers:
%s
Request Body:
%s
Stack trace:
%s
----------------------------------------------------------------------
`
var Logger *log.Logger
// LogRequest logs a request using the
func LogRequest(r *Request, v ...string) {
serializedHeaders := bytes.Buffer{}
r.Header.Write(&serializedHeaders)
printf := log.Printf
if Logger != nil {
printf = Logger.Printf
}
printf(
LogRequestTemplate,
strings.Join(v, " "),
r.URL.String(),
r.Method,
time.Now(),
serializedHeaders.String(),
string(r.BodyData()),
debug.Stack(),
)
}
|
Clean up result math and notation | import DicewareOptions from './DicewareOptions'
import React, { PureComponent } from 'react'
export default class App extends PureComponent {
state = {
length: 6
}
handleLengthChange = event => this.setState({ length: parseInt(event.target.value, 10) })
handlePossibleItemsChange = possibleItems => this.setState({ possibleItems })
render () {
const possiblePasswords = this.state.possibleItems ** this.state.length
const approximatePrefix = possiblePasswords > Number.MAX_SAFE_INTEGER && '~ '
return (
<form>
<h1>Password Entropy</h1>
<label>
<h2>Length</h2>
<input value={this.state.length} onChange={this.handleLengthChange} type="number" min="1" required/>
</label>
<h2>Options</h2>
<DicewareOptions onChange={this.handlePossibleItemsChange}/>
<h2>Possible Passwords</h2>
{approximatePrefix}{possiblePasswords.toLocaleString()} ({approximatePrefix}{Math.log2(possiblePasswords).toFixed(2)} bits of entropy)
</form>
)
}
}
| import DicewareOptions from './DicewareOptions'
import React, { PureComponent } from 'react'
export default class App extends PureComponent {
state = {
length: 6
}
handleLengthChange = event => this.setState({ length: parseInt(event.target.value, 10) })
handlePossibleItemsChange = possibleItems => this.setState({ possibleItems })
render () {
const possiblePasswords = this.state.possibleItems ** this.state.length
return (
<form>
<h1>Password Entropy</h1>
<label>
<h2>Length</h2>
<input value={this.state.length} onChange={this.handleLengthChange} type="number" min="1" required/>
</label>
<h2>Options</h2>
<DicewareOptions onChange={this.handlePossibleItemsChange}/>
<h2>Possible Passwords</h2>
Roughly {possiblePasswords.toPrecision(4)} ({Math.floor(Math.log2(possiblePasswords)) + 1} bits of entropy)
</form>
)
}
}
|
Package is now successfully getting integrated in a django project. So version increased | # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name='django-tests-assistant',
version='0.2.0',
description= 'A tool to help keep track of tests, specially for you - developer.',
license='(AGPL v3+) GNU AFFERO GENERAL PUBLIC LICENSE Version 3 or later',
url='https://github.com/tests-assistant/tests-assistant/',
author=u'Amirouche Boubekki',
author_email='amirouche.boubekki@gmail.com',
maintainer=u'Arun Karunagath',
maintainer_email='the1.arun@gmail.com',
packages=find_packages(),
long_description=open('README.rst').read(),
install_requires=open('requirements.txt').readlines(),
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
zip_safe=False,
)
| # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name='django-tests-assistant',
version='0.1.2',
description= 'A tool to help keep track of tests, specially for you - developer.',
license='(AGPL v3+) GNU AFFERO GENERAL PUBLIC LICENSE Version 3 or later',
url='https://github.com/tests-assistant/tests-assistant/',
author=u'Amirouche Boubekki',
author_email='amirouche.boubekki@gmail.com',
maintainer=u'Arun Karunagath',
maintainer_email='the1.arun@gmail.com',
packages=find_packages(),
long_description=open('README.rst').read(),
install_requires=open('requirements.txt').readlines(),
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
zip_safe=False,
)
|
Make console command always available from YII_CONSOLE_COMMANDS | <?php
/**
* Yii command line script file.
*
* This script is meant to be run on command line to execute
* one of the pre-defined console commands.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2011 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @version $Id$
*/
// fix for fcgi
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('YII_DEBUG') or define('YII_DEBUG',true);
require_once(dirname(__FILE__).'/yii.php');
if(isset($config))
{
$app=Yii::createConsoleApplication($config);
$app->commandRunner->addCommands(YII_PATH.'/cli/commands');
}
else
$app=Yii::createConsoleApplication(array('basePath'=>dirname(__FILE__).'/cli'));
$env=@getenv('YII_CONSOLE_COMMANDS');
if(!empty($env))
$app->commandRunner->addCommands($env);
$app->run(); | <?php
/**
* Yii command line script file.
*
* This script is meant to be run on command line to execute
* one of the pre-defined console commands.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2011 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @version $Id$
*/
// fix for fcgi
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('YII_DEBUG') or define('YII_DEBUG',true);
require_once(dirname(__FILE__).'/yii.php');
if(isset($config))
{
$app=Yii::createConsoleApplication($config);
$app->commandRunner->addCommands(YII_PATH.'/cli/commands');
$env=@getenv('YII_CONSOLE_COMMANDS');
if(!empty($env))
$app->commandRunner->addCommands($env);
}
else
$app=Yii::createConsoleApplication(array('basePath'=>dirname(__FILE__).'/cli'));
$app->run(); |
Move twig ref to $GLOBALS avoiding side-effects on the file | <?php
namespace Siler\Twig;
function init($templatesPath, $templatesCachePath = null, $debug = null)
{
if (is_null($debug)) {
$debug = false;
}
$twig = new \Twig_Environment(new \Twig_Loader_Filesystem($templatesPath), [
'debug' => $debug,
'cache' => $templatesCachePath,
]);
if (function_exists('url')) {
$twig->addFunction(new \Twig_SimpleFunction('url', 'url'));
}
$GLOBALS['twig'] = $twig;
return $twig;
}
function render($name, $data = [])
{
$twig = $GLOBALS['twig'];
return $twig->render($name, $data);
}
| <?php
namespace Siler\Twig;
$_twigEnv = null;
function init($templatesPath, $templatesCachePath = null, $debug = null)
{
global $_twigEnv;
if (is_null($debug)) {
$debug = false;
}
$_twigEnv = new \Twig_Environment(new \Twig_Loader_Filesystem($templatesPath), [
'debug' => $debug,
'cache' => $templatesCachePath,
]);
if (function_exists('url')) {
$_twigEnv->addFunction(new \Twig_SimpleFunction('url', 'url'));
}
return $_twigEnv;
}
function render($name, $data = [])
{
global $_twigEnv;
return $_twigEnv->render($name, $data);
}
|
Make it safe to call canProvide multiple times (or not at all). | package com.sedmelluq.discord.lavaplayer.demo.jda;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;
/**
* This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
* before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
* provide20MsAudio().
*/
public class AudioPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer;
private AudioFrame lastFrame;
/**
* @param audioPlayer Audio player to wrap.
*/
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
}
@Override
public boolean canProvide() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
return lastFrame != null;
}
@Override
public byte[] provide20MsAudio() {
if (lastFrame == null) {
lastFrame = audioPlayer.provide();
}
byte[] data = lastFrame != null ? lastFrame.data : null;
lastFrame = null;
return data;
}
@Override
public boolean isOpus() {
return true;
}
}
| package com.sedmelluq.discord.lavaplayer.demo.jda;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;
/**
* This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
* before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
* provide20MsAudio().
*/
public class AudioPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer;
private AudioFrame lastFrame;
/**
* @param audioPlayer Audio player to wrap.
*/
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
}
@Override
public boolean canProvide() {
lastFrame = audioPlayer.provide();
return lastFrame != null;
}
@Override
public byte[] provide20MsAudio() {
return lastFrame.data;
}
@Override
public boolean isOpus() {
return true;
}
}
|
Tests: Call correct port when API testing | var http = require('http');
var _ = require('underscore');
function request(rest, method, data, done)
{
done = done || data;
var ctype = 'text/plain';
if (typeof data === 'object') {
data = JSON.stringify(data);
ctype = 'application/json';
}
var options = {
'hostname' : 'localhost',
'port' : process.env.PORT,
'path' : '/' + rest.join('/'),
'method' : method.toUpperCase(),
'headers' : {
'Connection' : 'close',
'Content-Type' : ctype,
}
};
var hasEntityBody = data && _.contains(['POST', 'PUT'], method.toUpperCase());
if (hasEntityBody) {
options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
}
var req = http.request(options, function(res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function(e) {
var obj = JSON.parse(data);
done(obj, res.statusCode);
})
});
req.on('error', function(e) {
/* Something's wrong... */
console.log(e);
done();
});
if (hasEntityBody) {
req.write(data);
}
req.end();
}
module.exports.request = request;
| var http = require('http');
var _ = require('underscore');
function request(rest, method, data, done)
{
done = done || data;
var ctype = 'text/plain';
if (typeof data === 'object') {
data = JSON.stringify(data);
ctype = 'application/json';
}
var options = {
'hostname' : 'localhost',
'port' : 5000, /* Default port of canumb */
'path' : '/' + rest.join('/'),
'method' : method.toUpperCase(),
'headers' : {
'Connection' : 'close',
'Content-Type' : ctype,
}
};
var hasEntityBody = data && _.contains(['POST', 'PUT'], method.toUpperCase());
if (hasEntityBody) {
options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
}
var req = http.request(options, function(res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function(e) {
var obj = JSON.parse(data);
done(obj, res.statusCode);
})
});
req.on('error', function(e) {
/* Something's wrong... */
console.log(e);
done();
});
if (hasEntityBody) {
req.write(data);
}
req.end();
}
module.exports.request = request;
|
Update sample code using custom logger | <?php
/*
* Example: interactive_search_callsign
*
* Downloads necessary statistics from one of the availble
* data servers if local content is expired.
*
* Note: Not advised to use for inline calls of your
* web application. See cron documentation.
*
*/
use Vatsimphp\VatsimData;
use Vatsimphp\Log\LoggerFactory;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
require_once '../vendor/autoload.php';
// Create custom logger based on Monolog (note: every PSR-3 compliant logger will work)
// see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
$logFile = __DIR__ . '/../app/logs/vatsimphp_custom.log';
$logger = new Logger('vatsimphp');
$logger->pushHandler(new StreamHandler($logFile, Logger::DEBUG));
// Register custom logger
LoggerFactory::register("_DEFAULT_", $logger);
$vatsim = new VatsimData();
$vatsim->loadData();
// see app/logs/vatsimphp_custom.log for the result
| <?php
/*
* Example: interactive_search_callsign
*
* Downloads necessary statistics from one of the availble
* data servers if local content is expired.
*
* Note: Not advised to use for inline calls of your
* web application. See cron documentation.
*
*/
use Vatsimphp\VatsimData;
use Vatsimphp\Log\LoggerFactory;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
require_once '../vendor/autoload.php';
// Create custom logger based on Monolog (note: every PSR-3 compliant logger will work)
// see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
$logger = new Logger('vatsimphp');
$logger->pushHandler(new StreamHandler('vatsim.log', Logger::DEBUG));
// Register custom logger
LoggerFactory::register("_DEFAULT_", $logger);
$vatsim = new VatsimData();
$vatsim->loadData();
// see vatsim.log for the result
|
Change order of the subnavigation | /* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import ContainerSettings from './service-schema/ContainerSettings';
import EnvironmentVariables from './service-schema/EnvironmentVariables';
import General from './service-schema/General';
import HealthChecks from './service-schema/HealthChecks';
import Labels from './service-schema/Labels';
import Networking from './service-schema/Networking';
import Optional from './service-schema/Optional';
import Volumes from './service-schema/Volumes';
let ServiceSchema = {
type: 'object',
properties: {
general: General,
containerSettings: ContainerSettings,
networking: Networking,
environmentVariables: EnvironmentVariables,
labels: Labels,
healthChecks: HealthChecks,
volumes: Volumes,
optional: Optional
},
required: [
'general'
]
};
module.exports = ServiceSchema;
| /* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import ContainerSettings from './service-schema/ContainerSettings';
import EnvironmentVariables from './service-schema/EnvironmentVariables';
import General from './service-schema/General';
import HealthChecks from './service-schema/HealthChecks';
import Labels from './service-schema/Labels';
import Networking from './service-schema/Networking';
import Optional from './service-schema/Optional';
import Volumes from './service-schema/Volumes';
let ServiceSchema = {
type: 'object',
properties: {
general: General,
containerSettings: ContainerSettings,
networking: Networking,
optional: Optional,
environmentVariables: EnvironmentVariables,
volumes: Volumes,
labels: Labels,
healthChecks: HealthChecks
},
required: [
'general'
]
};
module.exports = ServiceSchema;
|
Improve performance: smaller scope, optimization
Change addEventListener to focus only on the large web chat in Facebook
(id = webMessengerRecentMessages). Also add this event listener only
after the entire page has loaded to prevent a flurry of runs.
Conflicts:
background.js | window.addEventListener("load", monospaceInit, false);
function monospaceInit(evt) {
detect(evt);
document.getElementById(
"webMessengerRecentMessages"
).addEventListener('DOMNodeInserted', detect, false);
}
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText;
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
| window.addEventListener("load", detect, false);
document.getElementById("webMessengerRecentMessages").addEventListener('DOMNodeInserted', detect, false);
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
|
Set custom dependency URL for docker-py until required features are merged
Signed-off-by: Maxime Petazzoni <0706025b2bbcec1ed8d64822f4eccd96314938d0@signalfuse.com> | #!/usr/bin/env python
# Copyright (C) 2013 SignalFuse, Inc.
# Setuptools install description file.
import os
from setuptools import setup, find_packages
setup(
name='maestro',
version='0.0.1',
description='Orchestrator for multi-host Docker deployments',
zip_safe=True,
packages=find_packages(),
install_requires=['docker-py'],
dependency_links=['https://github.com/mpetazzoni/docker-py/archive/timeout-and-localbinddirs.zip#egg=docker-py'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
],
entry_points={
'console': ['maestro = maestro.maestro'],
'setuptools.installation': ['eggsecutable = maestro.maestro:main'],
},
author='Maxime Petazzoni',
author_email='max@signalfuse.com',
license='GNU Lesser General Public License v3',
keywords='maestro docker orchestration deployment',
url='http://github.com/signalfuse/maestro-ng',
)
| #!/usr/bin/env python
# Copyright (C) 2013 SignalFuse, Inc.
# Setuptools install description file.
import os
from setuptools import setup, find_packages
requirements = ['docker-py==0.2.2']
setup(
name='maestro',
version='0.0.1',
description='Orchestrator for multi-host Docker deployments',
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
],
entry_points={
'console': ['maestro = maestro.maestro'],
'setuptools.installation': ['eggsecutable = maestro.maestro:main'],
},
author='Maxime Petazzoni',
author_email='max@signalfuse.com',
license='GNU Lesser General Public License v3',
keywords='maestro docker orchestration deployment',
url='http://github.com/signalfuse/maestro-ng',
)
|
Remove unneeded properties in base Channel class | from system.translations import Translations
__author__ = 'Sean'
_ = Translations().get()
class Channel(object):
"""
A channel - Represents a channel on a protocol. Subclass this!
@ivar name The name of the channel
@ivar users A set containing all the User objects in the channel
"""
def __init__(self, name, protocol=None):
"""
Initialise the channel. Remember to call super in subclasses!
:arg name: The name of the channel
:type name: str
:arg protocol: The protocol object this channel belongs to
:type protocol: Protocol
"""
self.name = name # This is essential!
self.protocol = protocol # May be None for one-off or fake channels
self.users = set() # This is also essential!
def respond(self, message):
raise NotImplementedError(_("This method must be overridden"))
def add_user(self, user):
self.users.add(user)
def remove_user(self, user):
try:
self.users.remove(user)
except KeyError:
self.protocol.log.debug(
"Tried to remove non-existent user \"%s\" from channel \"%s\""
% (user, self)
)
| from system.translations import Translations
__author__ = 'Sean'
_ = Translations().get()
class Channel(object):
name = ""
users = None
def __init__(self, name, protocol=None):
self.name = name
self.protocol = protocol
self.users = set()
def respond(self, message):
raise NotImplementedError(_("This method must be overridden"))
def add_user(self, user):
self.users.add(user)
def remove_user(self, user):
try:
self.users.remove(user)
except KeyError:
self.protocol.log.debug(
"Tried to remove non-existent user \"%s\" from channel \"%s\""
% (user, self)
)
|
Fix code style by phpcbf, make travis green again! | <?php
namespace Sirius\Validation\Rule;
class Website extends AbstractRule
{
const WEBSITE_REGEX = '@^((http|https)\:)//.+$@i';
const MESSAGE = 'This input must be a valid website address';
const LABELED_MESSAGE = '{label} must be a valid website address';
public function validate($value, $valueIdentifier = null)
{
$this->value = $value;
$this->success = (substr($value, 0, 2) == '//')
|| (preg_match(static::WEBSITE_REGEX, $value) && filter_var(
$value,
FILTER_VALIDATE_URL,
FILTER_FLAG_HOST_REQUIRED
));
return $this->success;
}
}
| <?php
namespace Sirius\Validation\Rule;
class Website extends AbstractRule
{
const WEBSITE_REGEX = '@^((http|https)\:)//.+$@i';
const MESSAGE = 'This input must be a valid website address';
const LABELED_MESSAGE = '{label} must be a valid website address';
public function validate($value, $valueIdentifier = null)
{
$this->value = $value;
$this->success = (substr($value, 0, 2) == '//')
|| (preg_match(static::WEBSITE_REGEX, $value) && filter_var(
$value,
FILTER_VALIDATE_URL,
FILTER_FLAG_HOST_REQUIRED
));
return $this->success;
}
}
|
Update default dev user data | /**
* This script automatically creates a default Admin user when an
* empty database is used for the first time. You can use this
* technique to insert data into any List you have defined.
*/
exports.create = {
User: [
{ 'name': 'Admin User', email: 'admin@javascript.org.nz', password: 'admin', isAdmin: true, committeeRole: 'officer' }
]
};
/**
* The following is the older version of this update script, it is
* left here for reference as an example of how more complex updates
* can be structured.
*/
/*
var keystone = require('keystone'),
async = require('async'),
User = keystone.list('User');
var admins = [
{ email: 'user@keystonejs.com', password: 'admin', name: { first: 'Admin', last: 'User' } }
];
function createAdmin(admin, done) {
var newAdmin = new User.model(admin);
newAdmin.isAdmin = true;
newAdmin.save(function(err) {
if (err) {
console.error("Error adding admin " + admin.email + " to the database:");
console.error(err);
} else {
console.log("Added admin " + admin.email + " to the database.");
}
done(err);
});
}
exports = module.exports = function(done) {
async.forEach(admins, createAdmin, done);
};
*/
| /**
* This script automatically creates a default Admin user when an
* empty database is used for the first time. You can use this
* technique to insert data into any List you have defined.
*/
exports.create = {
User: [
{ 'name.first': 'Admin', 'name.last': 'User', email: 'admin@javascript.org.nz', password: 'admin', isAdmin: true, committeeRole: 'officer' }
]
};
/**
* The following is the older version of this update script, it is
* left here for reference as an example of how more complex updates
* can be structured.
*/
/*
var keystone = require('keystone'),
async = require('async'),
User = keystone.list('User');
var admins = [
{ email: 'user@keystonejs.com', password: 'admin', name: { first: 'Admin', last: 'User' } }
];
function createAdmin(admin, done) {
var newAdmin = new User.model(admin);
newAdmin.isAdmin = true;
newAdmin.save(function(err) {
if (err) {
console.error("Error adding admin " + admin.email + " to the database:");
console.error(err);
} else {
console.log("Added admin " + admin.email + " to the database.");
}
done(err);
});
}
exports = module.exports = function(done) {
async.forEach(admins, createAdmin, done);
};
*/
|
Change some map test names | (function() {
module("R.map");
var map = require('eigensheep/map')['default'];
var double = function(x) { return x * 2 };
test("mapping over empty arrays", function() {
deepEqual(map(double, []), []);
});
test("mapping over nonempty arrays", function() {
deepEqual(map(double, [1, 2, 3]), [2, 4, 6]);
});
test("uses an object's own map implementation if available", function() {
expect(3);
function Vector(x, y) {
this.x = x;
this.y = y;
};
Vector.prototype.map = function(f) {
equal(f, double);
return new Vector(f(this.x), f(this.y));
};
var vector = new Vector(1, 2);
var newVector = map(double, vector);
equal(newVector.x, 2);
equal(newVector.y, 4);
});
})();
| (function() {
module("R.map");
var map = require('eigensheep/map')['default'];
var double = function(x) { return x * 2 };
test("on empty arrays", function() {
deepEqual(map(double, []), []);
});
test("on nonempty arrays", function() {
deepEqual(map(double, [1, 2, 3]), [2, 4, 6]);
});
test("uses an object's own map implementation if available", function() {
expect(3);
function Vector(x, y) {
this.x = x;
this.y = y;
};
Vector.prototype.map = function(f) {
equal(f, double);
return new Vector(f(this.x), f(this.y));
};
var vector = new Vector(1, 2);
var newVector = map(double, vector);
equal(newVector.x, 2);
equal(newVector.y, 4);
});
})();
|
Fix lint issues related to long lines | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
| from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, "Required field `{}` missing from headers.".format(
field)
assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
field, type(headers[field]), typ)
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
field, type(headers[field]), typ)
|
Fix invalid access to CachedObject | import logging
from importer.management.commands._import_base_command import ImportBaseCommand
from importer.models import ExternalList, CachedObject
logger = logging.getLogger(__name__)
class Command(ImportBaseCommand):
help = "Import the objects from an external list of an oparl body"
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"list", choices=["paper", "person", "organization", "meeting"]
)
def handle(self, *args, **options):
importer, body = self.get_importer(options)
body_data = CachedObject.objects.get(url=body.oparl_id)
oparl_id = body_data.data[options["list"]]
if ExternalList.objects.filter(url=oparl_id).exists():
importer.fetch_list_update(oparl_id)
else:
importer.fetch_list_initial(oparl_id)
importer.import_objects()
| import logging
from importer.management.commands._import_base_command import ImportBaseCommand
from importer.models import ExternalList, CachedObject
logger = logging.getLogger(__name__)
class Command(ImportBaseCommand):
help = "Import the objects from an external list of an oparl body"
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"list", choices=["paper", "person", "organization", "meeting"]
)
def handle(self, *args, **options):
importer, body = self.get_importer(options)
body_data = CachedObject.objects.get(url=body.oparl_id)
oparl_id = body_data[options["list"]]
if ExternalList.objects.filter(url=oparl_id).exists():
importer.fetch_list_update(oparl_id)
else:
importer.fetch_list_initial(oparl_id)
importer.import_objects()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.