text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
test: Add cozy-keys-lib exception to transformIgnorePatterns | module.exports = {
testURL: 'http://localhost/',
moduleFileExtensions: ['js', 'jsx', 'json', 'styl'],
setupFiles: ['<rootDir>/test/jestLib/setup.js'],
moduleDirectories: ['src', 'node_modules'],
moduleNameMapper: {
'^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client',
'\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js',
// identity-obj-proxy module is installed by cozy-scripts
'.styl$': 'identity-obj-proxy',
'^cozy-client$': 'cozy-client/dist/index'
},
transformIgnorePatterns: [
'node_modules/(?!cozy-ui|cozy-harvest-lib|cozy-keys-lib)'
],
globals: {
__ALLOW_HTTP__: false,
__TARGET__: 'browser',
__SENTRY_TOKEN__: 'token',
cozy: {}
}
}
| module.exports = {
testURL: 'http://localhost/',
moduleFileExtensions: ['js', 'jsx', 'json', 'styl'],
setupFiles: ['<rootDir>/test/jestLib/setup.js'],
moduleDirectories: ['src', 'node_modules'],
moduleNameMapper: {
'^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client',
'\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js',
// identity-obj-proxy module is installed by cozy-scripts
'.styl$': 'identity-obj-proxy',
'^cozy-client$': 'cozy-client/dist/index'
},
transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'],
globals: {
__ALLOW_HTTP__: false,
__TARGET__: 'browser',
__SENTRY_TOKEN__: 'token',
cozy: {}
}
}
|
Allow to specify output of a chain in the Graph class. | from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN, _output=None):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
if _output:
if not _output in self.nodes:
raise ValueError('Output not found.')
self.outputs_of(_input, create=True).add(self.nodes.index(_output))
return self
def __len__(self):
return len(self.nodes)
| from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
def __len__(self):
return len(self.nodes)
|
Implement conversion of json file to golang map
To try this program, put a valid json file at
$XDG_CONFIG_HOME/matterleast.conf
Then execute this code and you should see it print
the contents of that json file as a golang map, ready
for normal programmatic access. | package main
import (
"encoding/json"
"fmt"
"os"
"path"
)
const BUFFER_SIZE = 1024
// fatal crashes the program if the given error is non-nil
// This isn't a good way to perform production error-handling,
// but it will serve for this demo.
func fatal(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func main() {
xdgConfigPath := os.Getenv("XDG_CONFIG_HOME")
if xdgConfigPath == "" {
home := os.Getenv("HOME")
if home == "" {
fmt.Println("$HOME undefined, aborting...")
os.Exit(1)
}
xdgConfigPath = path.Join(home, ".config")
}
fmt.Println("Config Dir:", xdgConfigPath)
configFile, err := os.Open(path.Join(xdgConfigPath, "matterleast.conf"))
fatal(err)
defer configFile.Close()
data := make([]byte, BUFFER_SIZE)
bytesRead, err := configFile.Read(data)
fatal(err)
config := make(map[string]string)
err = json.Unmarshal(data[:bytesRead], &config)
fatal(err)
fmt.Println(config)
}
| package main
import (
"fmt"
"os"
"path"
)
const BUFFER_SIZE = 1024
// fatal crashes the program if the given error is non-nil
// This isn't a good way to perform production error-handling,
// but it will serve for this demo.
func fatal(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func main() {
xdgConfigPath := os.Getenv("XDG_CONFIG_HOME")
if xdgConfigPath == "" {
home := os.Getenv("HOME")
if home == "" {
fmt.Println("$HOME undefined, aborting...")
os.Exit(1)
}
xdgConfigPath = path.Join(home, ".config")
}
fmt.Println("Config Dir:", xdgConfigPath)
configFile, err := os.Open(path.Join(xdgConfigPath, "matterleast.conf"))
fatal(err)
defer configFile.Close()
data := make([]byte, BUFFER_SIZE)
bytesRead, err := configFile.Read(data)
fatal(err)
}
|
Add ability to "fix" texture
Former-commit-id: ef8268a05c85fdc1f0a3f5af77ceab963bc5f0f3 | import {
RepeatWrapping,
UVMapping,
NearestFilter,
LinearMipMapLinearFilter,
TextureLoader,
Vector2
} from 'three';
const loader = new TextureLoader();
export class TextureModule {
static load(url) {
return new TextureModule({url}).texture;
}
textures = [];
constructor(...textures) {
textures.forEach(({
url,
type = 'map',
offset = new Vector2(0, 0),
repeat = new Vector2(1, 1),
wrap = RepeatWrapping,
mapping = UVMapping,
fix = tex => tex
}) => {
const texture = loader.load(url);
if (wrap.length > 0) {
texture.wrapS = wrap[0];
texture.wrapT = wrap[1];
} else
texture.wrapS = texture.wrapT = wrap;
texture.mapping = mapping;
texture.offset.copy(offset);
texture.repeat.copy(repeat);
texture.magFilter = NearestFilter;
texture.minFilter = LinearMipMapLinearFilter;
this.textures.push([type, fix(texture)]);
});
}
bridge = {
material(material, self) {
self.textures.forEach(texture => {
material[texture[0]] = texture[1];
});
return material;
}
}
}
| import {
RepeatWrapping,
UVMapping,
NearestFilter,
LinearMipMapLinearFilter,
TextureLoader,
Vector2
} from 'three';
const loader = new TextureLoader();
export class TextureModule {
static load(url) {
return new TextureModule({url}).texture;
}
textures = [];
constructor(...textures) {
textures.forEach(({
url,
type = 'map',
offset = new Vector2(0, 0),
repeat = new Vector2(1, 1),
wrap = RepeatWrapping,
mapping = UVMapping
}) => {
const texture = loader.load(url);
if (wrap.length > 0) {
texture.wrapS = wrap[0];
texture.wrapT = wrap[1];
} else
texture.wrapS = texture.wrapT = wrap;
texture.mapping = mapping;
texture.offset.copy(offset);
texture.repeat.copy(repeat);
texture.magFilter = NearestFilter;
texture.minFilter = LinearMipMapLinearFilter;
this.textures.push([type, texture]);
});
}
bridge = {
material(material, self) {
self.textures.forEach(texture => {
material[texture[0]] = texture[1];
});
return material;
}
}
}
|
Change playfield factory method name to create() | package com.graphicsengine.charset;
import java.io.IOException;
import com.graphicsengine.assets.AssetManager;
import com.nucleus.renderer.BaseRenderer;
import com.nucleus.texturing.Texture2D;
/**
* Use to create charmaps from JSON source
*
* @author Richard Sahlin
*
*/
public class PlayfieldFactory {
/**
* Factory method for creating a playfield
*
* @param baseRenderer
* @param constructor
* @return
* @throws IOException
*/
public static Playfield create(BaseRenderer baseRenderer, PlayfieldSetup constructor) throws IOException {
Playfield map = new Playfield(constructor.mapWidth * constructor.mapHeight);
PlayfieldProgram program = new PlayfieldProgram();
baseRenderer.createProgram(program);
Texture2D texture = AssetManager.getInstance().getTexture(baseRenderer, constructor.textureSetup);
map.createMesh(program, texture, constructor.tileWidth, constructor.tileHeight, constructor.zpos,
constructor.textureFramesX, constructor.textureFramesY);
map.setupPlayfield(constructor.mapWidth, constructor.mapHeight, constructor.xpos, constructor.ypos);
map.setPlayfieldData(constructor.data, 0, 0, constructor.data.length);
return map;
}
}
| package com.graphicsengine.charset;
import java.io.IOException;
import com.graphicsengine.assets.AssetManager;
import com.nucleus.renderer.BaseRenderer;
import com.nucleus.texturing.Texture2D;
/**
* Use to create charmaps from JSON source
*
* @author Richard Sahlin
*
*/
public class PlayfieldFactory {
public static Playfield createCharmap(BaseRenderer baseRenderer, PlayfieldSetup constructor) throws IOException {
Playfield map = new Playfield(constructor.mapWidth * constructor.mapHeight);
PlayfieldProgram program = new PlayfieldProgram();
baseRenderer.createProgram(program);
Texture2D texture = AssetManager.getInstance().getTexture(baseRenderer, constructor.textureSource);
map.createMesh(program, texture, constructor.tileWidth, constructor.tileHeight, constructor.zpos,
constructor.textureFramesX, constructor.textureFramesY);
map.setupPlayfield(constructor.mapWidth, constructor.mapHeight, constructor.xpos, constructor.ypos);
map.setPlayfieldData(constructor.data, 0, 0, constructor.data.length);
return map;
}
}
|
Bump to Review Board 1.1alpha1.dev. | # The version of Review Board.
#
# This is in the format of:
#
# (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released)
#
VERSION = (1, 1, 0, 'alpha', 1, False)
def get_version_string():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version += ".%s" % VERSION[2]
if VERSION[3] != 'final':
if VERSION[3] == 'rc':
version += ' RC%s' % VERSION[4]
else:
version += ' %s %s' % (release_tag, VERSION[4])
if not is_release():
version += " (dev)"
return version
def get_package_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version += ".%s" % VERSION[2]
if VERSION[3] != 'final':
version += '%s%s' % (VERSION[3], VERSION[4])
return version
def is_release():
return VERSION[5]
| # The version of Review Board.
#
# This is in the format of:
#
# (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released)
#
VERSION = (1, 0, 0, 'final', 0, True)
def get_version_string():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version += ".%s" % VERSION[2]
if VERSION[3] != 'final':
if VERSION[3] == 'rc':
version += ' RC%s' % VERSION[4]
else:
version += ' %s %s' % (release_tag, VERSION[4])
if not is_release():
version += " (dev)"
return version
def get_package_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version += ".%s" % VERSION[2]
if VERSION[3] != 'final':
version += '%s%s' % (VERSION[3], VERSION[4])
return version
def is_release():
return VERSION[5]
|
Fix modifying of constant functions | 'use strict';
module.exports = toMDAST;
var minify = require('rehype-minify-whitespace')();
var xtend = require('xtend');
var one = require('./one');
var handlers = require('./handlers');
function toMDAST(tree, options) {
var settings = options || {};
h.handlers = xtend(handlers, settings.handlers || {});
h.augment = augment;
return one(h, minify(tree), null);
function h(node, type, props, children) {
var result;
if (!children && ((typeof props === 'object' && 'length' in props) || typeof props === 'string')) {
children = props;
props = {};
}
result = xtend({type: type}, props);
if (typeof children === 'string') {
result.value = children;
} else if (children) {
result.children = children;
}
return augment(node, result);
}
/* `right` is the finalized MDAST node,
* created from `left`, a HAST node */
function augment(left, right) {
if (left.position) {
right.position = left.position;
}
return right;
}
}
| 'use strict';
module.exports = toMDAST;
var minify = require('rehype-minify-whitespace')();
var xtend = require('xtend');
var one = require('./one');
var handlers = require('./handlers');
h.augment = augment;
function toMDAST(tree, options) {
options = options || {};
h.handlers = xtend(handlers, options.handlers || {});
return one(h, minify(tree), null);
}
function h(node, type, props, children) {
var result;
if (!children && ((typeof props === 'object' && 'length' in props) || typeof props === 'string')) {
children = props;
props = {};
}
result = xtend({type: type}, props);
if (typeof children === 'string') {
result.value = children;
} else if (children) {
result.children = children;
}
return augment(node, result);
}
/* `right` is the finalized MDAST node,
* created from `left`, a HAST node */
function augment(left, right) {
if (left.position) {
right.position = left.position;
}
return right;
}
|
Cut a new release to incorporate the HashableDict fix. | # -*- coding: utf-8 -*-
"""The top-level package for ``django-mysqlpool``."""
# These imports make 2 act like 3, making it easier on us to switch to PyPy or
# some other VM if we need to for performance reasons.
from __future__ import (absolute_import, print_function, unicode_literals,
division)
# Make ``Foo()`` work the same in Python 2 as it does in Python 3.
__metaclass__ = type
from functools import wraps
__version__ = "0.2.1"
def auto_close_db(f):
"""Ensure the database connection is closed when the function returns."""
from django.db import connection
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
return wrapper
| # -*- coding: utf-8 -*-
"""The top-level package for ``django-mysqlpool``."""
# These imports make 2 act like 3, making it easier on us to switch to PyPy or
# some other VM if we need to for performance reasons.
from __future__ import (absolute_import, print_function, unicode_literals,
division)
# Make ``Foo()`` work the same in Python 2 as it does in Python 3.
__metaclass__ = type
from functools import wraps
__version__ = "0.2.0"
def auto_close_db(f):
"""Ensure the database connection is closed when the function returns."""
from django.db import connection
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
return wrapper
|
Fix typo in help message. | /*
* Copyright (c) 2015, Facility for Rare Isotope Beams
*
*/
(function() {
function hideCompareButton() {
$('.compare-button').addClass('hidden');
};
function showCompareButton() {
$('.compare-button').removeClass('hidden');
};
function toggleCompareButton() {
var checked = $('.compare-checkbox:checked').length;
if( checked < 2) {
hideCompareButton();
} else if( checked == 2 ) {
showCompareButton();
} else if( checked == 3) {
$(this).prop("checked", false);
alert("Only two Models can be compared.");
}
};
$('#model_name').typeahead({hint:false}, {
source:function(query, syncResults, asyncResults) {
latticemodel.data.find_model_names(query, asyncResults);
},
limit:10
});
$('.compare-checkbox').on("change", toggleCompareButton);
$('a[href="#results"]')
.on('show.bs.tab', toggleCompareButton)
.on('hide.bs.tab', hideCompareButton);
$('.compare-button').on('click', function() {
$('.compare-form').submit();
});
// Initialize compare button because of possible autocomplete.
toggleCompareButton();
})();
| /*
* Copyright (c) 2015, Facility for Rare Isotope Beams
*
*/
(function() {
function hideCompareButton() {
$('.compare-button').addClass('hidden');
};
function showCompareButton() {
$('.compare-button').removeClass('hidden');
};
function toggleCompareButton() {
var checked = $('.compare-checkbox:checked').length;
if( checked < 2) {
hideCompareButton();
} else if( checked == 2 ) {
showCompareButton();
} else if( checked == 3) {
$(this).prop("checked", false);
alert("Only two Lattice can be compared.");
}
};
$('#model_name').typeahead({hint:false}, {
source:function(query, syncResults, asyncResults) {
latticemodel.data.find_model_names(query, asyncResults);
},
limit:10
});
$('.compare-checkbox').on("change", toggleCompareButton);
$('a[href="#results"]')
.on('show.bs.tab', toggleCompareButton)
.on('hide.bs.tab', hideCompareButton);
$('.compare-button').on('click', function() {
$('.compare-form').submit();
});
// Initialize compare button because of possible autocomplete.
toggleCompareButton();
})();
|
Add job id as foreign key to applications table | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateApplicationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('applications', function (Blueprint $table) {
$table->increments('id');
$table->integer('userid')->unsigned();
$table->foreign('userid')->references('id')->on('users')->onDelete('cascade');
$table->integer('employerid')->unsigned();
$table->foreign('employerid')->references('id')->on('employers')->onDelete('cascade');
$table->integer('jobid')->unsigned();
$table->foreign('jobid')->references('id')->on('jobs')->onDelete('cascade');
$table->text('message');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('applications', function (Blueprint $table) {
Schema::dropIfExists('applicants');
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateApplicationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('applications', function (Blueprint $table) {
$table->increments('id');
$table->integer('userid')->unsigned();
$table->foreign('userid')->references('id')->on('users')->onDelete('cascade');
$table->text('coverletter');
$table->integer('employerid')->unsigned();
$table->foreign('employerid')->references('id')->on('employers')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('applications', function (Blueprint $table) {
Schema::dropIfExists('applicants');
});
}
}
|
Disable host on browsersync server | var browserSync = require('browser-sync'),
config = require('./config.json'),
bs;
process.on('message', function(message) {
if (message.type === 'init') {
bs = browserSync.init(null, {
proxy: message.url,
// host: '192.168.56.101',
browser: 'disable',
https: true,
ghostMode: {
clicks: true,
location: true,
forms: true,
scroll: true
}
});
bs.events.on('init', function(api) {
process.send({type: 'browserSyncInit', browserSync: api.options.urls.external});
});
} else if (message.type === 'location') {
bs.io.sockets.emit('location', {url: message.url});
} else {
browserSync.exit();
}
}); | var browserSync = require('browser-sync'),
config = require('./config.json'),
bs;
process.on('message', function(message) {
if (message.type === 'init') {
bs = browserSync.init(null, {
proxy: message.url,
host: '192.168.56.101',
browser: 'disable',
https: true,
ghostMode: {
clicks: true,
location: true,
forms: true,
scroll: true
}
});
bs.events.on('init', function(api) {
process.send({type: 'browserSyncInit', browserSync: api.options.urls.external});
});
} else if (message.type === 'location') {
bs.io.sockets.emit('location', {url: message.url});
} else {
browserSync.exit();
}
}); |
Revert using input event, change seems good enough | "use strict";
if (typeof localStorage !== "undefined"){
for(var key in localStorage){
if (localStorage.hasOwnProperty(key) && key != "debug") exports[key] = localStorage[key];
}
}
exports.register = function(opt, ele, nopersist){
var field = ele.type == "checkbox" ? "checked" : "value";
if (exports[opt]) ele[field] = exports[opt];
if (!nopersist && typeof localStorage !== "undefined"){
ele.addEventListener("change", function() {
if (this[field]){
exports[opt] = localStorage[opt] = this[field];
}else{
delete localStorage[opt];
delete exports[opt];
}
});
}else{
ele.addEventListener("change", function() {
exports[opt] = field == "checked" && !this.checked ? "" : this[field];
});
}
} | "use strict";
if (typeof localStorage !== "undefined"){
for(var key in localStorage){
if (localStorage.hasOwnProperty(key) && key != "debug") exports[key] = localStorage[key];
}
}
exports.register = function(opt, ele, nopersist){
var field = ele.type == "checkbox" ? "checked" : "value";
if (exports[opt]) ele[field] = exports[opt];
if (!nopersist && typeof localStorage !== "undefined"){
ele.addEventListener("input", function() {
if (this[field]){
exports[opt] = localStorage[opt] = this[field];
}else{
delete localStorage[opt];
delete exports[opt];
}
});
}else{
ele.addEventListener("input", function() {
exports[opt] = field == "checked" && !this.checked ? "" : this[field];
});
}
} |
Remove logging and add globals for jshint. | /* global describe, it */
'use strict';
var assert = require('assert'),
Selector = require('./');
describe('Selector', function () {
it('should return an object', function () {
var selector = new Selector('body', [ 0, 0, 0, 1 ]);
assert(selector);
assert.equal(selector.text, 'body');
assert.deepEqual(selector.spec, [ 0, 0, 0, 1 ]);
});
});
describe('Selector.parsed', function () {
it('should get parsed selector', function () {
var selector = new Selector('body');
assert(selector.parsed());
assert.equal(selector.parsed()['0'].tag, 'body');
assert.equal(selector.parsed().length, 1);
});
});
describe('Selector.specificity', function () {
it('should get specificity', function () {
var selector = new Selector('body');
assert.deepEqual(selector.specificity(), [ 0, 0, 0, 1 ]);
});
});
| 'use strict';
var assert = require('assert'),
Selector = require('./');
describe('Selector', function () {
it('should return an object', function () {
var selector = new Selector('body', [ 0, 0, 0, 1 ]);
console.log(selector);
assert(selector);
assert.equal(selector.text, 'body');
assert.deepEqual(selector.spec, [ 0, 0, 0, 1 ]);
});
});
describe('Selector.parsed', function () {
it('should get parsed selector', function () {
var selector = new Selector('body');
console.log(selector.parsed());
assert(selector.parsed());
assert.equal(selector.parsed()['0'].tag, 'body');
assert.equal(selector.parsed().length, 1);
});
});
describe('Selector.specificity', function () {
it('should get specificity', function () {
var selector = new Selector('body');
console.log(selector.specificity());
assert.deepEqual(selector.specificity(), [ 0, 0, 0, 1 ]);
});
});
|
Throw 500 error on multiple account in LocaleMiddleware so we can fix them. | from django.utils.cache import patch_vary_headers
from django.utils import translation
from account.models import Account
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context depending on the user's account. This allows pages
to be dynamically translated to the language the user desires
(if the language is available, of course).
"""
def get_language_for_user(self, request):
if request.user.is_authenticated():
try:
account = Account.objects.get(user=request.user)
return account.language
except Account.DoesNotExist:
pass
return translation.get_language_from_request(request)
def process_request(self, request):
translation.activate(self.get_language_for_user(request))
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
| from django.utils.cache import patch_vary_headers
from django.utils import translation
from account.models import Account
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context depending on the user's account. This allows pages
to be dynamically translated to the language the user desires
(if the language is available, of course).
"""
def get_language_for_user(self, request):
if request.user.is_authenticated():
try:
account = Account.objects.get(user=request.user)
return account.language
except (Account.DoesNotExist, Account.MultipleObjectsReturned):
pass
return translation.get_language_from_request(request)
def process_request(self, request):
translation.activate(self.get_language_for_user(request))
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
|
Remove MIN_DELAY bc a default setting is guaranteed | from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay')
queue = Daemon()
| from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
MIN_DELAY = 0.1
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay', MIN_DELAY)
queue = Daemon()
|
Add /multimeter/ to robots.txt exclusion
We don't need search engines indexing /multimeter, it's unwanted load
and not at all useful. (It's also filling up the logs, currently)
Bug: T109247
Change-Id: I8d991f52b59219501982366738dfaab4ff6e7b43 | <?php
final class PhabricatorRobotsController extends PhabricatorController {
public function shouldRequireLogin() {
return false;
}
public function processRequest() {
$out = array();
// Prevent indexing of '/diffusion/', since the content is not generally
// useful to index, web spiders get stuck scraping the history of every
// file, and much of the content is Ajaxed in anyway so spiders won't even
// see it. These pages are also relatively expensive to generate.
// Note that this still allows commits (at '/rPxxxxx') to be indexed.
// They're probably not hugely useful, but suffer fewer of the problems
// Diffusion suffers and are hard to omit with 'robots.txt'.
$out[] = 'User-Agent: *';
$out[] = 'Disallow: /diffusion/';
$out[] = 'Disallow: /multimeter/';
// Add a small crawl delay (number of seconds between requests) for spiders
// which respect it. The intent here is to prevent spiders from affecting
// performance for users. The possible cost is slower indexing, but that
// seems like a reasonable tradeoff, since most Phabricator installs are
// probably not hugely concerned about cutting-edge SEO.
$out[] = 'Crawl-delay: 1';
$content = implode("\n", $out)."\n";
return id(new AphrontPlainTextResponse())
->setContent($content)
->setCacheDurationInSeconds(phutil_units('2 hours in seconds'));
}
}
| <?php
final class PhabricatorRobotsController extends PhabricatorController {
public function shouldRequireLogin() {
return false;
}
public function processRequest() {
$out = array();
// Prevent indexing of '/diffusion/', since the content is not generally
// useful to index, web spiders get stuck scraping the history of every
// file, and much of the content is Ajaxed in anyway so spiders won't even
// see it. These pages are also relatively expensive to generate.
// Note that this still allows commits (at '/rPxxxxx') to be indexed.
// They're probably not hugely useful, but suffer fewer of the problems
// Diffusion suffers and are hard to omit with 'robots.txt'.
$out[] = 'User-Agent: *';
$out[] = 'Disallow: /diffusion/';
// Add a small crawl delay (number of seconds between requests) for spiders
// which respect it. The intent here is to prevent spiders from affecting
// performance for users. The possible cost is slower indexing, but that
// seems like a reasonable tradeoff, since most Phabricator installs are
// probably not hugely concerned about cutting-edge SEO.
$out[] = 'Crawl-delay: 1';
$content = implode("\n", $out)."\n";
return id(new AphrontPlainTextResponse())
->setContent($content)
->setCacheDurationInSeconds(phutil_units('2 hours in seconds'));
}
}
|
Include a space after a return if an expression is used. | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.jdeparser;
import static org.jboss.jdeparser.Tokens.*;
import java.io.IOException;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
class KeywordExprJStatement extends KeywordJStatement {
private final JExpr expr;
KeywordExprJStatement(final $KW keyword, final JExpr expr) {
super(keyword);
this.expr = expr;
}
JExpr getExpression() {
return expr;
}
public void write(final SourceFileWriter writer) throws IOException {
writeComments(writer);
writer.write(getKeyword());
writer.sp();
writer.write(expr);
writer.write($PUNCT.SEMI);
}
}
| /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.jdeparser;
import static org.jboss.jdeparser.Tokens.*;
import java.io.IOException;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
class KeywordExprJStatement extends KeywordJStatement {
private final JExpr expr;
KeywordExprJStatement(final $KW keyword, final JExpr expr) {
super(keyword);
this.expr = expr;
}
JExpr getExpression() {
return expr;
}
public void write(final SourceFileWriter writer) throws IOException {
writeComments(writer);
writer.write(getKeyword());
writer.write(expr);
writer.write($PUNCT.SEMI);
}
}
|
Revert changes to helloworld example | # Copyright 2015 gRPC 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.
"""The Python implementation of the GRPC helloworld.Greeter server."""
from concurrent import futures
import time
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
logging.basicConfig()
serve()
| # Copyright 2015 gRPC 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.
"""The Python implementation of the GRPC helloworld.Greeter server."""
from concurrent import futures
import time
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()
|
Fix how parseCommand sends arguments to Command class | const {exec} = require('child_process')
const Command = exports.Command = require('./command')
const Response = exports.Response = require('./response')
const Controller = exports.Controller = require('./controller')
// System paths are not inherited in macOS
// This is a quick & dirty fix
if (process.platform === 'darwin') {
exec('/bin/bash -ilc "env; exit"', (err, result) => {
if (err) return
process.env.PATH = result.trim().split('\n')
.map(x => x.split('='))
.find(x => x[0] === 'PATH')[1]
})
}
exports.parseCommand = function(input) {
input = input.replace(/\t/g, ' ').trim()
let inputs = input.split(' ').filter(x => x !== '')
let id = parseFloat(inputs[0])
if (!isNaN(id)) inputs.shift()
else id = null
let name = inputs[0]
inputs.shift()
return new Command(id, name, ...inputs)
}
exports.parseResponse = function(input) {
input = input.replace(/\t/g, ' ').trim()
let error = input[0] !== '='
let hasId = input.length >= 2 && input[1] !== ' '
input = input.substr(1)
let id = hasId ? +input.split(' ')[0] : null
if (hasId) input = input.substr((id + '').length)
return new Response(id, input.substr(1), error)
}
| const {exec} = require('child_process')
const Command = exports.Command = require('./command')
const Response = exports.Response = require('./response')
const Controller = exports.Controller = require('./controller')
// System paths are not inherited in macOS
// This is a quick & dirty fix
if (process.platform === 'darwin') {
exec('/bin/bash -ilc "env; exit"', (err, result) => {
if (err) return
process.env.PATH = result.trim().split('\n')
.map(x => x.split('='))
.find(x => x[0] === 'PATH')[1]
})
}
exports.parseCommand = function(input) {
input = input.replace(/\t/g, ' ').trim()
let inputs = input.split(' ').filter(x => x !== '')
let id = parseFloat(inputs[0])
if (!isNaN(id)) inputs.shift()
else id = null
let name = inputs[0]
inputs.shift()
return new Command(id, name, inputs)
}
exports.parseResponse = function(input) {
input = input.replace(/\t/g, ' ').trim()
let error = input[0] !== '='
let hasId = input.length >= 2 && input[1] !== ' '
input = input.substr(1)
let id = hasId ? +input.split(' ')[0] : null
if (hasId) input = input.substr((id + '').length)
return new Response(id, input.substr(1), error)
}
|
Tidy types
Make class final and remove unused ctor/setter
git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@804702 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: a37b5f7b7d8cc52c9947bc15230d1a7f0e972d06 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.jmeter.testelement.property;
import java.util.Collection;
import java.util.Iterator;
public class PropertyIteratorImpl implements PropertyIterator {
private final Iterator<JMeterProperty> iter;
public PropertyIteratorImpl(Collection<JMeterProperty> value) {
iter = value.iterator();
}
/** {@inheritDoc} */
public boolean hasNext() {
return iter.hasNext();
}
/** {@inheritDoc} */
public JMeterProperty next() {
return iter.next();
}
/** {@inheritDoc} */
public void remove() {
iter.remove();
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.jmeter.testelement.property;
import java.util.Collection;
import java.util.Iterator;
public class PropertyIteratorImpl implements PropertyIterator {
Iterator iter;
public PropertyIteratorImpl(Collection value) {
iter = value.iterator();
}
public PropertyIteratorImpl() {
}
public void setCollection(Collection value) {
iter = value.iterator();
}
public boolean hasNext() {
return iter.hasNext();
}
public JMeterProperty next() {
return (JMeterProperty) iter.next();
}
/**
* @see org.apache.jmeter.testelement.property.PropertyIterator#remove()
*/
public void remove() {
iter.remove();
}
}
|
Change default language to zh-CN | 'use strict';
export default function($translateProvider, $mdIconProvider) {
'ngInject';
// put your common app configurations here
// register icons from outsides
$mdIconProvider
.icon('icon-navigate-first', 'assets/icons/navigate-first.svg', 24)
.icon('icon-navigate-last', 'assets/icons/navigate-last.svg', 24)
.icon('icon-navigate-next', 'assets/icons/navigate-next.svg', 24)
.icon('icon-navigate-previous', 'assets/icons/navigate-previous.svg', 24);
// angular-translate configuration
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '{part}/i18n/{lang}.json'
});
// tell the module what language to use by default
$translateProvider.preferredLanguage('zh');
// tell the module to store the language in the cookies
$translateProvider.useCookieStorage();
$translateProvider.useSanitizeValueStrategy('sce');
}
| 'use strict';
export default function($translateProvider, $mdIconProvider) {
'ngInject';
// put your common app configurations here
// register icons from outsides
$mdIconProvider
.icon('icon-navigate-first', 'assets/icons/navigate-first.svg', 24)
.icon('icon-navigate-last', 'assets/icons/navigate-last.svg', 24)
.icon('icon-navigate-next', 'assets/icons/navigate-next.svg', 24)
.icon('icon-navigate-previous', 'assets/icons/navigate-previous.svg', 24);
// angular-translate configuration
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '{part}/i18n/{lang}.json'
});
// tell the module what language to use by default
$translateProvider.preferredLanguage('en');
// tell the module to store the language in the cookies
$translateProvider.useCookieStorage();
$translateProvider.useSanitizeValueStrategy('sce');
}
|
chore(pins): Update to dictionary release tag
- Update to dictionary release tag | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.14.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
| from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@release/jibboo#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
Replace console.log to process.stdout to write without formatting | 'use strict'
module.exports = function insertInit (showErrors, showStdout) {
var callback
if (showErrors && showStdout) {
callback = function (e, result) {
if (e) {
console.error(e)
return
}
process.stdout.write(JSON.stringify(result.ops[0]) + '\n')
}
} else if (showErrors && !showStdout) {
callback = function (e) {
if (e) {
console.error(e)
}
}
} else if (!showErrors && showStdout) {
callback = function (e, result) {
process.stdout.write(JSON.stringify(result.ops[0]) + '\n')
}
}
return function insert (collection, log) {
collection.insertOne(log, {
forceServerObjectId: true
}, callback)
}
}
| 'use strict'
module.exports = function insertInit (showErrors, showStdout) {
var callback
if (showErrors && showStdout) {
callback = function (e, result) {
if (e) {
console.error(e)
return
}
console.log(JSON.stringify(result.ops[0]))
}
} else if (showErrors && !showStdout) {
callback = function (e) {
if (e) {
console.error(e)
}
}
} else if (!showErrors && showStdout) {
callback = function (e, result) {
console.log(JSON.stringify(result.ops[0]))
}
}
return function insert (collection, log) {
collection.insertOne(log, {
forceServerObjectId: true
}, callback)
}
}
|
Extend list of error codes treated as out-of-memory | /*
* 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.trino.execution.scheduler;
import io.trino.spi.ErrorCode;
import static io.trino.spi.StandardErrorCode.CLUSTER_OUT_OF_MEMORY;
import static io.trino.spi.StandardErrorCode.EXCEEDED_GLOBAL_MEMORY_LIMIT;
import static io.trino.spi.StandardErrorCode.EXCEEDED_LOCAL_MEMORY_LIMIT;
public final class ErrorCodes
{
private ErrorCodes() {}
public static boolean isOutOfMemoryError(ErrorCode errorCode)
{
return EXCEEDED_LOCAL_MEMORY_LIMIT.toErrorCode().equals(errorCode)
|| EXCEEDED_GLOBAL_MEMORY_LIMIT.toErrorCode().equals(errorCode)
|| CLUSTER_OUT_OF_MEMORY.toErrorCode().equals(errorCode);
}
}
| /*
* 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.trino.execution.scheduler;
import io.trino.spi.ErrorCode;
import static io.trino.spi.StandardErrorCode.CLUSTER_OUT_OF_MEMORY;
import static io.trino.spi.StandardErrorCode.EXCEEDED_LOCAL_MEMORY_LIMIT;
public final class ErrorCodes
{
private ErrorCodes() {}
public static boolean isOutOfMemoryError(ErrorCode errorCode)
{
return EXCEEDED_LOCAL_MEMORY_LIMIT.toErrorCode().equals(errorCode) // too many tasks from single query on a node
|| CLUSTER_OUT_OF_MEMORY.toErrorCode().equals(errorCode); // too many tasks in general on a node
}
}
|
Fix the warning when the immutable reducer is used when immutable.js isn't installed. |
import warning from 'warning';
import createReducer from './utils/createReducer';
import {
SHOW,
REPLACE,
DISMISS,
} from './actions';
let reducer; // eslint-disable-line import/no-mutable-exports
try {
const fromJS = require('immutable').fromJS; // eslint-disable-line global-require
const initialState = fromJS({
show: false,
title: '',
});
reducer = createReducer(initialState, {
[SHOW]: (state, { payload }) => fromJS({
show: true,
...payload,
}),
[REPLACE]: (state, { payload }) => fromJS({
...state,
...payload,
}),
[DISMISS]: () => initialState,
});
} catch (error) {
reducer = () => {
warning(false, 'You must install immutable-js for the immutable reducer to work!');
};
}
export default reducer;
|
import warning from 'warning';
import createReducer from './utils/createReducer';
import {
SHOW,
REPLACE,
DISMISS,
} from './actions';
let reducer; // eslint-disable-line import/no-mutable-exports
try {
const fromJS = require('immutable').fromJS; // eslint-disable-line global-require
const initialState = fromJS({
show: false,
title: '',
});
reducer = createReducer(initialState, {
[SHOW]: (state, { payload }) => fromJS({
show: true,
...payload,
}),
[REPLACE]: (state, { payload }) => fromJS({
...state,
...payload,
}),
[DISMISS]: () => initialState,
});
} catch (error) {
reducer = () => {
warning('You must install immutable-js for the immutable reducer to work!');
};
}
export default reducer;
|
Use the Correct Deprecation Error Type | <?php declare(strict_types=1);
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue;
@trigger_error(sprintf(
'The "%s" trait is deprecated since pmg/queue 5.0, a message\'s FQCN as the message name is the default in 5.0',
MessageTrait::class
), E_USER_DEPRECATED);
/**
* ABC for messages, implements `getName` as the class name.
*
* @since 2015-06-11
*/
trait MessageTrait
{
/**
* @see NamedMessage::getName
*/
public function getName() : string
{
return get_class($this);
}
}
| <?php declare(strict_types=1);
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue;
@trigger_error(sprintf('The "%s" trait is deprecated since pmg/queue 5.0, a message\'s FQCN as the message name is the default in 5.0', MessageTrait::class));
/**
* ABC for messages, implements `getName` as the class name.
*
* @since 2015-06-11
*/
trait MessageTrait
{
/**
* @see NamedMessage::getName
*/
public function getName() : string
{
return get_class($this);
}
}
|
Add missing reference to covistra system | /**
Copyright 2015 Covistra Technologies Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
var P = require('bluebird');
exports.register = function (server, options, next) {
server.dependency(['covistra-socket'], function(plugin, done) {
plugin.log(['plugin', 'info'], "Registering the messaging plugin");
var Router = server.plugins['covistra-system'].Router;
var config = server.plugins['hapi-config'].CurrentConfiguration;
var systemLog = server.plugins['covistra-system'].systemLog;
// Expose our services
plugin.expose('channelManager', require('./lib/channel-manager')(config, server, systemLog.child({service:'channel-manager'})));
plugin.expose('workerService', require('./lib/worker-service')(config, server, systemLog.child({service:'worker-service'})));
// Register routes
Router.routes(plugin, __dirname, "./routes");
done();
});
next();
};
exports.register.attributes = {
pkg: require(__dirname + '/package.json')
};
| /**
Copyright 2015 Covistra Technologies Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
var P = require('bluebird');
exports.register = function (server, options, next) {
server.dependency(['covistra-socket'], function(plugin, done) {
plugin.log(['plugin', 'info'], "Registering the messaging plugin");
var Router = server.plugins['covistra-system'].Router;
var config = server.plugins['hapi-config'].CurrentConfiguration;
var systemLog = server.plugins['system'].systemLog;
// Expose our services
plugin.expose('channelManager', require('./lib/channel-manager')(config, server, systemLog.child({service:'channel-manager'})));
plugin.expose('workerService', require('./lib/worker-service')(config, server, systemLog.child({service:'worker-service'})));
// Register routes
Router.routes(plugin, __dirname, "./routes");
done();
});
next();
};
exports.register.attributes = {
pkg: require(__dirname + '/package.json')
};
|
Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2. | from __future__ import absolute_import
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
from os import RTLD_NOW, RTLD_GLOBAL
except ImportError:
from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7
dlopen_flags = RTLD_NOW | RTLD_GLOBAL
import sys
old_flags = sys.getdlopenflags()
try:
sys.setdlopenflags(dlopen_flags)
import lupa._lupa
finally:
sys.setdlopenflags(old_flags)
try:
_try_import_with_global_library_symbols()
except:
pass
del _try_import_with_global_library_symbols
# the following is all that should stay in the namespace:
from lupa._lupa import *
try:
from lupa.version import __version__
except ImportError:
pass
|
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
import DLFCN
dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL
except ImportError:
import ctypes
dlopen_flags = ctypes.RTLD_GLOBAL
import sys
old_flags = sys.getdlopenflags()
try:
sys.setdlopenflags(dlopen_flags)
import lupa._lupa
finally:
sys.setdlopenflags(old_flags)
try:
_try_import_with_global_library_symbols()
except:
pass
del _try_import_with_global_library_symbols
# the following is all that should stay in the namespace:
from lupa._lupa import *
try:
from lupa.version import __version__
except ImportError:
pass
|
Fix Bandzone playing state recognition
Resolves #819. | 'use strict';
/* global Connector */
if (location.href === 'http://bandzone.cz/' || location.href === 'https://bandzone.cz/') {
Connector.playerSelector = '#stats';
Connector.getArtist = function () {
var text = $('.stat:has(.ui-miniaudioplayer-state-playing) h4').text().trim();
return text || null;
};
Connector.getTrack = function () {
var text = $('.stat:has(.ui-miniaudioplayer-state-playing) .songTitle').text().trim();
return text || null;
};
Connector.isPlaying = function () {
return $('.ui-miniaudioplayer-state-playing').length;
};
} else {
Connector.playerSelector = '#playerWidget';
Connector.getArtist = function () {
var text = $('.profile-name h1').text().replace($('.profile-name span').text(), '').trim();
return text || null;
};
Connector.trackSelector = '.ui-state-active .ui-audioplayer-song-title';
Connector.isPlaying = function () {
return $('.ui-audioplayer-button').text() === 'stop';
};
}
| 'use strict';
/* global Connector */
if (location.href === 'http://bandzone.cz/' || location.href === 'https://bandzone.cz/') {
Connector.playerSelector = '#stats';
Connector.getArtist = function () {
var text = $('.stat:has(.ui-miniaudioplayer-state-playing) h4').text().trim();
return text || null;
};
Connector.getTrack = function () {
var text = $('.stat:has(.ui-miniaudioplayer-state-playing) .songTitle').text().trim();
return text || null;
};
Connector.isPlaying = function () {
return $('.ui-miniaudioplayer-state-playing').length;
};
} else {
Connector.playerSelector = '#playerWidget';
Connector.getArtist = function () {
var text = $('.profile-name h1').text().replace($('.profile-name span').text(), '').trim();
return text || null;
};
Connector.trackSelector = '.ui-state-active .ui-audioplayer-song-title';
Connector.isPlaying = function () {
return $('ui-audioplayer-button').text() === 'stop';
};
}
|
Add congress to service_available group
Add congress to service_available group. used in tempest plugin
to check if service is available or not
Change-Id: Ia3edbb545819d76a6563ee50c2dcdad6013f90e9 | # Copyright 2015 Intel Corp
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from tempest import config # noqa
service_available_group = cfg.OptGroup(name="service_available",
title="Available OpenStack Services")
ServiceAvailableGroup = [
cfg.BoolOpt('congress',
default=True,
help="Whether or not Congress is expected to be available"),
]
congressha_group = cfg.OptGroup(name="congressha", title="Congress HA Options")
CongressHAGroup = [
cfg.StrOpt("replica_type",
default="policyha",
help="service type used to create a replica congress server."),
cfg.IntOpt("replica_port",
default=4001,
help="The listening port for a replica congress server. "),
]
| # Copyright 2015 Intel Corp
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from tempest import config # noqa
congressha_group = cfg.OptGroup(name="congressha", title="Congress HA Options")
CongressHAGroup = [
cfg.StrOpt("replica_type",
default="policyha",
help="service type used to create a replica congress server."),
cfg.IntOpt("replica_port",
default=4001,
help="The listening port for a replica congress server. "),
]
|
Use npm view to get all nested dependencies | 'use strict';
var execSync = require('child_process').execSync;
var dependencies = require('../../package.json').dependencies;
var dependencyNames = Object.keys(dependencies);
var dependencyPackages = dependencyNames.map(function (depName) {
var depPackages = {};
var depVersion = dependencies[depName];
var cmd = 'npm view --json ' + depName + '@' + depVersion + ' dependencies';
var result = execSync(cmd).toString();
if (result) {
depPackages = JSON.parse(result);
}
return {
name: depName,
dependencies: depPackages
};
});
describe('Shared dependency', function () {
dependencyPackages.forEach(function (depPkg) {
describe(depPkg.name, function () {
var sharedDependencyNames = Object.keys(depPkg.dependencies).filter(function (d) {
return dependencyNames.indexOf(d) !== -1;
});
sharedDependencyNames.forEach(function (sharedDepName) {
var sharedDepVersion = depPkg.dependencies[sharedDepName];
it('uses ' + sharedDepName + '@' + sharedDepVersion, function () {
var dependencyVersion = dependencies[sharedDepName];
if (sharedDepVersion !== dependencyVersion) {
throw new Error(depPkgName + ' should be using ' + sharedDepName + '@' + dependencyVersion + ' but was ' + sharedDepVersion);
}
});
});
});
});
});
| 'use strict';
var dependencies = require('../../package.json').dependencies;
var dependencyNames = Object.keys(dependencies);
var packages = dependencyNames.filter(function (d) {
// Remove scoped packages
return d[0] !== '@';
});
describe('Shared dependency', function () {
packages.forEach(function (pkgName) {
describe(pkgName, function () {
var pkgDependencies = require('../../node_modules/' + pkgName + '/package.json').dependencies;
var sharedDependencyNames = Object.keys(pkgDependencies).filter(function (d) {
return dependencyNames.indexOf(d) !== -1;
});
sharedDependencyNames.forEach(function (sharedDepName) {
var sharedDepVersion = pkgDependencies[sharedDepName];
it('uses ' + sharedDepName + '@' + sharedDepVersion, function () {
var dependencyVersion = dependencies[sharedDepName];
if (sharedDepVersion !== dependencyVersion) {
throw new Error(pkgName + ' should be using ' + sharedDepName + '@' + dependencyVersion + ' but was ' + sharedDepVersion);
}
});
});
});
});
});
|
Change file.src to filesSrc for grunt 0.4.0rc5.
See https://github.com/gruntjs/grunt/issues/606 | /*
* grunt-ember-handlebars
* https://github.com/yaymukund/grunt-ember-handlebars
*
* Copyright (c) 2012 Mukund Lakshman
* Licensed under the MIT license.
*
* A grunt task that precompiles Ember.js Handlebars templates into
* separate .js files of the same name. This script expects the
* following setup:
*
* tasks/
* ember-templates.js
* lib/
* headless-ember.js
* ember.js
*
* headless-ember and ember.js can both be found in the main Ember repo:
* https://github.com/emberjs/ember.js/tree/master/lib
*/
var precompiler = require('./lib/precompiler'),
path = require('path');
module.exports = function(grunt) {
grunt.registerMultiTask('ember_handlebars', 'Precompile Ember Handlebars templates', function() {
// Precompile each file and write it to the output directory.
grunt.util._.forEach(this.filesSrc.map(path.resolve), function(file) {
grunt.log.write('Precompiling "' + file + '" to "' + this.dest + '"\n');
var compiled = precompiler.precompile(file);
out = path.join(this.dest, compiled.filename);
grunt.file.write(out, compiled.src, 'utf8');
}, {dest: this.file.dest});
});
};
| /*
* grunt-ember-handlebars
* https://github.com/yaymukund/grunt-ember-handlebars
*
* Copyright (c) 2012 Mukund Lakshman
* Licensed under the MIT license.
*
* A grunt task that precompiles Ember.js Handlebars templates into
* separate .js files of the same name. This script expects the
* following setup:
*
* tasks/
* ember-templates.js
* lib/
* headless-ember.js
* ember.js
*
* headless-ember and ember.js can both be found in the main Ember repo:
* https://github.com/emberjs/ember.js/tree/master/lib
*/
var precompiler = require('./lib/precompiler'),
path = require('path');
module.exports = function(grunt) {
grunt.registerMultiTask('ember_handlebars', 'Precompile Ember Handlebars templates', function() {
// Precompile each file and write it to the output directory.
grunt.util._.forEach(this.file.src.map(path.resolve), function(file) {
grunt.log.write('Precompiling "' + file + '" to "' + this.dest + '"\n');
var compiled = precompiler.precompile(file);
out = path.join(this.dest, compiled.filename);
grunt.file.write(out, compiled.src, 'utf8');
}, {dest: this.file.dest});
});
};
|
Fix attempt: version specifier ~= is not supported on older installations of pip | #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
assert sys.version_info >= (2, 6), 'We only support Python 2.6+'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'asana'))
setup(
name='asana',
version='0.6.2',
description='Asana API client',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
install_requires=[
'requests >=2.9.1, == 2.9.*',
'requests_oauthlib >= 0.6.1, == 0.6.*',
'six >= 1.10.0, == 1.10.*'
],
author='Asana, Inc',
# author_email='',
url='http://github.com/asana/python-asana',
packages=find_packages(exclude=('tests',)),
keywords='asana',
zip_safe=True,
test_suite='tests')
| #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages
assert sys.version_info >= (2, 6), 'We only support Python 2.6+'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'asana'))
setup(
name='asana',
version='0.6.2',
description='Asana API client',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
install_requires=[
'requests~=2.9.1',
'requests_oauthlib~=0.6.1',
'six~=1.10.0'
],
author='Asana, Inc',
# author_email='',
url='http://github.com/asana/python-asana',
packages=find_packages(exclude=('tests',)),
keywords='asana',
zip_safe=True,
test_suite='tests')
|
Allow customizing filename field in parts | var uuid = require('node-uuid');
var CRLF = '\r\n';
function generate(tuples, options) {
options = options || {};
var boundary = options.boundary || uuid();
var headers = [
'From: ' + (options.from || ('nobody ' + Date())),
'MIME-Version: 1.0',
'Content-Type:multipart/mixed; boundary=' + boundary
];
var delimiter = CRLF + '--' + boundary;
var closeDelimiter = delimiter + '--';
var parts = tuples.map(function(tuple, i) {
var mimetype = tuple.mime || 'text/plain';
var encoding = tuple.encoding || 'utf8';
var filename = tuple.filename || ('file' + i);
var fileHeaders = [
'MIME-Version: 1.0',
'Content-Type: ' + mimetype + '; charset="' + encoding + '"',
'Content-Transfer-Encoding: 7bit',
'Content-Disposition: attachment; filename="' + filename + '"'
].join(CRLF);
return [delimiter, fileHeaders, tuple.content, closeDelimiter].join(CRLF);
});
return [headers.join(CRLF), parts].join(CRLF);
}
module.exports = {
generate: generate
};
| var uuid = require('node-uuid');
var CRLF = '\r\n';
function generate(tuples, options) {
options = options || {};
var boundary = options.boundary || uuid();
var headers = [
'From: ' + (options.from || ('nobody ' + Date())),
'MIME-Version: 1.0',
'Content-Type:multipart/mixed; boundary=' + boundary
];
var delimiter = CRLF + '--' + boundary;
var closeDelimiter = delimiter + '--';
var parts = tuples.map(function(tuple, i) {
var mimetype = tuple.mime || 'text/plain';
var encoding = tuple.encoding || 'utf8';
var fileHeaders = [
'MIME-Version: 1.0',
'Content-Type: ' + mimetype + '; charset="' + encoding + '"',
'Content-Transfer-Encoding: 7bit',
'Content-Disposition: attachment; filename="file' + i + '"'
].join(CRLF);
return [delimiter, fileHeaders, tuple.content, closeDelimiter].join(CRLF);
});
return [headers.join(CRLF), parts].join(CRLF);
}
module.exports = {
generate: generate
};
|
Add test for empty string; cleanup | ''' Tests for BaseUtils
'''
import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
''' Main test class for the BaseUtils '''
def test_word_segmenter_with_empty(self):
''' For an empty string, the segmenter returns
just an empty list '''
segments = BaseUtils.get_words('')
self.assertEqual(segments, [])
def test_word_segmenter(self):
''' The word segmenter returns the expected
array of strings '''
segments = BaseUtils.get_words('this is a random sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
def test_ignoring_whitespace(self):
''' Whitespace in the input string is ignored
in the input string '''
segments = BaseUtils.get_words('this is a random sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
def test_ignoring_special_chars(self):
''' If there are special characters in the input,
they are ignored as well '''
segments = BaseUtils.get_words('this is $$%%a random --00sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
if __name__ == '__main__':
unittest.main()
| import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
def test_word_segmenter(self):
segments = BaseUtils.get_words('this is a random sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
def test_word_segmenter_ignores_whitespace(self):
segments = BaseUtils.get_words('this is a random sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
def test_word_segmenter_ignores_special_chars(self):
segments = BaseUtils.get_words('this is $$%%a random --00sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
if __name__ == '__main__':
unittest.main()
|
Set correct size for window. | package com.salcedo.rapbot.keyboard;
import akka.actor.ActorRef;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import javax.swing.*;
public class KeyEventSource implements EventSource {
@Override
public void listen(ActorRef actor) {
JFrame frame = new JFrame("RapBot");
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(new KeyEventForwarder(actor));
frame.setBounds(100, 100, 640, 480);
frame.setContentPane(mediaPlayerComponent);
frame.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia("http://192.168.1.41:3001/stream.mjpg");
}
}
| package com.salcedo.rapbot.keyboard;
import akka.actor.ActorRef;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.media.callback.seekable.RandomAccessFileMedia;
import javax.swing.*;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
public class KeyEventSource implements EventSource {
@Override
public void listen(ActorRef actor) {
JFrame frame = new JFrame("RapBot");
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(new KeyEventForwarder(actor));
frame.setBounds(100, 100, 600, 400);
frame.setContentPane(mediaPlayerComponent);
frame.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia("http://192.168.1.41:3001/stream.mjpg");
}
}
|
Allow to retrieve component from View | package com.github.aleksandermielczarek.napkin;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.View;
/**
* Created by Aleksander Mielczarek on 14.05.2016.
*/
public class Napkin {
private Napkin() {
}
@SuppressWarnings("unchecked")
public static <T> T provideComponent(Object object) {
ComponentProvider<T> componentProvider = (ComponentProvider<T>) object;
return componentProvider.provideComponent();
}
public static <T> T provideAppComponent(Context context) {
Context application = context.getApplicationContext();
return provideComponent(application);
}
public static <T> T provideAppComponent(Fragment fragment) {
Context context = fragment.getContext();
return provideAppComponent(context);
}
public static <T> T provideAppComponent(View view) {
Context context = view.getContext();
return provideAppComponent(context);
}
public static <T> T provideActivityComponent(Fragment fragment) {
Context activity = fragment.getActivity();
return provideComponent(activity);
}
public static <T> T provideActivityComponent(View view) {
Context activity = view.getContext();
return provideComponent(activity);
}
}
| package com.github.aleksandermielczarek.napkin;
import android.content.Context;
import android.support.v4.app.Fragment;
/**
* Created by Aleksander Mielczarek on 14.05.2016.
*/
public class Napkin {
private Napkin() {
}
public static <T> T provideComponent(Object object) {
ComponentProvider<T> componentProvider = (ComponentProvider<T>) object;
return componentProvider.provideComponent();
}
public static <T> T provideAppComponent(Context context) {
Context application = context.getApplicationContext();
return provideComponent(application);
}
public static <T> T provideAppComponent(Fragment fragment) {
Context application = fragment.getContext().getApplicationContext();
return provideComponent(application);
}
public static <T> T provideActivityComponent(Fragment fragment) {
Context activity = fragment.getActivity();
return provideComponent(activity);
}
}
|
Set a micropub token when not in production | <?php
namespace App\Providers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
class MicropubSessionProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//allow micropub use in development
if (config('app.env') !== 'production') {
session(['me' => env('APP_URL')]);
if (Storage::exists('dev-token')) {
session(['token' => Storage::get('dev-token')]);
}
}
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
| <?php
namespace App\Providers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
class MicropubSessionProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//allow micropub use in development
if (env('APP_DEBUG') == true) {
session(['me' => env('APP_URL')]);
if (Storage::exists('dev-token')) {
session(['token' => Storage::get('dev-token')]);
}
}
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
|
Remove possibly risky update query
While fixing a default value bug[1] for the email verification
configuration option, the additional UPDATE query in the migration
(Version20180330094402) was not removed. This is risky and not necessary
as the default value is set in the ALTER TABLE and the column is not
nullable.
This issue was identified during review of the changes described in the
associated PR. The fix for this migration was boyscouted.
See:
1. https://github.com/OpenConext/Stepup-Middleware/pull/215 | <?php
namespace Surfnet\StepupMiddleware\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20180330094402 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE institution_configuration_options CHANGE verify_email_option verify_email_option TINYINT(1) DEFAULT \'1\' NOT NULL');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE institution_configuration_options CHANGE verify_email_option verify_email_option TINYINT(1) NOT NULL');
}
}
| <?php
namespace Surfnet\StepupMiddleware\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20180330094402 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE institution_configuration_options CHANGE verify_email_option verify_email_option TINYINT(1) DEFAULT \'1\' NOT NULL');
$this->addSql('UPDATE institution_configuration_options SET verify_email_option = 1');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE institution_configuration_options CHANGE verify_email_option verify_email_option TINYINT(1) NOT NULL');
}
}
|
[Parser] Add more patterns for future use | package seedu.address.logic.parser;
import java.util.regex.Pattern;
import seedu.address.logic.parser.ArgumentTokenizer.Prefix;
/**
* Contains Command Line Interface (CLI) syntax definitions common to multiple commands
*/
public class CliSyntax {
/* Prefix definitions */
public static final Prefix PREFIX_NAME = new Prefix("n/");
public static final Prefix PREFIX_DATE = new Prefix("due/");
public static final Prefix PREFIX_TIME = new Prefix("t/");
public static final Prefix PREFIX_TAG = new Prefix("#");
public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/");
public static final Prefix PREFIX_VENUE = new Prefix("@");
public static final Prefix PREFIX_PRIORITY = new Prefix("p/");
/* Patterns definitions */
public static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
/* Patterns definitions */
public static final Pattern KEYWORDS_ARGS_FORMAT_LIST =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
}
| package seedu.address.logic.parser;
import java.util.regex.Pattern;
import seedu.address.logic.parser.ArgumentTokenizer.Prefix;
/**
* Contains Command Line Interface (CLI) syntax definitions common to multiple commands
*/
public class CliSyntax {
/* Prefix definitions */
public static final Prefix PREFIX_NAME = new Prefix("n/");
public static final Prefix PREFIX_DATE = new Prefix("due/");
public static final Prefix PREFIX_TIME = new Prefix("t/");
public static final Prefix PREFIX_TAG = new Prefix("#");
public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/");
public static final Prefix PREFIX_VENUE = new Prefix("@");
public static final Prefix PREFIX_PRIORITY = new Prefix("p/");
/* Patterns definitions */
public static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
}
|
Disable sync watchdog timeout check. | from tapiriik.database import db
from tapiriik.sync import SyncStep
import os
import signal
import socket
from datetime import timedelta, datetime
for worker in db.sync_workers.find({"Host": socket.gethostname()}):
# Does the process still exist?
alive = True
try:
os.kill(worker["Process"], 0)
except os.error:
alive = False
# Has it been stalled for too long?
if worker["State"] == SyncStep.List:
timeout = timedelta(minutes=45) # This can take a loooooooong time
else:
timeout = timedelta(minutes=10) # But everything else shouldn't
# if alive and worker["Heartbeat"] < datetime.utcnow() - timeout:
# os.kill(worker["Process"], signal.SIGKILL)
# alive = False
# Clear it from the database if it's not alive.
if not alive:
db.sync_workers.remove({"_id": worker["_id"]})
| from tapiriik.database import db
from tapiriik.sync import SyncStep
import os
import signal
import socket
from datetime import timedelta, datetime
for worker in db.sync_workers.find({"Host": socket.gethostname()}):
# Does the process still exist?
alive = True
try:
os.kill(worker["Process"], 0)
except os.error:
alive = False
# Has it been stalled for too long?
if worker["State"] == SyncStep.List:
timeout = timedelta(minutes=45) # This can take a loooooooong time
else:
timeout = timedelta(minutes=10) # But everything else shouldn't
if alive and worker["Heartbeat"] < datetime.utcnow() - timeout:
os.kill(worker["Process"], signal.SIGKILL)
alive = False
# Clear it from the database if it's not alive.
if not alive:
db.sync_workers.remove({"_id": worker["_id"]})
|
welcome: Format the source of the help prose a bit better.
Template literals FTW.
I'd like to keep all the lines to a reasonable length for reading the
source... but unfortunately even single newlines get displayed
literally. Still, this is much closer. | /* @flow */
import React, { PureComponent } from 'react';
import { Screen, RawLabel, Centerer } from '../common';
export default class WelcomeHelpScreen extends PureComponent<{}> {
render() {
return (
<Screen title="Help" padding>
<Centerer>
<RawLabel
text={
`Zulip combines the immediacy of Slack with an email threading model. With Zulip, you can catch up on important conversations while ignoring irrelevant ones.
New to Zulip? You'll need to first create an account from your computer.
If you're not sure where to start, go to zulipchat.com from your web browser.
Hope to see you back here soon!
`
}
/>
</Centerer>
</Screen>
);
}
}
| /* @flow */
import React, { PureComponent } from 'react';
import { Screen, RawLabel, Centerer } from '../common';
export default class WelcomeHelpScreen extends PureComponent<{}> {
render() {
return (
<Screen title="Help" padding>
<Centerer>
<RawLabel
text={
"Zulip combines the immediacy of Slack with an email threading model. With Zulip, you can catch up on important conversations while ignoring irrelevant ones.\n\nNew to Zulip? You'll need to first create an account from your computer.\n\nIf you're not sure where to start, go to zulipchat.com from your web browser.\n\nHope to see you back here soon!"
}
/>
</Centerer>
</Screen>
);
}
}
|
Validate required env vars existence | package config
import (
"bytes"
"errors"
"fmt"
"github.com/eyecuelab/kit/assets"
"github.com/spf13/viper"
)
func Load(envPrefix string, configPath string) error {
viper.SetConfigType("yaml")
if len(configPath) > 0 {
viper.SetConfigFile(configPath)
if err := viper.ReadInConfig(); err != nil {
return err
}
} else {
if data, err := assets.Get("data/bin/config.yaml"); err != nil {
return err
} else {
viper.ReadConfig(bytes.NewBuffer(data))
}
}
viper.SetEnvPrefix(envPrefix)
viper.AutomaticEnv()
for _, envVar := range viper.GetStringSlice("env") {
if err := viper.BindEnv(envVar); err != nil {
return err
}
if !viper.IsSet(envVar) {
return errors.New(fmt.Sprintf("Env var is not set: %s", envVar))
}
}
return nil
}
| package config
import (
"bytes"
"github.com/eyecuelab/kit/assets"
"github.com/spf13/viper"
)
func Load(envPrefix string, configPath string) error {
viper.SetConfigType("yaml")
if len(configPath) > 0 {
viper.SetConfigFile(configPath)
if err := viper.ReadInConfig(); err != nil {
return err
}
} else {
if data, err := assets.Get("data/bin/config.yaml"); err != nil {
return err
} else {
viper.ReadConfig(bytes.NewBuffer(data))
}
}
viper.SetEnvPrefix(envPrefix)
viper.AutomaticEnv()
for _, envVar := range viper.GetStringSlice("env") {
if err := viper.BindEnv(envVar); err != nil {
return err
}
}
return nil
}
|
Disable init view for now, add extra url for specific quotes page | from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'qi.views.home', name='home'),
# url(r'^qi/', include('qi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'quotes_page.core.views.main', name="main"),
url(r'^(?P<quote_id>\d+)/?$', 'quotes_page.core.views.quote', name="quote"),
#url(r'^init/?$', 'quotes_page.core.views.init', name="init"),
url(r'^stats/?$', 'quotes_page.core.views.stats', name="stats"),
)
| from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'qi.views.home', name='home'),
# url(r'^qi/', include('qi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<quote_id>\d*)$', 'quotes_page.core.views.main', name="main"),
url(r'^init/?$', 'quotes_page.core.views.init', name="init"),
url(r'^stats/?$', 'quotes_page.core.views.stats', name="stats"),
)
|
Fix menu view event trigger. | // @flow
import ListPanelView from './ListPanelView';
import MenuItemView from './MenuItemView';
/**
* @name MenuPanelView
* @memberof module:core.dropdown.views
* @class Одиночный элемент меню. Используется для создания стандартного меню фабричным методом
* @class List view used to display a list of menu items.
* Factory method {@link module:core.dropdown.factory createMenu} uses it to create a menu.
* {@link module:core.dropdown.factory createMenu}.
* @constructor
* @extends module:core.dropdown.views.ListPanelView
* */
export default ListPanelView.extend({
initialize() {
ListPanelView.prototype.initialize.apply(this, Array.from(arguments));
},
className: 'popout-menu',
childView(model) {
if (model.get('customView')) {
return model.get('customView');
}
return MenuItemView;
},
childViewEvents: {
execute: '__execute'
},
__execute(model) {
this.options.parent.close();
this.options.parent.button.trigger('execute', model.id, model);
}
});
| // @flow
import ListPanelView from './ListPanelView';
import MenuItemView from './MenuItemView';
/**
* @name MenuPanelView
* @memberof module:core.dropdown.views
* @class Одиночный элемент меню. Используется для создания стандартного меню фабричным методом
* @class List view used to display a list of menu items.
* Factory method {@link module:core.dropdown.factory createMenu} uses it to create a menu.
* {@link module:core.dropdown.factory createMenu}.
* @constructor
* @extends module:core.dropdown.views.ListPanelView
* */
export default ListPanelView.extend({
initialize() {
ListPanelView.prototype.initialize.apply(this, Array.from(arguments));
},
className: 'popout-menu',
childView(model) {
if (model.get('customView')) {
return model.get('customView');
}
return MenuItemView;
},
childViewEvents: {
execute: '__execute'
},
__execute(model) {
this.options.parent.close();
this.options.parent.trigger('execute', model.id, model);
}
});
|
Return ARN directly if topic name appears to be an ARN | """SNS Topic functions."""
import logging
import boto3
from ..exceptions import SNSTopicNotFound
LOG = logging.getLogger(__name__)
def get_sns_topic_arn(topic_name, account, region):
"""Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g. dev
region (str): Region name, e.g. us-east-1
Returns:
str: ARN for requested topic name
"""
if topic_name.count(':') == 5:
return topic_name
session = boto3.Session(profile_name=account, region_name=region)
sns_client = session.client('sns')
topics = sns_client.list_topics()['Topics']
matched_topic = None
for topic in topics:
topic_arn = topic['TopicArn']
if topic_name == topic_arn.split(':')[-1]:
matched_topic = topic_arn
break
else:
LOG.critical("No topic with name %s found.", topic_name)
raise SNSTopicNotFound('No topic with name {0} found'.format(topic_name))
return matched_topic
| """SNS Topic functions."""
import logging
import boto3
from ..exceptions import SNSTopicNotFound
LOG = logging.getLogger(__name__)
def get_sns_topic_arn(topic_name, account, region):
"""Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g. dev
region (str): Region name, e.g. us-east-1
Returns:
str: ARN for requested topic name
"""
session = boto3.Session(profile_name=account, region_name=region)
sns_client = session.client('sns')
topics = sns_client.list_topics()['Topics']
matched_topic = None
for topic in topics:
topic_arn = topic['TopicArn']
if topic_name == topic_arn.split(':')[-1]:
matched_topic = topic_arn
break
else:
LOG.critical("No topic with name %s found.", topic_name)
raise SNSTopicNotFound('No topic with name {0} found'.format(topic_name))
return matched_topic
|
Add new line at end of file and after imports block | import * as React from "react";
import {getField} from "./utils/getField";
/**
* Component used as an indicator for build status.
* Statuses are differentiated by alternative
* styling rules.
* @param props.status the build status. Partially determines
* the styling of the rules.
*/
const StatusIndicator = (props) => {
const className = 'indicator #'.replace('#', props.status);
return (
<div className={className}></div>
);
}
/**
* Component used to display information for a builder.
* @param props.status the build status of the bot.
* @param props.name the name of the bot.
*/
const Builder = (props) => {
return (
<button className='builder' onClick={props.onClick}>
<StatusIndicator status={props.status}/>
{props.name}
</button>
);
}
/**
* Component used to display the list of builders that built a commit.
*
* @param props.builders
* @param props.builders[].builder.status
* @param props.builders[].builder.name
*/
export const BuilderGrid = (props) => {
const builders = getField(props, 'builders', []);
return (
<div className='builder-grid'>
{builders.map((b, idx) => <Builder key={idx} status={b.status} name={b.name} onClick={props.onClick.bind(this, idx)}/>)}
</div>
);
}
| import * as React from "react";
import {getField} from "./utils/getField";
/**
* Component used as an indicator for build status.
* Statuses are differentiated by alternative
* styling rules.
* @param props.status the build status. Partially determines
* the styling of the rules.
*/
const StatusIndicator = (props) => {
const className = 'indicator #'.replace('#', props.status);
return (
<div className={className}></div>
);
}
/**
* Component used to display information for a builder.
* @param props.status the build status of the bot.
* @param props.name the name of the bot.
*/
const Builder = (props) => {
return (
<button className='builder' onClick={props.onClick}>
<StatusIndicator status={props.status}/>
{props.name}
</button>
);
}
/**
* Component used to display the list of builders that built a commit.
*
* @param props.builders
* @param props.builders[].builder.status
* @param props.builders[].builder.name
*/
export const BuilderGrid = (props) => {
const builders = getField(props, 'builders', []);
return (
<div className='builder-grid'>
{builders.map((b, idx) => <Builder key={idx} status={b.status} name={b.name} onClick={props.onClick.bind(this, idx)}/>)}
</div>
);
} |
Refactor the stock titles for buttons.
svn commit r187 | <?php
/**
* @package Swat
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @copyright silverorange 2004
*/
require_once('Swat/SwatControl.php');
require_once('Swat/SwatHtmlTag.php');
/**
* A form submit button.
*/
class SwatButton extends SwatControl {
/**
* The visible text on the button.
* @var string
*/
public $title;
public function init() {
$this->setTitleFromStock('submit');
}
public function display() {
$input_tag = new SwatHtmlTag('input');
$input_tag->type = 'submit';
$input_tag->name = $this->name;
$input_tag->value = $this->title;
$input_tag->display();
}
/**
* Set a stock title.
* Lookup a stock title for the button and set it as the current title.
* @param id string The shortname of the stock title.
*/
public function setTitleFromStock($id) {
switch ($id) {
case 'submit':
$this->title = _S('Submit');
break;
case 'create':
$this->title = _S('Create');
break;
case 'apply':
$this->title = _S('Apply');
break;
}
}
}
?>
| <?php
/**
* @package Swat
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @copyright silverorange 2004
*/
require_once('Swat/SwatControl.php');
require_once('Swat/SwatHtmlTag.php');
/**
* A form submit button.
*/
class SwatButton extends SwatControl {
/**
* The visible text on the button.
* @var string
*/
public $title;
public function init() {
$this->title = $this->getStockTitle('submit');
}
public function display() {
$input_tag = new SwatHtmlTag('input');
$input_tag->type = 'submit';
$input_tag->name = $this->name;
$input_tag->value = $this->title;
$input_tag->display();
}
public function getStockTitle($id) {
switch ($id) {
case 'submit':
return _S('Submit');
case 'create':
return _S('Create');
case 'apply':
return _S('Apply');
}
}
}
?>
|
Add factory for mock responses with entity | package io.github.pyranja.hamcrest.jaxrs;
import org.mockito.Mockito;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.mockito.Mockito.when;
/**
* Factory methods for jaxrs.Response mocks
*/
public final class MockResponse {
private MockResponse() { /* no instances */ }
/**
* Create mock response with given status only.
*/
static Response with(final Response.StatusType status) {
final Response mock = Mockito.mock(Response.class);
when(mock.getStatusInfo()).thenReturn(status);
when(mock.getStatus()).thenReturn(status.getStatusCode());
return mock;
}
/**
* Create mock response with given content type.
*/
static Response having(final MediaType mime) {
final Response mock = Mockito.mock(Response.class);
when(mock.getMediaType()).thenReturn(mime);
return mock;
}
/**
* Create mock response with given entity
*/
static <CONTENT> Response containing(final Class<CONTENT> type, final CONTENT content) {
final Response mock = Mockito.mock(Response.class);
when(mock.hasEntity()).thenReturn(true);
when(mock.getEntity()).thenReturn(content);
when(mock.readEntity(type)).thenReturn(content);
return mock;
}
}
| package io.github.pyranja.hamcrest.jaxrs;
import org.mockito.Mockito;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.mockito.Mockito.when;
/**
* Factory methods for jaxrs.Response mocks
*/
public final class MockResponse {
private MockResponse() { /* no instances */ }
/**
* Create mock response with given status only.
*/
static Response with(final Response.StatusType status) {
final Response mock = Mockito.mock(Response.class);
when(mock.getStatusInfo()).thenReturn(status);
when(mock.getStatus()).thenReturn(status.getStatusCode());
return mock;
}
static Response having(final MediaType mime) {
final Response mock = Mockito.mock(Response.class);
when(mock.getMediaType()).thenReturn(mime);
return mock;
}
}
|
[Genomics]: Create BQSR targets on a single, merged file, as it is not
scatter-gatherable, and is pretty quick on large files anyways. | package com.github.sparkcaller.preprocessing;
import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;
import java.io.File;
/*
* Recalibrate the base quality scores inorder to get more accurate scores.
*
* See:
* https://www.broadinstitute.org/gatk/documentation/tooldocs/org_broadinstitute_gatk_tools_walkers_bqsr_BaseRecalibrator.php
*
* For more information.
*
*/
public class BQSRTargetGenerator extends BaseGATKProgram {
public BQSRTargetGenerator(String pathToReference, String knownSites, String extraArgs, String coresPerNode) {
super("BaseRecalibrator", extraArgs);
setReference(pathToReference);
addArgument("-knownSites", knownSites);
setThreads(coresPerNode);
}
public File generateTargets(File file) throws Exception {
setInputFile(file.getPath());
String outputTableFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-recal_data.table";
File outputTable = new File(outputTableFilename);
setOutputFile(outputTable.getPath());
executeProgram();
return outputTable;
}
}
| package com.github.sparkcaller.preprocessing;
import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;
import org.apache.spark.api.java.function.Function;
import scala.Tuple2;
import java.io.File;
/*
* Recalibrate the base quality scores inorder to get more accurate scores.
*
* See:
* https://www.broadinstitute.org/gatk/documentation/tooldocs/org_broadinstitute_gatk_tools_walkers_bqsr_BaseRecalibrator.php
*
* For more information.
*
*/
public class BQSRTargetGenerator extends BaseGATKProgram implements Function<File, Tuple2<File, File>> {
public BQSRTargetGenerator(String pathToReference, String knownSites, String extraArgs, String coresPerNode) {
super("BaseRecalibrator", extraArgs);
setReference(pathToReference);
addArgument("-knownSites", knownSites);
setThreads(coresPerNode);
}
public Tuple2<File, File> call(File file) throws Exception {
setInputFile(file.getPath());
String outputTableFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-recal_data.table";
File outputTable = new File(outputTableFilename);
setOutputFile(outputTable.getPath());
executeProgram();
return new Tuple2<File, File>(file, outputTable);
}
}
|
[FIX] Fix compute contains_unreserved on NewId records | # Copyright 2018 Camptocamp SA
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockQuant(models.Model):
_inherit = "stock.quant"
contains_unreserved = fields.Boolean(
string="Contains unreserved products",
compute="_compute_contains_unreserved",
store=True,
)
@api.depends("product_id", "location_id", "quantity", "reserved_quantity")
def _compute_contains_unreserved(self):
for record in self:
# Avoid error when adding a new line on manually Update Quantity
if isinstance(record.id, models.NewId):
record.contains_unreserved = False
continue
available = record._get_available_quantity(
record.product_id, record.location_id
)
record.contains_unreserved = True if available > 0 else False
| # Copyright 2018 Camptocamp SA
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockQuant(models.Model):
_inherit = "stock.quant"
contains_unreserved = fields.Boolean(
string="Contains unreserved products",
compute="_compute_contains_unreserved",
store=True,
)
@api.depends("product_id", "location_id", "quantity", "reserved_quantity")
def _compute_contains_unreserved(self):
for record in self:
available = record._get_available_quantity(
record.product_id, record.location_id
)
record.contains_unreserved = True if available > 0 else False
|
Remove disconnected client from clients list, allow client callbacks to be set in constructor. | import asyncore
import socket
from logging import error, info, warning
from client import Client
class Server(asyncore.dispatcher):
def __init__(self, port, connect_fn=None, msg_fn=None, close_fn=None):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
self.bind(('localhost', port))
self.listen(5)
self.client_connect_fn = connect_fn
self.client_msg_fn = msg_fn
self.client_close_fn = close_fn
self.clients = []
def handle_accepted(self, sock, addr):
client = Client(sock)
client.msg_fn = self.client_msg_fn
client.close_fn = self.client_close
self.clients.append(client)
if self.client_connect_fn:
self.client_connect_fn(client)
def client_close(self, client):
self.clients.remove(client)
if self.client_close_fn:
self.client_close_fn(client)
def broadcast(self, msg):
for client in self.clients:
client.send_msg(msg)
| import asyncore
import socket
from logging import error, info, warning
from client import Client
class Server(asyncore.dispatcher):
def __init__(self, port, host="localhost"):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
self.connect_fn = None
self.msg_fn = None
self.close_fn = None
self.clients = []
def handle_accepted(self, sock, addr):
new_client = Client(sock)
new_client.msg_fn = self.msg_fn
new_client.close_fn = self.close_fn
self.clients.append(new_client)
if self.connect_fn is not None:
self.connect_fn(new_client)
def broadcast(self, msg):
for client in self.clients:
client.send_msg(msg)
|
Fix ruler menu for breakpoints
Review URL: http://codereview.chromium.org/99357 | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.debug.ui.editors;
import org.eclipse.ui.editors.text.TextEditor;
/**
* A simplistic Javascript editor which supports its own key binding scope.
*/
public class JsEditor extends TextEditor {
/** The ID of this editor as defined in plugin.xml */
public static final String EDITOR_ID =
"org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$
/** The ID of the editor context menu */
public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$
/** The ID of the editor ruler context menu */
public static final String RULER_CONTEXT = EDITOR_ID + ".ruler"; //$NON-NLS-1$
@Override
protected void initializeEditor() {
super.initializeEditor();
setEditorContextMenuId(EDITOR_CONTEXT);
setRulerContextMenuId(RULER_CONTEXT);
}
public JsEditor() {
super();
setSourceViewerConfiguration(new JsSourceViewerConfiguration());
setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$
"org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$
}
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.debug.ui.editors;
import org.eclipse.ui.editors.text.TextEditor;
/**
* A simplistic Javascript editor which supports its own key binding scope.
*/
public class JsEditor extends TextEditor {
/** The ID of this editor as defined in plugin.xml */
public static final String EDITOR_ID =
"org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$
/** The ID of the editor context menu */
public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$
/** The ID of the editor ruler context menu */
public static final String RULER_CONTEXT = EDITOR_CONTEXT + ".ruler"; //$NON-NLS-1$
protected void initializeEditor() {
super.initializeEditor();
setEditorContextMenuId(EDITOR_CONTEXT);
setRulerContextMenuId(RULER_CONTEXT);
}
public JsEditor() {
super();
setSourceViewerConfiguration(new JsSourceViewerConfiguration());
setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$
"org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$
}
}
|
Add some tests for GitTree | <?php
use Git4p\Git;
use Git4p\GitObject;
use Git4p\GitTree;
class GitTreeTest extends PHPUnit_Framework_TestCase {
protected $git = false;
protected $gittree = false;
public function setup() {
$this->git = new Git('/tmp/phpunit/gittestrepo');
$this->gittree = new GitTree($this->git);
}
public function teardown() {
$this->git = false;
$this->gittree = false;
}
public function testShouldReturnGitTreeType() {
$this->assertEquals($this->gittree->type(), GitObject::TYPE_TREE);
}
public function testShouldHaveDirectoryName() {
$this->gittree->setName('SomeDirectoryName');
$this->assertEquals($this->gittree->name(), 'SomeDirectoryName');
}
public function testShouldContainReferencesToFiles() {
$data = ['file1', 'file2'];
$this->gittree->setData($data);
$this->assertEquals($this->gittree->entries(), $data);
}
}
| <?php
use Git4p\Git;
use Git4p\GitObject;
use Git4p\GitTree;
class GitTreeTest extends PHPUnit_Framework_TestCase {
protected $git = false;
protected $gittree = false;
public function setup() {
$this->git = new Git('/tmp/phpunit/gittestrepo');
$this->gittree = new GitTree($this->git);
}
public function teardown() {
$this->git = false;
$this->gittree = false;
}
public function testShouldReturnGitTreeType() {
$this->assertEquals($this->gittree->type(), GitObject::TYPE_TREE);
}
public function testShouldHaveDirectoryName() {
$this->gittree->setName('SomeDirectoryName');
$this->assertEquals($this->gittree->name(), 'SomeDirectoryName');
}
}
|
Make reaction api display user id instead of username. | from apps.bluebottle_utils.serializers import SorlImageField
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Reaction
class ReactionAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class ReactionDetailSerializer(serializers.ModelSerializer):
# Read-only fields.
created = serializers.Field()
# Custom fields.
# TODO: Enable embedded models in Ember Data and re-enable this.
# author = ReactionAuthorSerializer()
author = serializers.PrimaryKeyRelatedField(read_only=True)
# TODO: This isn't working with the pattern: api/blogs/<slug>/reactions/<pk>
# Delete or fix this ... we don't really need it so removing it is ok but it's nice to have.
# url = HyperlinkedIdentityField(view_name='reactions:reaction-detail')
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction', 'id')
class ReactionListSerializer(ReactionDetailSerializer):
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction', 'id')
| from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Reaction
from rest_framework.fields import HyperlinkedIdentityField
class ReactionAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class ReactionDetailSerializer(serializers.ModelSerializer):
# Read-only fields.
created = serializers.Field()
# Custom fields.
# TODO: Enable embedded models in Ember Data and re-enable this.
# author = ReactionAuthorSerializer()
author = serializers.Field() # Needed to make the author field read-only.
# TODO: This isn't working with the pattern: api/blogs/<slug>/reactions/<pk>
# Delete or fix this ... we don't really need it so removing it is ok but it's nice to have.
# url = HyperlinkedIdentityField(view_name='reactions:reaction-detail')
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction', 'id')
class ReactionListSerializer(ReactionDetailSerializer):
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction', 'id')
|
Update test for cookies fixture | # -*- coding: utf-8 -*-
def test_cookies_fixture(testdir):
"""Make sure that pytest accepts the `cookies` fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_valid_fixture(cookies):
assert hasattr(cookies, 'bake')
assert callable(cookies.bake)
assert cookies.exception is None
assert cookies.exit_code == 0
assert cookies.project is None
""")
# run pytest with the following cmd args
result = testdir.runpytest('-v')
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'*::test_valid_fixture PASSED',
])
# make sure that that we get a '0' exit code for the testsuite
assert result.ret == 0
def test_help_message(testdir):
result = testdir.runpytest(
'--help',
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'cookies:',
])
| # -*- coding: utf-8 -*-
def test_cookies_fixture(testdir):
"""Make sure that pytest accepts the `cookies` fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_valid_fixture(cookies):
assert hasattr(cookies, 'bake')
assert callable(cookies.bake)
assert cookies.error is None
assert cookies.project is None
""")
# run pytest with the following cmd args
result = testdir.runpytest('-v')
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'*::test_valid_fixture PASSED',
])
# make sure that that we get a '0' exit code for the testsuite
assert result.ret == 0
def test_help_message(testdir):
result = testdir.runpytest(
'--help',
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'cookies:',
])
|
Fix the test method names :) | import pytest
from spec2scl.transformers.R import RTransformer
from transformer_test_case import TransformerTestCase
class TestRTransformer(TransformerTestCase):
def setup_method(self, method):
self.t = RTransformer('', {})
@pytest.mark.parametrize(('spec'), [
('"%{bindir}/R foo" stays'),
])
def test_R_specific_commands_not_matching(self, spec):
patterns = self.t.handle_R_specific_commands.matches
assert self.get_pattern_for_spec(patterns, spec) == None
@pytest.mark.parametrize(('spec', 'expected'), [
('R CMD foo bar', '%{?scl:scl enable %{scl} "}\nR CMD foo bar%{?scl:"}\n'),
('%{bindir}/R CMD foo bar\n', '%{?scl:scl enable %{scl} "}\n%{bindir}/R CMD foo bar\n%{?scl:"}\n'),
])
def test_R_specific_commands_matching(self, spec, expected):
patterns = self.t.handle_R_specific_commands.matches
assert self.t.handle_R_specific_commands(self.get_pattern_for_spec(patterns, spec), spec) == expected
| import pytest
from spec2scl.transformers.R import RTransformer
from transformer_test_case import TransformerTestCase
class TestRTransformer(TransformerTestCase):
def setup_method(self, method):
self.t = RTransformer('', {})
@pytest.mark.parametrize(('spec'), [
('"%{bindir}/R foo" stays'),
])
def test_ruby_specific_commands_not_matching(self, spec):
patterns = self.t.handle_R_specific_commands.matches
assert self.get_pattern_for_spec(patterns, spec) == None
@pytest.mark.parametrize(('spec', 'expected'), [
('R CMD foo bar', '%{?scl:scl enable %{scl} "}\nR CMD foo bar%{?scl:"}\n'),
('%{bindir}/R CMD foo bar\n', '%{?scl:scl enable %{scl} "}\n%{bindir}/R CMD foo bar\n%{?scl:"}\n'),
])
def test_ruby_specific_commands_matching(self, spec, expected):
patterns = self.t.handle_R_specific_commands.matches
assert self.t.handle_R_specific_commands(self.get_pattern_for_spec(patterns, spec), spec) == expected
|
Fix previous commit (balancing scripts) | # This script creates a balanced ground truth given an unbalanced on by applying
# random sampling. The size of the resulting classes equals to the minimum size
# among original classes.
import sys
import yaml
from random import shuffle
try:
input_gt = sys.argv[1]
balanced_gt = sys.argv[2]
except:
print 'usage:', sys.argv[0], '<input-grounttruth> <output-balanced-groundtruth>'
sys.exit()
input_gt = yaml.load(open(input_gt, 'r'))
gt = {}
for t, l in input_gt['groundTruth'].items():
gt.setdefault(l, [])
gt[l] += [t]
for label in gt:
print label, len(gt[label])
min_class_len = min(len(gt[label]) for label in gt)
print 'Minimum class length:', min_class_len
input_gt['groundTruth'] = {}
for label in gt:
shuffle(gt[label])
for track in gt[label][:min_class_len]:
input_gt['groundTruth'][track] = label
with open(balanced_gt, 'w') as f:
yaml.dump(input_gt, f)
| # This script creates a balanced ground truth given an unbalanced on by applying
# random sampling. The size of the resulting classes equals to the minimum size
# among original classes.
import sys
import yaml
from random import shuffle
try:
input_gt = sys.argv[1]
balanced_gt = sys.argv[2]
except:
print 'usage:', sys.argv[0], '<input-grounttruth> <output-balanced-groundtruth>'
sys.exit()
input_gt = yaml.load(open(input_gt, 'r'))
gt = {}
for t, l in input_gt['groundTruth'].items():
gt.setdefault(l, [])
gt[l] += [t]
for label in gt:
print label, len(gt[label])
min_class_len = min(len(gt[label]) for label in gt)
print 'Minimum class length:', min_class_len
for label in gt:
shuffle(gt[label])
for track in gt[label][:min_class_len]:
input_gt['groundTruth'][track] = label
with open(balanced_gt, 'w') as f:
yaml.dump(input_gt, f)
|
Use varint instead of uint8 for bloom filter data length | 'use strict';
var bitcore = require('bitcore');
var BloomFilter = require('bloom-filter');
var BufferReader = bitcore.encoding.BufferReader;
var BufferWriter = bitcore.encoding.BufferWriter;
/**
* A constructor for Bloom Filters
* @see https://github.com/bitpay/bloom-filter
* @param {Buffer} - payload
*/
BloomFilter.fromBuffer = function fromBuffer(payload) {
var obj = {};
var parser = new BufferReader(payload);
var length = parser.readVarintNum();
obj.vData = [];
for(var i = 0; i < length; i++) {
obj.vData.push(parser.readUInt8());
}
obj.nHashFuncs = parser.readUInt32LE();
obj.nTweak = parser.readUInt32LE();
obj.nFlags = parser.readUInt8();
return new BloomFilter(obj);
};
/**
* @returns {Buffer}
*/
BloomFilter.prototype.toBuffer = function toBuffer() {
var bw = new BufferWriter();
bw.writeVarintNum(this.vData.length);
for(var i = 0; i < this.vData.length; i++) {
bw.writeUInt8(this.vData[i]);
}
bw.writeUInt32LE(this.nHashFuncs);
bw.writeUInt32LE(this.nTweak);
bw.writeUInt8(this.nFlags);
return bw.concat();
};
module.exports = BloomFilter;
| 'use strict';
var bitcore = require('bitcore');
var BloomFilter = require('bloom-filter');
var BufferReader = bitcore.encoding.BufferReader;
var BufferWriter = bitcore.encoding.BufferWriter;
/**
* A constructor for Bloom Filters
* @see https://github.com/bitpay/bloom-filter
* @param {Buffer} - payload
*/
BloomFilter.fromBuffer = function fromBuffer(payload) {
var obj = {};
var parser = new BufferReader(payload);
var length = parser.readUInt8();
obj.vData = [];
for(var i = 0; i < length; i++) {
obj.vData.push(parser.readUInt8());
}
obj.nHashFuncs = parser.readUInt32LE();
obj.nTweak = parser.readUInt32LE();
obj.nFlags = parser.readUInt8();
return new BloomFilter(obj);
};
/**
* @returns {Buffer}
*/
BloomFilter.prototype.toBuffer = function toBuffer() {
var bw = new BufferWriter();
bw.writeVarintNum(this.vData.length);
for(var i = 0; i < this.vData.length; i++) {
bw.writeUInt8(this.vData[i]);
}
bw.writeUInt32LE(this.nHashFuncs);
bw.writeUInt32LE(this.nTweak);
bw.writeUInt8(this.nFlags);
return bw.concat();
};
module.exports = BloomFilter;
|
Change action after ChangeDirectoryCommand to be executed regardless of any user action to the command | package seedu.task.alerts;
import java.util.Optional;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Alert.AlertType;
public class ChangeDirectoryCommandAlert extends Alert{
public static final String CHANGE_DIRECTORY_COMMAND_TITLE = "Change task directory";
public static final String CHANGE_DIRECTORY_COMMAND_HEADER_TEXT = "Task directory has been changed successfully, Never Forget must now restart.\nPlease launch the application again";
public ChangeDirectoryCommandAlert(AlertType alertType) {
super(alertType);
}
public static boolean changeDirectoryCommand(){
try {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(CHANGE_DIRECTORY_COMMAND_TITLE);
alert.setHeaderText(CHANGE_DIRECTORY_COMMAND_HEADER_TEXT);
alert.showAndWait();
if (!alert.isShowing()) {
return true;
}
else {
return false;
}
} catch (ExceptionInInitializerError | IllegalStateException e) {
return false;
}
}
}
| package seedu.task.alerts;
import java.util.Optional;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Alert.AlertType;
public class ChangeDirectoryCommandAlert extends Alert{
public static final String CHANGE_DIRECTORY_COMMAND_TITLE = "Change task directory";
public static final String CHANGE_DIRECTORY_COMMAND_HEADER_TEXT = "Task directory has been changed successfully, Never Forget must now restart.\nPlease launch the application again";
public ChangeDirectoryCommandAlert(AlertType alertType) {
super(alertType);
}
public static boolean changeDirectoryCommand(){
try {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(CHANGE_DIRECTORY_COMMAND_TITLE);
alert.setHeaderText(CHANGE_DIRECTORY_COMMAND_HEADER_TEXT);
Optional<ButtonType> result = alert.showAndWait();
if (!alert.isShowing()) {
return true;
}
else {
return false;
}
} catch (ExceptionInInitializerError | IllegalStateException e) {
return false;
}
}
}
|
Add karma serve path for MutationObservers and WeakMap | module.exports = function(karma) {
var common = require('../../tools/test/karma-common.conf.js');
karma.set(common.mixin_common_opts(karma, {
// base path, that will be used to resolve files and exclude
basePath: '../../',
// list of files / patterns to load in the browser
files: [
'tools/test/mocha-htmltest.js',
'CustomElements/conf/mocha.conf.js',
'CustomElements/../tools/test/chai/chai.js',
'CustomElements/custom-elements.js',
'CustomElements/test/js/*.js',
{pattern: 'CustomElements/src/*', included: false},
{pattern: 'CustomElements/test/html/*.html', included: false},
{pattern: 'MutationObservers/*.js', included: false},
{pattern: 'WeakMap/*.js', included: false},
{pattern: 'tools/**/*.js', included: false}
]
}));
};
| module.exports = function(karma) {
var common = require('../../tools/test/karma-common.conf.js');
karma.set(common.mixin_common_opts(karma, {
// base path, that will be used to resolve files and exclude
basePath: '../../',
// list of files / patterns to load in the browser
files: [
'tools/test/mocha-htmltest.js',
'CustomElements/conf/mocha.conf.js',
'CustomElements/../tools/test/chai/chai.js',
'CustomElements/custom-elements.js',
'CustomElements/test/js/*.js',
{pattern: 'CustomElements/src/*', included: false},
{pattern: 'CustomElements/MutationObservers/*.js', included: false},
{pattern: 'CustomElements/test/html/*.html', included: false},
{pattern: 'tools/**/*.js', included: false}
]
}));
};
|
Add a simple card counting strategy | class FixFoldStrategy:
"""This strategy folds every time there is a small card available."""
def __init__(self, N=3):
self.N = N
def play(self, info):
if info.bestFold(self.player)[1] > self.N:
return 'Hit me'
else:
return 'fold'
class RatioFoldStrategy:
"""This strategy folds more readily as their stack grows worse"""
def __init__(self, N=4):
self.N = N
def play(self, info):
if info.bestFold(self.player)[1]*self.N > sum([s*s for s in self.player.stack]):
return 'Hit me'
else:
return 'fold'
class CardCounter:
"""This strategy folds based on card counting expectation values."""
def __init__(self, scared=0.23):
from collections import Counter
self.Counter = Counter
self.scared = scared
def play(self, info):
c = self.Counter(info.deck)
if info.bestFold(self.player)[1] > self.scared*sum([s*c[s] for s in c])/len(info.deck) + sum([s*c[s]/len(info.deck) for s in self.player.stack]):
return 'Hit me'
else:
return 'fold'
| class FixFoldStrategy:
"""This strategy folds every time there is a small card available."""
def __init__(self, N=3):
self.N = N
def play(self, info):
if info.bestFold(self.player)[1] > self.N:
return 'Hit me'
else:
return 'fold'
class RatioFoldStrategy:
"""This strategy folds more readily as their stack grows worse"""
def __init__(self, N=4):
self.N = N
def play(self, info):
if info.bestFold(self.player)[1]*self.N > sum([s*s for s in self.player.stack]):
return 'Hit me'
else:
return 'fold'
|
Add port and ip from heroku env variables. | const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const fx = require("./fx");
const app = express();
const PORT = process.env.PORT || 3000;
const IP = process.env.IP || "0.0.0.0";
// serve static files.
app.use(express.static('./public', { maxAge: 4 * 60 * 60 * 1000 /* 2hrs */ }));
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.json());
// API route to get all rates.
app.get('/api/v1/rates', function (req, res) {
fx(process.env.OER_KEY, function (err, rates) {
if (err) {
res.json({ error : err });
} else {
res.json(rates);
}
});
});
// Set root to the main angular js app.
app.get('/',function (req, res) {
filepath = path.join(path.dirname(__filename), 'public/index.html');
res.sendFile(filepath);
});
app.listen(IP, PORT);
console.log('Listening on port ' + PORT + "!");
| const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const fx = require("./fx");
const app = express();
// serve static files.
app.use(express.static('./public', { maxAge: 4 * 60 * 60 * 1000 /* 2hrs */ }));
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.json());
// API route to get all rates.
app.get('/api/v1/rates', function (req, res) {
fx(process.env.OER_KEY, function (err, rates) {
if (err) {
res.json({ error : err });
} else {
res.json(rates);
}
});
});
// Set root to the main angular js app.
app.get('/',function (req, res) {
filepath = path.join(path.dirname(__filename), 'public/index.html');
res.sendFile(filepath);
});
app.listen(3000);
console.log('Listening on port 3000!');
|
Remove options argument to setupFreedom. | Components.utils.import("resource://gre/modules/devtools/Console.jsm");
Components.utils.import("resource://gre/modules/Timer.jsm");
// This module does not support all of es6 promise functionality.
// Components.utils.import("resource://gre/modules/Promise.jsm");
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest");
Components.utils.importGlobalProperties(['URL']);
var freedom;
function setupFreedom(manifest) {
if (this.freedom) {
return this.freedom;
}
var lastSlash = manifest.lastIndexOf("/");
var manifestLocation = manifest.substring(0, lastSlash + 1);
//var manifestFilename = manifest.substring(lastSlash + 1);
firefox_config = {
isApp: false,
manifest: manifest,
portType: 'Worker',
stayLocal: true,
location: manifestLocation
};
| Components.utils.import("resource://gre/modules/devtools/Console.jsm");
Components.utils.import("resource://gre/modules/Timer.jsm");
// This module does not support all of es6 promise functionality.
// Components.utils.import("resource://gre/modules/Promise.jsm");
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest");
Components.utils.importGlobalProperties(['URL']);
var freedom;
function setupFreedom(options, manifest) {
if (this.freedom) {
return this.freedom;
}
var lastSlash = manifest.lastIndexOf("/");
var manifestLocation = manifest.substring(0, lastSlash + 1);
//var manifestFilename = manifest.substring(lastSlash + 1);
firefox_config = {
isApp: false,
manifest: manifest,
portType: 'Worker',
stayLocal: true,
location: manifestLocation
};
|
Replace the jitterbug page with the SF Bug Tracker page. | #
# Minimal "re" compatibility wrapper
#
# If your regexps don't work well under 2.0b1, you can switch
# to the old engine ("pre") down below.
#
# To help us fix any remaining bugs in the new engine, please
# report what went wrong. You can either use the following web
# page:
#
# http://sourceforge.net/bugs/?group_id=5470
#
# or send a mail to SRE's author:
#
# Fredrik Lundh <effbot@telia.com>
#
# Make sure to include the pattern, the string SRE failed to
# match, and what result you expected.
#
# thanks /F
#
# engine = "sre"
engine = "pre"
if engine == "sre":
# New unicode-aware engine
from sre import *
else:
# Old 1.5.2 engine. This one supports 8-bit strings only,
# and will be removed in 2.0 final.
from pre import *
| #
# Minimal "re" compatibility wrapper
#
# If your regexps don't work well under 2.0b1, you can switch
# to the old engine ("pre") down below.
#
# To help us fix any remaining bugs in the new engine, please
# report what went wrong. You can either use the following web
# page:
#
# http://www.python.org/search/search_bugs.html
#
# or send a mail to SRE's author:
#
# Fredrik Lundh <effbot@telia.com>
#
# Make sure to include the pattern, the string SRE failed to
# match, and what result you expected.
#
# thanks /F
#
engine = "sre"
# engine = "pre"
if engine == "sre":
# New unicode-aware engine
from sre import *
else:
# Old 1.5.2 engine. This one supports 8-bit strings only,
# and will be removed in 2.0 final.
from pre import *
|
Stop forwarding flash by default, it breaks more than it doesn't.
git-svn-id: 87d19257dd11500985d055ec4730e446075a5f07@1279 78c7df6f-8922-0410-bcd3-9426b1ad491b | # Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com>
#
# 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 wsgi, convergence
forwarding_conditions = [
lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url'],
lambda e : 'mozilla.org/en-US/firefox/livebookmarks.html' not in e['reconstructed_url'],
lambda e : e.get('CONTENT_TYPE') != 'application/x-shockwave-flash',
]
def add_forward_condition(condition):
forwarding_conditions.append(condition)
def remove_forward_condition(condition):
while condition in forwarding_conditions:
forwarding_conditions.remove(condition)
| # Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com>
#
# 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 wsgi, convergence
forwarding_conditions = [
lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url'],
lambda e : 'mozilla.org/en-US/firefox/livebookmarks.html' not in e['reconstructed_url'],
]
def add_forward_condition(condition):
forwarding_conditions.append(condition)
def remove_forward_condition(condition):
while condition in forwarding_conditions:
forwarding_conditions.remove(condition)
|
Fix bug when file is minified
We needed to inject scope with the full notation | (function() {
'use strict';
// Create module
var module = angular.module('filteredTable', []);
function filteredTable() {
function controller($scope) {
$scope.predicate = null;
$scope.reverse = false;
$scope.sorting = {};
$scope.orderBy = function(key) {
// Clean old predicate sorting
$scope.sorting[$scope.predicate] = null;
// Set new parameters
$scope.predicate = key;
$scope.reverse = !$scope.reverse;
$scope.sorting[key] = $scope.reverse ? 'desc' : 'asc';
}
}
return {
restrict: 'A',
controller: ['$scope', controller]
}
}
// Declare directive
module.directive('filteredTable', filteredTable);
})(); | (function() {
'use strict';
// Create module
var module = angular.module('filteredTable', []);
function filteredTable() {
function controller($scope) {
$scope.predicate = null;
$scope.reverse = false;
$scope.sorting = {};
$scope.orderBy = function(key) {
// Clean old predicate sorting
$scope.sorting[$scope.predicate] = null;
// Set new parameters
$scope.predicate = key;
$scope.reverse = !$scope.reverse;
$scope.sorting[key] = $scope.reverse ? 'desc' : 'asc';
}
}
return {
restrict: 'A',
controller: controller
}
}
// Declare directive
module.directive('filteredTable', [filteredTable]);
})(); |
BB-1412: Apply validation rules for import data
- fixed validator | <?php
namespace Oro\Bundle\EntityExtendBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Oro\Bundle\EntityExtendBundle\Model\EnumValue as EnumValueEntity;
use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper;
class EnumValueValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($entity, Constraint $constraint)
{
if ($entity instanceof EnumValueEntity) {
$entity = $entity->toArray();
}
if (!empty($entity['id']) || empty($entity['label'])) {
return;
}
$valueId = ExtendHelper::buildEnumValueId($entity['label'], false);
if (empty($valueId)) {
$this->context
->buildViolation($constraint->message, ['{{ value }}' => $entity['label']])
->atPath('[label]')
->addViolation()
;
}
}
}
| <?php
namespace Oro\Bundle\EntityExtendBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Oro\Bundle\EntityExtendBundle\Model\EnumValue as EnumValueEntity;
use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper;
class EnumValueValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($entity, Constraint $constraint)
{
if (!$entity instanceof EnumValueEntity) {
throw new UnexpectedTypeException(
$entity,
'Oro\Bundle\EntityExtendBundle\Model\EnumValue'
);
}
/* @var $entity EnumValueEntity */
if ($entity->getId() || !$entity->getLabel()) {
return;
}
$valueId = ExtendHelper::buildEnumValueId($entity->getLabel(), false);
if (empty($valueId)) {
$this->context->addViolationAt('label', $constraint->message, ['{{ value }}' => $entity->getLabel()]);
}
}
}
|
Add support for error detail | var Promise = require("bluebird");
module.exports = (response, body) => {
var outResponse = {
statusCode: response.statusCode,
headers: response.headers,
body: body
};
if (response.statusCode != 200) {
var errorResponse = outResponse;
if (response.headers['content-type'] === 'application/json;charset=UTF-8') {
var responseBody = JSON.parse(body);
errorResponse.errorCode = responseBody.errorCode;
errorResponse.message = responseBody.message;
errorResponse.refId = responseBody.refId;
if (responseBody.detail !== undefined) {
errorResponse.detail = responseBody.detail;
}
} else {
errorResponse.message = body;
}
return new Promise.reject(errorResponse);
} else if (response.headers['content-type'] === 'application/json;charset=UTF-8') {
outResponse.content = JSON.parse(body);
return outResponse;
} else {
outResponse.content = body;
return outResponse;
}
};
| var Promise = require("bluebird");
module.exports = (response, body) => {
var outResponse = {
statusCode: response.statusCode,
headers: response.headers,
body: body
};
if (response.statusCode != 200) {
var errorResponse = outResponse;
if (response.headers['content-type'] === 'application/json;charset=UTF-8') {
var responseBody = JSON.parse(body);
errorResponse.errorCode = responseBody.errorCode;
errorResponse.message = responseBody.message;
errorResponse.refId = responseBody.refId;
} else {
errorResponse.message = body;
}
return new Promise.reject(errorResponse);
} else if (response.headers['content-type'] === 'application/json;charset=UTF-8') {
outResponse.content = JSON.parse(body);
return outResponse;
} else {
outResponse.content = body;
return outResponse;
}
};
|
Enable policy feedback in interaction creation selection | module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
{
value: 'policy_feedback',
label: 'Capture policy feedback',
hint: 'For example, and issue or comment on government policy from a company',
}],
}],
}
}
| module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [
{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
/*, {
value: 'policy_feedback',
label: 'Policy feedback',
hint: 'For example, when a company wants to give UK government policy feedback',
} */
],
},
],
}
}
|
Replace Twig global namespaces to support Twig 3
Use of the globally namespaced Twig functions was deprecated in Twig 2.x and removed in Twig 3.x.
This commit simply replaces the globally namespaced functions with their namespaced equivalents. | <?php
namespace DZunke\FeatureFlagsBundle\Twig;
use DZunke\FeatureFlagsBundle\Toggle;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class FeatureExtension extends AbstractExtension
{
/**
* @var Toggle
*/
protected $toggle;
/**
* @param Toggle $toggle
*/
public function __construct(Toggle $toggle)
{
$this->toggle = $toggle;
}
public function getFunctions()
{
return [
new TwigFunction('has_feature', [$this, 'checkFeature'], ['is_safe' => ['html']]),
];
}
/**
* @param string $name
* @param array $arguments
* @return bool
*/
public function checkFeature($name, $arguments = null)
{
return $this->toggle->isActive($name, $arguments);
}
public function getName()
{
return 'd_zunke_feature_extension';
}
}
| <?php
namespace DZunke\FeatureFlagsBundle\Twig;
use DZunke\FeatureFlagsBundle\Toggle;
class FeatureExtension extends \Twig_Extension
{
/**
* @var Toggle
*/
protected $toggle;
/**
* @param Toggle $toggle
*/
public function __construct(Toggle $toggle)
{
$this->toggle = $toggle;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('has_feature', [$this, 'checkFeature'], ['is_safe' => ['html']]),
];
}
/**
* @param string $name
* @param array $arguments
* @return bool
*/
public function checkFeature($name, $arguments = null)
{
return $this->toggle->isActive($name, $arguments);
}
public function getName()
{
return 'd_zunke_feature_extension';
}
}
|
Update frebsd-pkg-audit to rely on yaml data and take data from hubble.py | # -*- encoding: utf-8 -*-
'''
Hubble Nova plugin for FreeBSD pkgng audit
:maintainer: HubbleStack
:maturity: 20160421
:platform: FreeBSD
:requires: SaltStack
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def __virtual__():
if 'FreeBSD' not in __grains__['os']:
return False, 'This audit module only runs on FreeBSD'
return True
def audit(data_list, tags, verbose=False):
'''
Run the pkg.audit command
'''
ret = {'Success': [], 'Failure': []}
__tags__ = []
for data in data_list:
if 'freebsd-pkg' in data:
__tags__ = ['freebsd-pkg-audit']
break
if not __tags__:
# No yaml data found, don't do any work
return ret
salt_ret = __salt__['pkg.audit']()
if '0 problem(s)' not in salt_ret:
ret['Failure'].append(salt_ret)
else:
ret['Success'].append(salt_ret)
return ret
| # -*- encoding: utf-8 -*-
'''
Hubble Nova plugin for FreeBSD pkgng audit
:maintainer: HubbleStack
:maturity: 20160421
:platform: FreeBSD
:requires: SaltStack
'''
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
__tags__ = None
def __virtual__():
if 'FreeBSD' not in __grains__['os']:
return False, 'This audit module only runs on FreeBSD'
global __tags__
__tags__ = ['freebsd-pkg-audit']
return True
def audit(tags, verbose=False):
'''
Run the pkg.audit command
'''
ret = {'Success': [], 'Failure': []}
salt_ret = __salt__['pkg.audit']()
if '0 problem(s)' not in salt_ret:
ret['Failure'].append(salt_ret)
else:
ret['Success'].append(salt_ret)
return ret
|
Add unicode to test data generator. | function generateData(rows) {
var data = [];
for (var i = 0; i < rows; ++i) {
data.push({
"id": "#" + (i + 1),
"created_at": new Date().toDateString(),
"status": "In progress",
"title": "Test unicode €∑ĒŽŌ•ōļķņ© " + i + Math.round(Math.random() * 1000),
"count": Math.round(Math.random() * 100)
});
}
return data;
}
function getColumns(data) {
var firstRow = data[0];
return _.map(firstRow, function (val, key) {
return {name: key, type: "string"}
});
} | function generateData(rows) {
var data = [];
for (var i = 0; i < rows; ++i) {
data.push({
"id": "#" + (i + 1),
"created_at": new Date().toDateString(),
"status": "In progress",
"title": "Test " + i + Math.round(Math.random() * 1000),
"count": Math.round(Math.random() * 100)
});
}
return data;
}
function getColumns(data) {
var firstRow = data[0];
return _.map(firstRow, function (val, key) {
return {name: key, type: "string"}
});
}
//// define columns
//var columns = [
// {name: "id", type: "string"},
// {name: "created_at", type: "string"},
// {name: "status", type: "string", editor: "CustomEditor"},
// {name: "title", type: "string"},
// {name: "count", type: "string"}
//]; |
machete: Split DOM element selection and style reset | export class Machete {
// TODO: Implement polyfills
/**
* Utility function to get an element from the DOM.
* It is needed because everytime we get an element from the DOM,
* we reset its style to make sure code works as needed.
* @param string selector CSS selector
* @return Element Selected element
*/
static getDOMElement(selector) {
return Machete.resetStyles(document.querySelector(selector));
}
static resetStyles(element) {
let style = window.getComputedStyle(element);
element.style.left = style.left;
element.style.top = style.top;
element.style.width = style.width;
element.style.height = style.height;
element.style.transform = style.transform;
return element;
}
}
| export class Machete {
// TODO: Implement polyfills
/**
* Utility function to get an element from the DOM.
* It is needed because everytime we get an element from the DOM,
* we reset its style to make sure code works as needed.
* @param string selector CSS selector
* @return Element Selected element
*/
static getDOMElement(selector) {
let element = document.querySelector(selector),
style = window.getComputedStyle(element);
element.style.left = style.left;
element.style.top = style.top;
element.style.width = style.width;
element.style.height = style.height;
element.style.transform = style.transform;
return element;
}
}
|
Use Node 12's Array.flat() when available and start flattening tasks given to taskling.
It was already flattening tasks given to prepend() and append(). | 'use strict'
// ignore for coverage. its coverage is checked manually with the two different
// node versions required to test both branches of the statement.
/* istanbul ignore next */
const flatten = // allow nested arrays. try to use node 12's builtin flatten.
Array.prototype.flat ?
(array) => { return array.flat(Infinity) } // eslint-disable-line brace-style
: require('@flatten/array')
// shared - shared object given to every function as 2nd arg.
// taskArray - array of functions to call.
// done - error accepting callback.
// executor - defaults to process.nextTick, could be setImmediate.
module.exports = function runTasks(shared, taskArray, done, executor) {
// allow nested arrays.
const tasks = flatten(taskArray)
// run with nextTick by default.
const run = executor || process.nextTick
// combine tasks w/utils
const control = { prepend, append, clear, tasks }
// iterator given to each task.
function next(error, result) {
// end on error or all done.
if (error || tasks.length < 1) done(error, result)
// call next function.
else tasks.shift().call(control, next, shared)
}
run(next) // return now, begin async later.
}
function prepend(array) { // add array of tasks to front of tasks array
this.tasks.unshift.apply(this.tasks, flatten(array))
}
function append(array) { // add array of tasks to end of tasks array
this.tasks.push.apply(this.tasks, flatten(array))
}
function clear() { // empty tasks array
this.tasks.length = 0
}
| 'use strict'
const flatten = require('@flatten/array') // allow nested arrays
// shared - shared object given to every function as 2nd arg.
// tasks - array of functions to call.
// done - error accepting callback.
// executor - defaults to process.nextTick, could be setImmediate.
module.exports = function runTasks(shared, tasks, done, executor) {
// run with nextTick by default.
const run = executor || process.nextTick
// combine tasks w/utils
const control = { prepend, append, clear, tasks }
// iterator given to each task.
function next(error, result) {
// end on error or all done.
if (error || tasks.length < 1) done(error, result)
// call next function.
else tasks.shift().call(control, next, shared)
}
run(next) // return now, begin async later.
}
function prepend(array) { // add array of tasks to front of tasks array
this.tasks.unshift.apply(this.tasks, flatten(array))
}
function append(array) { // add array of tasks to end of tasks array
this.tasks.push.apply(this.tasks, flatten(array))
}
function clear() { // empty tasks array
this.tasks.length = 0
}
|
Add LONGTEXT type for MySQL | var Sequelize = require('sequelize');
var inflection = require('inflection');
$config.database.logging = $config.database.log ? console.log : false;
var sequelize = new Sequelize($config.database.name,
$config.database.user,
$config.database.pass,
$config.database);
var self = module.exports = {};
var models = require('node-require-directory')(__dirname);
Object.keys(models).forEach(function(key) {
var modelName = inflection.classify(key);
var modelInstance = sequelize.import(modelName , function(sequelize, DataTypes) {
var definition = [modelName].concat(models[key](DataTypes));
if (sequelize.options.dialect === 'mysql') {
DataTypes.LONGTEXT = 'LONGTEXT';
} else {
DataTypes.LONGTEXT = 'TEXT';
}
return sequelize.define.apply(sequelize, definition);
});
self[modelName] = modelInstance;
});
self.User.hasMany(self.Team);
self.Team.hasMany(self.User);
self.Project.hasMany(self.Team, { through: self.ProjectTeam });
self.Team.hasMany(self.Project, { through: self.ProjectTeam });
self.sequelize = self.DB = sequelize;
| var Sequelize = require('sequelize');
var inflection = require('inflection');
$config.database.logging = $config.database.log ? console.log : false;
var sequelize = new Sequelize($config.database.name,
$config.database.user,
$config.database.pass,
$config.database);
var self = module.exports = {};
var models = require('node-require-directory')(__dirname);
Object.keys(models).forEach(function(key) {
var modelName = inflection.classify(key);
var modelInstance = sequelize.import(modelName , function(sequelize, DataTypes) {
var definition = [modelName].concat(models[key](DataTypes));
return sequelize.define.apply(sequelize, definition);
});
self[modelName] = modelInstance;
});
self.User.hasMany(self.Team);
self.Team.hasMany(self.User);
self.Project.hasMany(self.Team, { through: self.ProjectTeam });
self.Team.hasMany(self.Project, { through: self.ProjectTeam });
self.sequelize = self.DB = sequelize;
|
[FIX] Make RecordingManager work with new plugin system | # -*- coding: utf-8 -*-
##
## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from MaKaC.i18n import _
pluginType = "Collaboration"
pluginName = "RecordingManager"
pluginDescription = _("Recording Manager")
| # -*- coding: utf-8 -*-
##
## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from MaKaC.plugins import getModules, initModule
from MaKaC.i18n import _
pluginType = "Collaboration"
pluginName = "RecordingManager"
pluginDescription = _("Recording Manager")
modules = {}
topModule = None
|
Update for 1.6.0 - TODO: Add Windows | from setuptools import setup
setup(
name = 'brunnhilde',
version = '1.6.0',
url = 'https://github.com/timothyryanwalsh/brunnhilde',
author = 'Tim Walsh',
author_email = 'timothyryanwalsh@gmail.com',
py_modules = ['brunnhilde'],
scripts = ['brunnhilde.py'],
description = 'A Siegfried-based digital archives reporting tool for directories and disk images',
keywords = 'archives reporting characterization identification diskimages',
platforms = ['POSIX'],
test_suite='test',
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: MacOS',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :: Linux',
'Topic :: Communications :: File Sharing',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Database',
'Topic :: System :: Archiving',
'Topic :: System :: Filesystems',
'Topic :: Utilities'
],
)
| from setuptools import setup
setup(
name = 'brunnhilde',
version = '1.5.4',
url = 'https://github.com/timothyryanwalsh/brunnhilde',
author = 'Tim Walsh',
author_email = 'timothyryanwalsh@gmail.com',
py_modules = ['brunnhilde'],
scripts = ['brunnhilde.py'],
description = 'A Siegfried-based digital archives reporting tool for directories and disk images',
keywords = 'archives reporting characterization identification diskimages',
platforms = ['POSIX'],
test_suite='test',
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: MacOS',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :: Linux',
'Topic :: Communications :: File Sharing',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Database',
'Topic :: System :: Archiving',
'Topic :: System :: Filesystems',
'Topic :: Utilities'
],
)
|
Add title when action buttons is disabled - FF fix | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.
*/
(function () {
'use strict';
var module = angular.module('pnc.common.authentication');
/**
* @ngdoc directive
* @name pnc.common.authentication:pncRequiresAuth
* @restrict A
* @description
* @example
* @author Alex Creasy
*/
module.directive('pncRequiresAuth', [
'authService',
function (authService) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
if (!authService.isAuthenticated()) {
attrs.$set('disabled', 'disabled');
attrs.$set('title', 'Log in to run this action');
attrs.$set('tooltip', ''); // hack to hide bootstrap tooltip in FF
elem.addClass('pointer-events-auto');
}
}
};
}
]);
})();
| /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.
*/
(function () {
'use strict';
var module = angular.module('pnc.common.authentication');
/**
* @ngdoc directive
* @name pnc.common.authentication:pncRequiresAuth
* @restrict A
* @description
* @example
* @author Alex Creasy
*/
module.directive('pncRequiresAuth', [
'authService',
function (authService) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
if (!authService.isAuthenticated()) {
attrs.$set('disabled', 'disabled');
attrs.$set('title', 'Log in to run this action');
elem.addClass('pointer-events-auto');
}
}
};
}
]);
})();
|
refactor: Fix classList misuse on error case
Fix the error on viewModel where assignment was used on document.body.classList instead of the add method. | var ViewModel = function() {
'use strict';
this.filter = ko.observable('');
this.drawerActive = ko.observable(false);
this.listActive = ko.observable(true);
this.toggleListAndDrawer = () => {
this.drawerActive(!this.drawerActive());
this.listActive(!this.listActive());
};
this.venues = ko.observableArray([]);
this.venuesToShow = ko.pureComputed(function() {
var filter = this.filter();
if (filter === '') {
return this.venues();
}
return ko.utils.arrayFilter(this.venues(), function(venue) {
// TODO: Make filtering UX MUCH better
return venue.category.tag === filter || venue.category.name === filter || venue.name === filter;
});
}, this);
dataModel.foursquare.then(data => {
this.venues(data);
}, function(error) {
console.error('Failed:', error);
document.body.classList.add('error', 'mdl-color--grey-300', 'mdl-color-text--grey-700');
document.body.innerHTML = '<h1 class="error__text">Oops, something went wrong</h1>';
});
};
ko.applyBindings(new ViewModel());
| var ViewModel = function() {
'use strict';
this.filter = ko.observable('');
this.drawerActive = ko.observable(false);
this.listActive = ko.observable(true);
this.toggleListAndDrawer = () => {
this.drawerActive(!this.drawerActive());
this.listActive(!this.listActive());
};
this.venues = ko.observableArray([]);
this.venuesToShow = ko.pureComputed(function() {
var filter = this.filter();
if (filter === '') {
return this.venues();
}
return ko.utils.arrayFilter(this.venues(), function(venue) {
// TODO: Make filtering UX MUCH better
return venue.category.tag === filter || venue.category.name === filter || venue.name === filter;
});
}, this);
dataModel.foursquare.then(data => {
this.venues(data);
}, function(error) {
console.error('Failed:', error);
document.body.classList = 'error mdl-color--grey-300 mdl-color-text--grey-700';
document.body.innerHTML = '<h1 class="error__text">Oops, something went wrong</h1>';
});
};
ko.applyBindings(new ViewModel());
|
Fix splunk module name (splunk => splunklib) | #!/usr/bin/env python
#
# Copyright 2011-2012 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from distutils.core import setup
import splunklib
setup(
author="Splunk, Inc.",
author_email="devinfo@splunk.com",
description="The Splunk Software Development Kit for Python.",
license="http://www.apache.org/licenses/LICENSE-2.0",
name="splunk-sdk",
packages = ["splunklib"],
url="http://github.com/splunk/splunk-sdk-python",
version=splunklib.__version__,
classifiers = [
"Programming Language :: Python",
"Development Status :: 3 - Alpha",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: Libraries :: Application Frameworks",
],
)
| #!/usr/bin/env python
#
# Copyright 2011-2012 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from distutils.core import setup
import splunk
setup(
author="Splunk, Inc.",
author_email="devinfo@splunk.com",
description="The Splunk Software Development Kit for Python.",
license="http://www.apache.org/licenses/LICENSE-2.0",
name="splunk-sdk",
packages = ["splunk"],
url="http://github.com/splunk/splunk-sdk-python",
version=splunk.__version__,
classifiers = [
"Programming Language :: Python",
"Development Status :: 3 - Alpha",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: Libraries :: Application Frameworks",
],
)
|
Implement regex pattern for list values | # -*- coding: utf-8 -*-
INDENT = r"(?P<indent>^ *)"
VARIABLE = r"(?P<variable>.+):"
VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
NEWLINE = r"$\n"
BLANK = r" +"
INLINE_COMMENT = r"(?: +#.*)?"
COMMENT = r"^ *#.*" + NEWLINE
BLANK_LINE = r"^[ \t]*" + NEWLINE
DASHES = r"^---" + NEWLINE
SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE
SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE
LISTITEM = BLANK + r"-" + BLANK + VALUE + INLINE_COMMENT + NEWLINE
LIST = SECTION + r"(?P<items>(?:(?P=indent)" + LISTITEM + r")+)"
NULL = r"\b(null|Null|NULL|~)\b"
TRUE = r"\b(true|True|TRUE)\b"
FALSE = r"\b(false|False|FALSE)\b"
INT = r"[-+]?[0-9]+"
FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)"
STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
| # -*- coding: utf-8 -*-
INDENT = r"(?P<indent>^ *)"
VARIABLE = r"(?P<variable>.+):"
VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
NEWLINE = r"$\n"
BLANK = r" +"
INLINE_COMMENT = r"(?: +#.*)?"
COMMENT = r"^ *#.*" + NEWLINE
BLANK_LINE = r"^[ \t]*" + NEWLINE
DASHES = r"^---" + NEWLINE
SECTION = INDENT + VARIABLE + INLINE_COMMENT + NEWLINE
SIMPLE = INDENT + VARIABLE + BLANK + VALUE + INLINE_COMMENT + NEWLINE
NULL = r"\b(null|Null|NULL|~)\b"
TRUE = r"\b(true|True|TRUE)\b"
FALSE = r"\b(false|False|FALSE)\b"
INT = r"[-+]?[0-9]+"
FLOAT = r"([-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?)"
STR = r"(?P<quotes>['\"]?).*(?P=quotes)"
|
migrations: Fix typo in 0099 reverse_sql.
Signed-off-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com> | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("zerver", "0098_index_has_alert_word_user_messages"),
]
operations = [
migrations.RunSQL(
"""
CREATE INDEX IF NOT EXISTS zerver_usermessage_wildcard_mentioned_message_id
ON zerver_usermessage (user_profile_id, message_id)
WHERE (flags & 8) != 0 OR (flags & 16) != 0;
""",
reverse_sql="DROP INDEX zerver_usermessage_wildcard_mentioned_message_id;",
),
]
| from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("zerver", "0098_index_has_alert_word_user_messages"),
]
operations = [
migrations.RunSQL(
"""
CREATE INDEX IF NOT EXISTS zerver_usermessage_wildcard_mentioned_message_id
ON zerver_usermessage (user_profile_id, message_id)
WHERE (flags & 8) != 0 OR (flags & 16) != 0;
""",
reverse_sql="DROP INDEX zerver_usermessage_wilcard_mentioned_message_id;",
),
]
|
Add java to automatic conversions | var codes = document.getElementsByTagName("code");
var title, elTitle, elPre;
for (var i=0, l=codes.length ; i<l ; i++) {
elPre = codes[i].parentNode;
if (elPre.tagName != "PRE") continue;
// Prepare for highlighting
// elPre.className = elPre.className.replace("sourceCode ","");
if (elPre.className.match("sourceCode"))
switch (elPre.className.replace("sourceCode ","")) {
case 'css':
case 'haskell':
case 'html':
case 'php':
case 'java':
case 'python':
elPre.className = "sourceCode sh_" + elPre.className.replace("sourceCode ", "");
break;
case 'js':
elPre.className += " sh_javascript";
case 'literate haskell':
elPre.className += " sh_haskell";
break;
}
}
//sh_highlightDocument("/static/js/lang/", ".js");
| var codes = document.getElementsByTagName("code");
var title, elTitle, elPre;
for (var i=0, l=codes.length ; i<l ; i++) {
elPre = codes[i].parentNode;
if (elPre.tagName != "PRE") continue;
// Prepare for highlighting
// elPre.className = elPre.className.replace("sourceCode ","");
if (elPre.className.match("sourceCode"))
switch (elPre.className.replace("sourceCode ","")) {
case 'css':
case 'haskell':
case 'html':
case 'php':
case 'python':
elPre.className = "sourceCode sh_" + elPre.className.replace("sourceCode ", "");
break;
case 'js':
elPre.className += " sh_javascript";
case 'literate haskell':
elPre.className += " sh_haskell";
break;
}
}
//sh_highlightDocument("/static/js/lang/", ".js");
|
Include Redux DevTools extension in the content script | // dev only: async fetch bundle
const arrowURLs = [ 'https://github.com' ];
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status !== 'loading') return;
const matched = arrowURLs.every(url => !!tab.url.match(url));
if (!matched) return;
chrome.tabs.executeScript(tabId, {
code: 'var injected = window.browserReduxInjected; window.browserReduxInjected = true; injected;',
runAt: 'document_start'
}, (result) => {
if (chrome.runtime.lastError || result[0]) return;
fetch('http://localhost:3000/js/inject.bundle.js').then(response => {
return response.text();
}).then(response => {
// Include Redux DevTools extension
const httpRequest = new XMLHttpRequest();
httpRequest.open('GET', 'chrome-extension://lmhkpmbekcpmknklioeibfkpmmfibljd/js/inject.bundle.js');
httpRequest.send();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
chrome.tabs.executeScript(tabId, { code: httpRequest.responseText, runAt: 'document_start' });
}
};
chrome.tabs.executeScript(tabId, { code: response, runAt: 'document_end' });
});
});
});
| // dev only: async fetch bundle
const arrowURLs = [ 'https://github.com' ];
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status !== 'loading') return;
const matched = arrowURLs.every(url => !!tab.url.match(url));
if (!matched) return;
chrome.tabs.executeScript(tabId, {
code: 'var injected = window.browserReduxInjected; window.browserReduxInjected = true; injected;',
runAt: 'document_start'
}, (result) => {
if (chrome.runtime.lastError || result[0]) return;
fetch('http://localhost:3000/js/inject.bundle.js').then(response => {
return response.text();
}).then(response => {
chrome.tabs.executeScript(tabId, { code: response, runAt: 'document_end' });
});
});
});
|
Switch BooleanChoiceField to use Select widget instead of the RadioSelect widget | from django import forms
from django.utils.translation import ugettext_lazy as _
def boolean_coerce(value):
if value in {1, '1'}:
return True
if value in {0, '0'}:
return False
class BooleanChoiceField(forms.TypedChoiceField):
widget = forms.Select
def __init__(self, *args, **kwargs):
defaults = {
'choices': [
('1', _('Yes')),
('0', _('No')),
],
'coerce': boolean_coerce,
'required': True,
}
defaults.update(kwargs)
super(BooleanChoiceField, self).__init__(*args, **defaults)
def prepare_value(self, value):
if value is not None:
return str(int(value))
| from django import forms
from django.utils.translation import ugettext_lazy as _
def boolean_coerce(value):
if value in {1, '1'}:
return True
if value in {0, '0'}:
return False
class BooleanChoiceField(forms.TypedChoiceField):
widget = forms.RadioSelect
def __init__(self, *args, **kwargs):
defaults = {
'choices': [
('1', _('Yes')),
('0', _('No')),
],
'coerce': boolean_coerce,
'required': True,
}
defaults.update(kwargs)
super(BooleanChoiceField, self).__init__(*args, **defaults)
def prepare_value(self, value):
if value is not None:
return str(int(value))
|
Fix the UMD bundle that would still use modules | import babel from 'rollup-plugin-babel';
import nodeResolve from 'rollup-plugin-node-resolve';
import uglify from 'rollup-plugin-uglify';
import bundleSize from 'rollup-plugin-bundle-size';
import commonjs from 'rollup-plugin-commonjs';
const name = `isLoading`;
const plugins = [
babel(),
nodeResolve({
module: false,
jsnext: true
}),
commonjs({
include: `node_modules/**`
}),
bundleSize()
];
const isProd = process.env.NODE_ENV === `production`;
if (isProd) plugins.push(uglify());
const isExample = process.env.NODE_ENV === `example`;
let config = {
entry: `src/index.js`,
plugins,
dest: `dist/${name}${isProd ? `.min` : ``}.js`,
moduleName: name,
format: `umd`
};
if (isExample) {
Object.assign(config, {
entry: `example/sample.js`,
dest: `example/sample.bundle.js`,
plugins
});
}
export default config;
| import babel from 'rollup-plugin-babel';
import nodeResolve from 'rollup-plugin-node-resolve';
import uglify from 'rollup-plugin-uglify';
import bundleSize from 'rollup-plugin-bundle-size';
import commonjs from 'rollup-plugin-commonjs';
const name = `isLoading`;
const plugins = [
babel(),
nodeResolve({
module: true,
jsnext: true
}),
commonjs({
include: `node_modules/**`
}),
bundleSize()
];
const isProd = process.env.NODE_ENV === `production`;
if (isProd) plugins.push(uglify());
const isExample = process.env.NODE_ENV === `example`;
let config = {
entry: `src/index.js`,
plugins,
dest: `dist/${name}${isProd ? `.min` : ``}.js`,
moduleName: name,
format: `umd`
};
if (isExample) {
Object.assign(config, {
entry: `example/sample.js`,
dest: `example/sample.bundle.js`,
plugins
});
}
export default config;
|
Add trailing slash to url | from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from derrida.books.views import (
PublisherAutocomplete, LanguageAutocomplete, InstanceDetailView,
InstanceListView
)
urlpatterns = [
# TODO: come up with cleaner url patterns/names for autocomplete views
url(r'^publishers/autocomplete/$', staff_member_required(PublisherAutocomplete.as_view()),
name='publisher-autocomplete'),
url(r'^languages/autocomplete/$', staff_member_required(LanguageAutocomplete.as_view()),
name='language-autocomplete'),
url(r'^(?P<pk>\d+)/$', InstanceDetailView.as_view(), name='detail'),
url(r'^$', InstanceListView.as_view(), name='list'),
]
| from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from derrida.books.views import (
PublisherAutocomplete, LanguageAutocomplete, InstanceDetailView,
InstanceListView
)
urlpatterns = [
# TODO: come up with cleaner url patterns/names for autocomplete views
url(r'^publishers/autocomplete/$', staff_member_required(PublisherAutocomplete.as_view()),
name='publisher-autocomplete'),
url(r'^languages/autocomplete/$', staff_member_required(LanguageAutocomplete.as_view()),
name='language-autocomplete'),
url(r'^(?P<pk>\d+)$', InstanceDetailView.as_view(), name='detail'),
url(r'^$', InstanceListView.as_view(), name='list'),
]
|
Return lowercased random tokens for consistency. | import random
import hashlib
import base64
def generate_key():
key = hashlib.sha224(str(random.getrandbits(256))).digest()
key = base64.b64encode(key,
random.choice(['rA','aZ','gQ','hH','hG','aR','DD']))
key = key.rstrip('==').lower()
return key
def chunked(seq, n):
"""By Ned Batchelder.
Yield successive n-sized chunks from seq.
>>> for group in chunked(range(8), 3):
... print group
[0, 1, 2]
[3, 4, 5]
[6, 7]
"""
for i in xrange(0, len(seq), n):
yield seq[i:i+n]
def flatten(lst):
for elem in lst:
if hasattr(elem, '__iter__'):
for e in flatten(elem):
yield e
else:
yield elem
def find_dict_key(dictionary, search_value):
for key, value in dictionary.iteritems():
if value == search_value:
return key
def extract(dictionary, keys):
"""Returns a new dictionary with only the keys from the dictionary passed in
specified in the keys list.
"""
return dict((key, dictionary[key]) for key in keys if key in dictionary)
| import random
import hashlib
import base64
def generate_key():
key = hashlib.sha224(str(random.getrandbits(256))).digest()
key = base64.b64encode(key,
random.choice(['rA','aZ','gQ','hH','hG','aR','DD']))
key = key.rstrip('==')
return key
def chunked(seq, n):
"""By Ned Batchelder.
Yield successive n-sized chunks from seq.
>>> for group in chunked(range(8), 3):
... print group
[0, 1, 2]
[3, 4, 5]
[6, 7]
"""
for i in xrange(0, len(seq), n):
yield seq[i:i+n]
def flatten(lst):
for elem in lst:
if hasattr(elem, '__iter__'):
for e in flatten(elem):
yield e
else:
yield elem
def find_dict_key(dictionary, search_value):
for key, value in dictionary.iteritems():
if value == search_value:
return key
def extract(dictionary, keys):
"""Returns a new dictionary with only the keys from the dictionary passed in
specified in the keys list.
"""
return dict((key, dictionary[key]) for key in keys if key in dictionary)
|
Allow ecdsa 384 bit keys too | from django.db import models
KEYTYPE_CHOICES = (
('RSA', 'ssh-rsa'),
('DSA', 'ssh-dsa'),
('ECC-256', 'ecdsa-sha2-nistp256'),
('ECC-384', 'ecdsa-sha2-nistp384'),
('ECC-521', 'ecdsa-sha2-nistp521'),
)
class Node(models.Model):
name = models.CharField(unique=True, primary_key=True, max_length=256)
hostname = models.CharField(blank=True, max_length=256)
public_keys = models.ManyToManyField('OpensshKey')
def __unicode__(self):
return self.name
class OpensshKey(models.Model):
name = models.CharField(unique=True, max_length=256)
keytype = models.CharField(max_length=6, choices=KEYTYPE_CHOICES)
key = models.TextField()
host = models.CharField(max_length=256, blank=True)
def __unicode__(self):
return self.name
| from django.db import models
KEYTYPE_CHOICES = (
('RSA', 'ssh-rsa'),
('DSA', 'ssh-dsa'),
('ECC-256', 'ecdsa-sha2-nistp256'),
('ECC-521', 'ecdsa-sha2-nistp521'),
)
class Node(models.Model):
name = models.CharField(unique=True, primary_key=True, max_length=256)
hostname = models.CharField(blank=True, max_length=256)
public_keys = models.ManyToManyField('OpensshKey')
def __unicode__(self):
return self.name
class OpensshKey(models.Model):
name = models.CharField(unique=True, max_length=256)
keytype = models.CharField(max_length=6, choices=KEYTYPE_CHOICES)
key = models.TextField()
host = models.CharField(max_length=256, blank=True)
def __unicode__(self):
return self.name
|
Insert request method option storage driver URLFor
Docker-DCO-1.1-Signed-off-by: Josh Hawn <josh.hawn@docker.com> (github: jlhawn) | package storage
import (
"net/http"
"time"
"github.com/docker/distribution"
"github.com/docker/distribution/digest"
)
// layerReader implements Layer and provides facilities for reading and
// seeking.
type layerReader struct {
fileReader
digest digest.Digest
}
var _ distribution.Layer = &layerReader{}
func (lr *layerReader) Digest() digest.Digest {
return lr.digest
}
func (lr *layerReader) Length() int64 {
return lr.size
}
func (lr *layerReader) CreatedAt() time.Time {
return lr.modtime
}
// Close the layer. Should be called when the resource is no longer needed.
func (lr *layerReader) Close() error {
return lr.closeWithErr(distribution.ErrLayerClosed)
}
func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Docker-Content-Digest", lr.digest.String())
if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{"method": r.Method}); err == nil {
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr)
}
| package storage
import (
"net/http"
"time"
"github.com/docker/distribution"
"github.com/docker/distribution/digest"
)
// layerReader implements Layer and provides facilities for reading and
// seeking.
type layerReader struct {
fileReader
digest digest.Digest
}
var _ distribution.Layer = &layerReader{}
func (lr *layerReader) Digest() digest.Digest {
return lr.digest
}
func (lr *layerReader) Length() int64 {
return lr.size
}
func (lr *layerReader) CreatedAt() time.Time {
return lr.modtime
}
// Close the layer. Should be called when the resource is no longer needed.
func (lr *layerReader) Close() error {
return lr.closeWithErr(distribution.ErrLayerClosed)
}
func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Docker-Content-Digest", lr.digest.String())
if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{}); err == nil {
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr)
}
|
Whitelist params returned from isMobile
Fixes bugs where the environment leaks through isMobile. | import Service from 'ember-service';
import get, { getProperties } from 'ember-metal/get';
import set from 'ember-metal/set';
import computed from 'ember-computed';
import getOwner from 'ember-owner/get';
import isMobile from 'ismobilejs';
export default Service.extend({
fastboot: computed(function() {
return getOwner(this).lookup('service:fastboot');
}),
init() {
this._super(...arguments);
let queries;
if (get(this, 'fastboot.isFastBoot')) {
const headers = get(this, 'fastboot.request.headers');
const userAgent = headers.get('user-agent');
queries = getProperties(isMobile(userAgent), ['any', 'phone', 'tablet', 'apple', 'android', 'amazon', 'windows', 'seven_inch', 'other']);
} else {
queries = isMobile;
}
for (let media in queries) {
set(this, media, queries[media]);
}
}
}); | import Service from 'ember-service';
import get from 'ember-metal/get';
import set from 'ember-metal/set';
import computed from 'ember-computed';
import getOwner from 'ember-owner/get';
import isMobile from 'ismobilejs';
export default Service.extend({
fastboot: computed(function() {
return getOwner(this).lookup('service:fastboot');
}),
init() {
this._super(...arguments);
let queries;
if (get(this, 'fastboot.isFastBoot')) {
const headers = get(this, 'fastboot.request.headers');
const userAgent = headers.get('user-agent');
queries = isMobile(userAgent);
} else {
queries = isMobile;
}
for (let media in queries) {
set(this, media, queries[media]);
}
}
}); |
Add siblings to forum serializer | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from machina.core.db.models import get_model
from rest_framework import serializers
Forum = get_model('forum', 'Forum')
class ForumSerializer(serializers.ModelSerializer):
description = serializers.SerializerMethodField()
previous_sibling = serializers.SerializerMethodField()
next_sibling = serializers.SerializerMethodField()
class Meta:
model = Forum
fields = [
'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects',
'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on',
'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent',
'previous_sibling', 'next_sibling',
]
def get_description(self, obj):
return obj.description.rendered
def get_previous_sibling(self, obj):
sibling = obj.get_previous_sibling()
return sibling.pk if sibling else None
def get_next_sibling(self, obj):
sibling = obj.get_next_sibling()
return sibling.pk if sibling else None
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from machina.core.db.models import get_model
from rest_framework import serializers
Forum = get_model('forum', 'Forum')
class ForumSerializer(serializers.ModelSerializer):
description = serializers.SerializerMethodField()
class Meta:
model = Forum
fields = [
'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects',
'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on',
'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent',
]
def get_description(self, obj):
return obj.description.rendered
|
Update description with more detailed description | var yeoman = require('yeoman-generator');
module.exports = yeoman.generators.Base.extend({
constructor: function () {
yeoman.generators.Base.apply(this, arguments);
var options = require('./options/index');
this.description = "Yeoman generator that provides already configured and optimized Sails REST API with bundle of predefined features";
Object.keys(options).forEach(function (name) {
this.option(name, options[name]);
}.bind(this));
this.config.save();
},
initializing: require('./steps/initializing'),
prompting: require('./steps/prompting'),
configuring: require('./steps/configuring'),
writing: require('./steps/writing'),
conflicts: require('./steps/conflicts'),
install: require('./steps/install'),
end: require('./steps/end')
});
| var yeoman = require('yeoman-generator');
module.exports = yeoman.generators.Base.extend({
constructor: function () {
yeoman.generators.Base.apply(this, arguments);
var options = require('./options/index');
this.description = "Yeoman generator for scaffolding Sails REST API with predefined features";
Object.keys(options).forEach(function (name) {
this.option(name, options[name]);
}.bind(this));
this.config.save();
},
initializing: require('./steps/initializing'),
prompting: require('./steps/prompting'),
configuring: require('./steps/configuring'),
writing: require('./steps/writing'),
conflicts: require('./steps/conflicts'),
install: require('./steps/install'),
end: require('./steps/end')
});
|
Fix irregular whitespace linter error. | import React, {PropTypes, Component} from 'react'
import Dropdown from 'shared/components/Dropdown'
import {showDatabases} from 'shared/apis/metaQuery'
import showDatabasesParser from 'shared/parsing/showDatabases'
class DatabaseDropdown extends Component {
constructor(props) {
super(props)
this.state = {
databases: [],
}
}
componentDidMount() {
const {source} = this.context
const {database, onSelectDatabase} = this.props
const proxy = source.links.proxy
showDatabases(proxy).then(resp => {
const {databases} = showDatabasesParser(resp.data)
this.setState({databases})
const selected = databases.includes(database)
? database
: databases[0] || 'No databases'
onSelectDatabase({text: selected})
})
}
render() {
const {databases} = this.state
const {database, onSelectDatabase} = this.props
return (
<Dropdown
items={databases.map(text => ({text}))}
selected={database}
onChoose={onSelectDatabase}
/>
)
}
}
const {func, shape, string} = PropTypes
DatabaseDropdown.contextTypes = {
source: shape({
links: shape({
proxy: string.isRequired,
}).isRequired,
}).isRequired,
}
DatabaseDropdown.propTypes = {
database: string,
onSelectDatabase: func.isRequired,
}
export default DatabaseDropdown
| import React, {PropTypes, Component} from 'react'
import Dropdown from 'shared/components/Dropdown'
import {showDatabases} from 'shared/apis/metaQuery'
import showDatabasesParser from 'shared/parsing/showDatabases'
class DatabaseDropdown extends Component {
constructor(props) {
super(props)
this.state = {
databases: [],
}
}
componentDidMount() {
const {source} = this.context
const {database, onSelectDatabase} = this.props
const proxy = source.links.proxy
showDatabases(proxy).then(resp => {
const {databases} = showDatabasesParser(resp.data)
this.setState({databases})
const selected = databases.includes(database) ? database : databases[0] || 'No databases'
onSelectDatabase({text: selected})
})
}
render() {
const {databases} = this.state
const {database, onSelectDatabase} = this.props
return (
<Dropdown
items={databases.map(text => ({text}))}
selected={database}
onChoose={onSelectDatabase}
/>
)
}
}
const {func, shape, string} = PropTypes
DatabaseDropdown.contextTypes = {
source: shape({
links: shape({
proxy: string.isRequired,
}).isRequired,
}).isRequired,
}
DatabaseDropdown.propTypes = {
database: string,
onSelectDatabase: func.isRequired,
}
export default DatabaseDropdown
|
Change Status filters to build from constant | """
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from sentry.constants import STATUS_LEVELS
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
choices = SortedDict(STATUS_LEVELS)
def get_choices(self):
return self.choices
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
| """
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
def get_choices(self):
return SortedDict([
(0, _('Unresolved')),
(1, _('Resolved')),
])
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
|
Fix double-layer overlay on create channel on iOS | // @flow
import TeamsContainer from './container'
import {RouteDefNode} from '../route-tree'
import NewTeamDialog from './new-team/container'
import ManageChannels from '../chat/manage-channels/container'
import CreateChannel from '../chat/create-channel/container'
import ReallyLeaveTeam from './really-leave-team/container'
import Team from './team/container'
import {isMobile} from '../constants/platform'
const makeManageChannels = () => ({
manageChannels: {
children: {},
component: ManageChannels,
tags: {layerOnTop: true},
},
createChannel: {
children: {},
component: CreateChannel,
tags: {layerOnTop: !isMobile},
},
})
const routeTree = new RouteDefNode({
children: {
...makeManageChannels(),
showNewTeamDialog: {
children: {},
component: NewTeamDialog,
tags: {layerOnTop: true},
},
team: {
children: {
...makeManageChannels(),
reallyLeaveTeam: {
children: {},
component: ReallyLeaveTeam,
tags: {layerOnTop: !isMobile},
},
},
component: Team,
},
},
component: TeamsContainer,
tags: {title: 'Teams'},
})
export default routeTree
| // @flow
import TeamsContainer from './container'
import {RouteDefNode} from '../route-tree'
import NewTeamDialog from './new-team/container'
import ManageChannels from '../chat/manage-channels/container'
import CreateChannel from '../chat/create-channel/container'
import ReallyLeaveTeam from './really-leave-team/container'
import Team from './team/container'
import {isMobile} from '../constants/platform'
const makeManageChannels = () => ({
manageChannels: {
children: {},
component: ManageChannels,
tags: {layerOnTop: true},
},
createChannel: {
children: {},
component: CreateChannel,
tags: {layerOnTop: true},
},
})
const routeTree = new RouteDefNode({
children: {
...makeManageChannels(),
showNewTeamDialog: {
children: {},
component: NewTeamDialog,
tags: {layerOnTop: true},
},
team: {
children: {
...makeManageChannels(),
reallyLeaveTeam: {
children: {},
component: ReallyLeaveTeam,
tags: {layerOnTop: !isMobile},
},
},
component: Team,
},
},
component: TeamsContainer,
tags: {title: 'Teams'},
})
export default routeTree
|
Use a OneToMany field for the activity joiner. | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_together = (("group", "grouptype", "disabled", "time"),)
class ActivityEntry(models.Model):
user = models.OneToOneField(
'tracker.Tbluser',
related_name="user_foreign"
)
activity = models.OneToOneField(
Activity,
related_name="activity_foreign"
)
amount = models.BigIntegerField()
def time(self):
return self.activity.time * self.amount
| from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_together = (("group", "grouptype", "disabled", "time"),)
class ActivityEntry(models.Model):
user = models.ManyToManyField(
'tracker.Tbluser',
related_name="user_foreign"
)
activity = models.ManyToManyField(
Activity,
related_name="activity_foreign"
)
amount = models.BigIntegerField()
def time(self):
return self.activity.time * self.amount
|
Change prompt to a diamond | #!/usr/bin/env python3
import token
import lexer as l
import parser as p
import evaluator as e
import context as c
def main(ctx):
string = input("⧫ ")
string = string.replace("\\n", "\n") + ";"
tokens = l.lex(string)
parser = p.Parser(tokens)
program = parser.parse_program()
if len(parser.errors) > 0:
parser.print_errors()
else:
# print(program)
print(e.eval(program, ctx))
if __name__ == "__main__":
ctx = c.Context()
while True:
try:
main(ctx)
except (KeyboardInterrupt, EOFError):
print('Goodbye!')
break
| #!/usr/bin/env python3
import token
import lexer as l
import parser as p
import evaluator as e
import context as c
def main(ctx):
string = input(">> ")
string = string.replace("\\n", "\n") + ";"
tokens = l.lex(string)
parser = p.Parser(tokens)
program = parser.parse_program()
if len(parser.errors) > 0:
parser.print_errors()
else:
# print(program)
print(e.eval(program, ctx))
if __name__ == "__main__":
ctx = c.Context()
while True:
try:
main(ctx)
except (KeyboardInterrupt, EOFError):
print('Goodbye!')
break
|
Add shortcut -f (force) for artisan publish commands | <?php
declare(strict_types=1);
namespace Rinvex\Auth\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:publish:auth {--f|force : Overwrite any existing files.} {--r|resource=all}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Rinvex Auth Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
$this->call('vendor:publish', ['--tag' => 'rinvex-auth-config', '--force' => $this->option('force')]);
$this->line('');
}
}
| <?php
declare(strict_types=1);
namespace Rinvex\Auth\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rinvex:publish:auth {--force : Overwrite any existing files.} {--R|resource=all}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Rinvex Auth Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
$this->call('vendor:publish', ['--tag' => 'rinvex-auth-config', '--force' => $this->option('force')]);
$this->line('');
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.