text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Remove unnecessary aliases for Ember utils | import Em from 'ember';
import { ArrayController } from 'ember-legacy-controllers';
const ArrayPauser = ArrayController.extend({
isPaused: false,
buffer: Em.computed(function () {
return Em.A();
}),
addToBuffer: function (idx, removedCount, added) {
const buffer = this.get('buffer');
buffer.pushObject([idx, removedCount, added]);
},
clearBuffer: Em.observer('isPaused', function () {
const buffer = this.get('buffer');
const arrangedContent = this.get('arrangedContent');
buffer.forEach((args) => {
arrangedContent.replace(...args);
});
buffer.clear();
}),
arrangedContent: Em.computed('content', function () {
const content = this.get('content');
const clone = Em.copy(content);
return clone;
}),
contentArrayDidChange: function (arr, idx, removedCount, addedCount) {
const added = arr.slice(idx, idx + addedCount);
const isPaused = this.get('isPaused');
let arrangedContent;
if (isPaused) {
this.addToBuffer(idx, removedCount, added);
}
else {
arrangedContent = this.get('arrangedContent');
arrangedContent.replace(idx, removedCount, added);
}
},
});
export default ArrayPauser;
| import Em from 'ember';
import { ArrayController } from 'ember-legacy-controllers';
const get = Em.get;
const copy = Em.copy;
const ArrayPauser = ArrayController.extend({
isPaused: false,
buffer: Em.computed(function () {
return Em.A();
}),
addToBuffer: function (idx, removedCount, added) {
const buffer = get(this, 'buffer');
buffer.pushObject([idx, removedCount, added]);
},
clearBuffer: Em.observer('isPaused', function () {
const buffer = get(this, 'buffer');
const arrangedContent = get(this, 'arrangedContent');
buffer.forEach((args) => {
arrangedContent.replace(...args);
});
buffer.clear();
}),
arrangedContent: Em.computed('content', function () {
const content = get(this, 'content');
const clone = copy(content);
return clone;
}),
contentArrayDidChange: function (arr, idx, removedCount, addedCount) {
const added = arr.slice(idx, idx + addedCount);
const isPaused = get(this, 'isPaused');
let arrangedContent;
if (isPaused) {
this.addToBuffer(idx, removedCount, added);
}
else {
arrangedContent = get(this, 'arrangedContent');
arrangedContent.replace(idx, removedCount, added);
}
},
});
export default ArrayPauser;
|
Add a more descriptive message at ModelNotFoundException | <?php
abstract class ActiveRecordBase {
public function delete() {
$id = $this->id;
db_delete(
$this->tableName,
compact( "id" )
);
}
public function save() {
$this->validate();
if ( $this->exists ) {
$this->update();
}
else {
$this->create();
}
}
}
class ModelNotFoundException extends Exception {
public function __construct() {
parent::__construct( 'Model not found' );
}
}
class ModelValidationException extends Exception {
public $error;
public function __construct( $error = "" ) {
parent::__construct( "Model validation error: " . $error );
$this->error = $error;
}
}
?>
| <?php
abstract class ActiveRecordBase {
public function delete() {
$id = $this->id;
db_delete(
$this->tableName,
compact( "id" )
);
}
public function save() {
$this->validate();
if ( $this->exists ) {
$this->update();
}
else {
$this->create();
}
}
}
class ModelNotFoundException extends Exception {
public function __construct() {
parent::__construct( 'NotFound' );
}
}
class ModelValidationException extends Exception {
public $error;
public function __construct( $error = "" ) {
parent::__construct( "Model validation error: " . $error );
$this->error = $error;
}
}
?>
|
Use textContent instead of innerHTML. | "use strict";
chrome.sessions.getDevices({}, function(sessions){
for (var i in sessions) {
var device = sessions[i];
var deviceDiv = document.createElement("div");
deviceDiv.classList.add("device");
var deviceName = document.createElement("div");
deviceName.textContent = device.deviceName;
deviceName.classList.add("device-name");
deviceDiv.appendChild(deviceName);
var sessionsDiv = document.createElement("div");
sessionsDiv.classList.add("sessions");
for (var j in device.sessions) {
var session = device.sessions[j];
var sessionDiv = document.createElement("div");
sessionDiv.classList.add("session");
for (var k in session.window.tabs) {
var tab = session.window.tabs[k];
var link = document.createElement("a");
link.href = tab.url;
link.textContent = tab.title;
link.title = tab.title;
link.classList.add("link");
sessionDiv.appendChild(link);
}
sessionsDiv.appendChild(sessionDiv);
}
deviceDiv.appendChild(sessionsDiv);
document.getElementById("main").appendChild(deviceDiv);
}
});
| "use strict";
chrome.sessions.getDevices({}, function(sessions){
for (var i in sessions) {
var device = sessions[i];
var deviceDiv = document.createElement("div");
deviceDiv.classList.add("device");
var deviceName = document.createElement("div");
deviceName.innerHTML = device.deviceName;
deviceName.classList.add("device-name");
deviceDiv.appendChild(deviceName);
var sessionsDiv = document.createElement("div");
sessionsDiv.classList.add("sessions");
for (var j in device.sessions) {
var session = device.sessions[j];
var sessionDiv = document.createElement("div");
sessionDiv.classList.add("session");
for (var k in session.window.tabs) {
var tab = session.window.tabs[k];
var link = document.createElement("a");
link.href = tab.url;
link.innerHTML = tab.title;
link.title = tab.title;
link.classList.add("link");
sessionDiv.appendChild(link);
}
sessionsDiv.appendChild(sessionDiv);
}
deviceDiv.appendChild(sessionsDiv);
document.getElementById("main").appendChild(deviceDiv);
}
});
|
en-2018-04-22: Make a statement concerning requests 3.x more precise.
requests 3 has not yet been released, so it may theoretically happen that the
fix will be also needed for requests 3.x. | #!/usr/bin/env python3
#
# An HTTP client that checks that the content of the response has at least
# Content-Length bytes.
#
# For requests 2.x (should not be needed for requests 3.x).
#
import requests
import sys
response = requests.get('http://localhost:8080/')
if not response.ok:
sys.exit('error: HTTP {}'.format(response.status_code))
# Check that we have read all the data as the requests library does not
# currently enforce this.
expected_length = response.headers.get('Content-Length')
if expected_length is not None:
# We cannot use len(response.content) as this would not work when the body
# of the response was compressed (e.g. when the response has
# `Content-Encoding: gzip`).
actual_length = response.raw.tell()
expected_length = int(expected_length)
if actual_length < expected_length:
raise IOError(
'incomplete read ({} bytes read, {} more expected)'.format(
actual_length,
expected_length - actual_length
)
)
print(response.headers)
print(response.content)
print(len(response.content))
| #!/usr/bin/env python3
#
# An HTTP client that checks that the content of the response has at least
# Content-Length bytes.
#
# For requests 2.x (not needed for requests 3.x).
#
import requests
import sys
response = requests.get('http://localhost:8080/')
if not response.ok:
sys.exit('error: HTTP {}'.format(response.status_code))
# Check that we have read all the data as the requests library does not
# currently enforce this.
expected_length = response.headers.get('Content-Length')
if expected_length is not None:
# We cannot use len(response.content) as this would not work when the body
# of the response was compressed (e.g. when the response has
# `Content-Encoding: gzip`).
actual_length = response.raw.tell()
expected_length = int(expected_length)
if actual_length < expected_length:
raise IOError(
'incomplete read ({} bytes read, {} more expected)'.format(
actual_length,
expected_length - actual_length
)
)
print(response.headers)
print(response.content)
print(len(response.content))
|
Add logging permissions needed by aws-for-fluent-bit | from troposphere import Join, iam, logs
from .common import arn_prefix
from .template import template
container_log_group = logs.LogGroup(
"ContainerLogs",
template=template,
RetentionInDays=365,
DeletionPolicy="Retain",
)
logging_policy = iam.Policy(
PolicyName="LoggingPolicy",
PolicyDocument=dict(
Statement=[dict(
Effect="Allow",
Action=[
"logs:Create*",
"logs:PutLogEvents",
# Needed by aws-for-fluent-bit:
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
],
Resource=Join("", [
arn_prefix,
":logs:*:*:*", # allow logging to any log group
]),
)],
),
)
| from troposphere import Join, iam, logs
from .common import arn_prefix
from .template import template
container_log_group = logs.LogGroup(
"ContainerLogs",
template=template,
RetentionInDays=365,
DeletionPolicy="Retain",
)
logging_policy = iam.Policy(
PolicyName="LoggingPolicy",
PolicyDocument=dict(
Statement=[dict(
Effect="Allow",
Action=[
"logs:Create*",
"logs:PutLogEvents",
],
Resource=Join("", [
arn_prefix,
":logs:*:*:*", # allow logging to any log group
]),
)],
),
)
|
Add resource ID to refresh errors | package terraform
import (
"fmt"
"log"
)
// EvalRefresh is an EvalNode implementation that does a refresh for
// a resource.
type EvalRefresh struct {
Provider *ResourceProvider
State **InstanceState
Info *InstanceInfo
Output **InstanceState
}
// TODO: test
func (n *EvalRefresh) Eval(ctx EvalContext) (interface{}, error) {
provider := *n.Provider
state := *n.State
// If we have no state, we don't do any refreshing
if state == nil {
log.Printf("[DEBUG] refresh: %s: no state, not refreshing", n.Info.Id)
return nil, nil
}
// Call pre-refresh hook
err := ctx.Hook(func(h Hook) (HookAction, error) {
return h.PreRefresh(n.Info, state)
})
if err != nil {
return nil, err
}
// Refresh!
state, err = provider.Refresh(n.Info, state)
if err != nil {
return nil, fmt.Errorf("%s: %s", n.Info.Id, err.Error())
}
// Call post-refresh hook
err = ctx.Hook(func(h Hook) (HookAction, error) {
return h.PostRefresh(n.Info, state)
})
if err != nil {
return nil, err
}
if n.Output != nil {
*n.Output = state
}
return nil, nil
}
| package terraform
import (
"log"
)
// EvalRefresh is an EvalNode implementation that does a refresh for
// a resource.
type EvalRefresh struct {
Provider *ResourceProvider
State **InstanceState
Info *InstanceInfo
Output **InstanceState
}
// TODO: test
func (n *EvalRefresh) Eval(ctx EvalContext) (interface{}, error) {
provider := *n.Provider
state := *n.State
// If we have no state, we don't do any refreshing
if state == nil {
log.Printf("[DEBUG] refresh: %s: no state, not refreshing", n.Info.Id)
return nil, nil
}
// Call pre-refresh hook
err := ctx.Hook(func(h Hook) (HookAction, error) {
return h.PreRefresh(n.Info, state)
})
if err != nil {
return nil, err
}
// Refresh!
state, err = provider.Refresh(n.Info, state)
if err != nil {
return nil, err
}
// Call post-refresh hook
err = ctx.Hook(func(h Hook) (HookAction, error) {
return h.PostRefresh(n.Info, state)
})
if err != nil {
return nil, err
}
if n.Output != nil {
*n.Output = state
}
return nil, nil
}
|
Use objectMode for throttle stream | var Transform = require('readable-stream/transform');
var util = require('util');
function ThrottleStream (options) {
if (!(this instanceof ThrottleStream)) {
return new ThrottleStream(options);
}
options = options || {};
options.objectMode = true;
options.writeableObjectMode = true;
options.readableObjectMode = true;
this.lastTime = 0;
this.interval = (1000 / 5);
this.timeoutId = null;
this.buffer = [];
Transform.call(this, options);
}
util.inherits(ThrottleStream, Transform);
ThrottleStream.prototype.flush = function (callback) {
if (this.buffer.length > 0) {
var chunk = this.buffer.shift();
this.push(chunk);
if (this.buffer.length > 0) {
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
} else {
if (callback) {
return callback();
}
}
}
};
ThrottleStream.prototype._transform = function (chunk, encoding, callback) {
this.buffer.push(chunk);
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
};
ThrottleStream.prototype._flush = function (callback) {
this.flush(callback);
};
module.exports = ThrottleStream;
| var Transform = require('readable-stream/transform');
var util = require('util');
function ThrottleStream (options) {
if (!(this instanceof ThrottleStream)) {
return new ThrottleStream(options);
}
options = options || {};
options.writeableObjectMode = true;
options.readableObjectMode = true;
this.lastTime = 0;
this.interval = (1000 / 5);
this.timeoutId = null;
this.buffer = [];
Transform.call(this, options);
}
util.inherits(ThrottleStream, Transform);
ThrottleStream.prototype.flush = function (callback) {
if (this.buffer.length > 0) {
var chunk = this.buffer.shift();
this.push(chunk);
if (this.buffer.length > 0) {
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
} else {
if (callback) {
return callback();
}
}
}
};
ThrottleStream.prototype._transform = function (chunk, encoding, callback) {
this.buffer.push(chunk);
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
};
ThrottleStream.prototype._flush = function (callback) {
this.flush(callback);
};
module.exports = ThrottleStream;
|
Use models PK for findable actions | <?php namespace Picqer\Financials\Exact\Query;
trait Findable
{
public function find($id)
{
$result = $this->connection()->get($this->url, [
'$filter' => $this->primaryKey . " eq guid'$id'"
]);
return new self($this->connection(), $result);
}
public function filter($filter)
{
$result = $this->connection()->get($this->url, [
'$filter' => $filter
]);
return new self($this->connection(), $result);
}
public function get()
{
$result = $this->connection()->get($this->url);
return $this->collectionFromResult($result);
}
public function collectionFromResult($result)
{
$collection = [];
foreach ($result as $r)
{
$collection[] = new self($this->connection(), $r);
}
return $collection;
}
} | <?php namespace Picqer\Financials\Exact\Query;
trait Findable
{
public function find($id)
{
$result = $this->connection()->get($this->url, [
'$filter' => "ID eq guid'$id'"
]);
return new self($this->connection(), $result);
}
public function filter($filter)
{
$result = $this->connection()->get($this->url, [
'$filter' => $filter
]);
return new self($this->connection(), $result);
}
public function get()
{
$result = $this->connection()->get($this->url);
return $this->collectionFromResult($result);
}
public function collectionFromResult($result)
{
$collection = [];
foreach ($result as $r)
{
$collection[] = new self($this->connection(), $r);
}
return $collection;
}
} |
Fix lint warnings. cc @kadamwhite | 'use strict';
/**
* @ngdoc directive
* @name vlui.directive:bookmarkList
* @description
* # bookmarkList
*/
angular.module('vlui')
.directive('bookmarkList', function (Bookmarks, consts, Logger) {
return {
templateUrl: 'bookmarklist/bookmarklist.html',
restrict: 'E',
replace: true,
scope: {
highlighted: '='
},
link: function postLink(scope /*, element, attrs*/) {
// The bookmark list is designed to render within a modal overlay.
// Because modal contents are hidden via ng-if, if this link function is
// executing it is because the directive is being shown. Log the event:
Logger.logInteraction(Logger.actions.BOOKMARK_OPEN);
scope.logBookmarksClosed = function() {
Logger.logInteraction(Logger.actions.BOOKMARK_CLOSE);
};
scope.Bookmarks = Bookmarks;
scope.consts = consts;
}
};
});
| 'use strict';
/**
* @ngdoc directive
* @name vlui.directive:bookmarkList
* @description
* # bookmarkList
*/
angular.module('vlui')
.directive('bookmarkList', function (Bookmarks, consts, Logger) {
return {
templateUrl: 'bookmarklist/bookmarklist.html',
restrict: 'E',
replace: true,
scope: {
highlighted: '='
},
link: function postLink(scope, element, attrs, modalController) {
// The bookmark list is designed to render within a modal overlay.
// Because modal contents are hidden via ng-if, if this link function is
// executing it is because the directive is being shown. Log the event:
Logger.logInteraction(Logger.actions.BOOKMARK_OPEN);
scope.logBookmarksClosed = function() {
Logger.logInteraction(Logger.actions.BOOKMARK_CLOSE);
};
scope.Bookmarks = Bookmarks;
scope.consts = consts;
}
};
});
|
Update description of throw annotation | 'use strict';
// MODULES //
var factory = require( './factory.js' );
// MAIN //
/**
* Executes functions in series, passing the results of one function as arguments to the next function.
*
* @param {FunctionArray} fcns - array of functions
* @param {Callback} clbk - callback to invoke upon completion
* @param {*} [thisArg] - function context
* @throws {TypeError} first argument must be an array of functions
* @throws {TypeError} second argument must be a function
*
* @example
* function foo( next ) {
* next( null, 'beep' );
* }
*
* function bar( str, next ) {
* console.log( str );
* // => 'beep'
*
* next();
* }
*
* function done( error ) {
* if ( error ) {
* throw error;
* }
* }
*
* var fcns = [ foo, bar ];
*
* waterfall( fcns, done );
*/
function waterfall( fcns, clbk, thisArg ) {
factory( fcns, clbk, thisArg )();
} // end FUNCTION waterfall()
// EXPORTS //
module.exports = waterfall;
| 'use strict';
// MODULES //
var factory = require( './factory.js' );
// MAIN //
/**
* Executes functions in series, passing the results of one function as arguments to the next function.
*
* @param {FunctionArray} fcns - array of functions
* @param {Callback} clbk - callback to invoke upon completion
* @param {*} [thisArg] - function context
* @throws {TypeError} first argument must be an array of functions
* @throws {TypeError} callback argument must be a function
*
* @example
* function foo( next ) {
* next( null, 'beep' );
* }
*
* function bar( str, next ) {
* console.log( str );
* // => 'beep'
*
* next();
* }
*
* function done( error ) {
* if ( error ) {
* throw error;
* }
* }
*
* var fcns = [ foo, bar ];
*
* waterfall( fcns, done );
*/
function waterfall( fcns, clbk, thisArg ) {
factory( fcns, clbk, thisArg )();
} // end FUNCTION waterfall()
// EXPORTS //
module.exports = waterfall;
|
Print progress of combinatorical build | import os
from subprocess import call
from itertools import product, repeat
# To be called from the OpenSpace main folder
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
call(cmd)
call(["make", "clean"])
call(["make", "-j4"])
| import os
from subprocess import call
from itertools import product, repeat
# To be called from the OpenSpace main folder
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
call(cmd)
call(["make", "clean"])
call(["make", "-j4"])
|
Remove should from test descriptions | var expect = require('chai').expect;
var supertest = require('supertest');
var api = supertest("http://localhost:3000");
describe('Checkout index page', function(){
it("responds with 200", function(done){
api.get("/checkouts/new").expect(200, done);
});
it("generates a client token", function(done){
api.get("/checkouts/new").end(function(err, res) {
expect(res.text).to.match(/var token = \"[\w=]+\";/);
done();
});
});
it("includes the checkout form", function(done){
api.get("/checkouts/new").end(function(err, res) {
expect(res.text).to.match(/<form id="checkout"/);
done();
});
});
it("includes the dropin payment-form div", function(done){
api.get("/checkouts/new").end(function(err, res) {
expect(res.text).to.match(/<div id="payment-form"/);
done();
});
});
});
| var expect = require('chai').expect;
var supertest = require('supertest');
var api = supertest("http://localhost:3000");
describe('Checkout index page', function(){
it("should respond with 200", function(done){
api.get("/checkouts/new").expect(200, done);
});
it("should generate a client token", function(done){
api.get("/checkouts/new").end(function(err, res) {
expect(res.text).to.match(/var token = \"[\w=]+\";/);
done();
});
});
it("should include the checkout form", function(done){
api.get("/checkouts/new").end(function(err, res) {
expect(res.text).to.match(/<form id="checkout"/);
done();
});
});
it("should include the dropin payment-form div", function(done){
api.get("/checkouts/new").end(function(err, res) {
expect(res.text).to.match(/<div id="payment-form"/);
done();
});
});
});
|
Fix bug holding onto deleted item, just use name | function App(viewDiv, twitterScreenName)
{
var app = this;
this.view = new View(viewDiv);
this.view.itemRemoveClicked = function(item) { app.onViewItemRemoveClicked(item); };
this.view.itemChangeClicked = function(item) { app.onViewItemChangeClicked(item); };
this.model = new Model();
this.model.itemsLoaded = function() { app.onModelItemsLoaded(); };
this.model.itemRemoved = function(item) { app.onModelItemRemoved(item); };
this.model.load(twitterScreenName);
}
App.prototype.onViewItemRemoveClicked = function(item)
{
this.model.remove(item.name);
};
App.prototype.onViewItemChangeClicked = function(item)
{
var model = this.model;
var input = $('#newTextInput');
var name = item.name;
input.val(name);
$('#newTextSubmit').click(function()
{
model.change(name, input.val());
$('#newTextDialog').dialog('close');
});
$.mobile.changePage('#newTextDialog');
};
App.prototype.onModelItemsLoaded = function()
{
this.view.refresh(this.model.items);
};
App.prototype.onModelItemRemoved = function(item)
{
this.view.remove(item);
};
| function App(viewDiv, twitterScreenName)
{
var app = this;
this.view = new View(viewDiv);
this.view.itemRemoveClicked = function(item) { app.onViewItemRemoveClicked(item); };
this.view.itemChangeClicked = function(item) { app.onViewItemChangeClicked(item); };
this.model = new Model();
this.model.itemsLoaded = function() { app.onModelItemsLoaded(); };
this.model.itemRemoved = function(item) { app.onModelItemRemoved(item); };
this.model.load(twitterScreenName);
}
App.prototype.onViewItemRemoveClicked = function(item)
{
this.model.remove(item.name);
};
App.prototype.onViewItemChangeClicked = function(item)
{
var model = this.model;
var input = $('#newTextInput');
input.val(item.name);
$('#newTextSubmit').click(function()
{
model.change(item.name, input.val());
$('#newTextDialog').dialog('close');
});
$.mobile.changePage('#newTextDialog');
};
App.prototype.onModelItemsLoaded = function()
{
this.view.refresh(this.model.items);
};
App.prototype.onModelItemRemoved = function(item)
{
this.view.remove(item);
};
|
Migrate script now also updates CropTemplate | <?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {
/**
* Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
* This command migrates extended models to the new namespace.
*/
public function migrateGarpModels() {
$modelDir = APPLICATION_PATH . '/modules/default/Model';
$dirIterator = new DirectoryIterator($modelDir);
foreach ($dirIterator as $finfo) {
if ($finfo->isDot()) {
continue;
}
$this->_modifyModelFile($finfo);
}
$this->_updateCropTemplateRefs();
}
// Change references to G_Model_CropTemplate
protected function _updateCropTemplateRefs() {
$iniPaths = ['/configs/content.ini', '/configs/acl.ini'];
foreach ($iniPaths as $i => $path) {
$content = file_get_contents(APPLICATION_PATH . $path);
$content = str_replace('G_Model_CropTemplate', 'Garp_Model_Db_CropTemplate', $content);
file_put_contents(APPLICATION_PATH . $path, $content);
}
}
protected function _modifyModelFile($finfo) {
$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
$contents = file_get_contents($path);
if (strpos($contents, 'extends G_Model_') === false) {
return;
}
$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
return file_put_contents($path, $contents);
}
}
| <?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {
/**
* Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
* This command migrates extended models to the new namespace.
*/
public function migrateGarpModels() {
$modelDir = APPLICATION_PATH . '/modules/default/Model';
$dirIterator = new DirectoryIterator($modelDir);
foreach ($dirIterator as $finfo) {
if ($finfo->isDot()) {
continue;
}
$this->_modifyModelFile($finfo);
}
}
protected function _modifyModelFile($finfo) {
$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
$contents = file_get_contents($path);
if (strpos($contents, 'extends G_Model_') === false) {
return;
}
$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
return file_put_contents($path, $contents);
}
}
|
[SYN5-201] Fix stripe icon in billing section | import React from 'react';
import _ from 'lodash';
import PaymentIcon from '../PaymentIcon';
const PaymentIcons = ({ number, cardNiceType }) => {
const styles = {
paymentIcon: {
width: 40,
height: 'auto',
display: 'block',
marginRight: 10
},
paymentIconHidden: {
opacity: '.1'
}
};
const paymentIcons = [
'Visa',
'MasterCard',
'American Express',
'Discover',
'Diners Club',
'JCB'
];
const renderPaymentIcons = () => _.map(paymentIcons, (icon) => {
let iconStyles = styles.paymentIcon;
if (number && cardNiceType && icon !== cardNiceType) {
iconStyles = { ...styles.paymentIcon, ...styles.paymentIconHidden };
}
return (
<PaymentIcon
niceType={icon}
style={iconStyles}
/>
);
});
return (
<div
className="col-flex-1"
style={{ display: 'flex', alignItems: 'center' }}
>
{renderPaymentIcons()}
<img
src={require('../../assets/img/stripe-badge@3x.png')}
alt="Powered by Stripe"
style={{ display: 'block', height: 78 / 3, marginLeft: 'auto' }}
/>
</div>
);
};
export default PaymentIcons;
| import React from 'react';
import _ from 'lodash';
import PaymentIcon from '../PaymentIcon';
const PaymentIcons = ({ number, cardNiceType }) => {
const styles = {
paymentIcon: {
width: 40,
height: 'auto',
display: 'block',
marginRight: 10
},
paymentIconHidden: {
opacity: '.1'
}
};
const paymentIcons = [
'Visa',
'MasterCard',
'American Express',
'Discover',
'Diners Club',
'JCB'
];
const renderPaymentIcons = () => _.map(paymentIcons, (icon) => {
let iconStyles = styles.paymentIcon;
if (number && cardNiceType && icon !== cardNiceType) {
iconStyles = { ...styles.paymentIcon, ...styles.paymentIconHidden };
}
return (
<PaymentIcon
niceType={icon}
style={iconStyles}
/>
);
});
return (
<div
className="col-flex-1"
style={{ display: 'flex', alignItems: 'center' }}
>
{renderPaymentIcons()}
<img
src={'/img/stripe-badge@3x.png'}
alt="Powered by Stripe"
style={{ display: 'block', height: 78 / 3, marginLeft: 'auto' }}
/>
</div>
);
};
export default PaymentIcons;
|
Add full syntax for SHOW TABLES to help | package com.facebook.presto.cli;
public final class Help
{
private Help() {}
public static String getHelpText()
{
return "" +
"Supported commands:\n" +
"QUIT\n" +
"DESCRIBE <table>\n" +
"SHOW COLUMNS FROM <table>\n" +
"SHOW FUNCTIONS\n" +
"SHOW PARTITIONS FROM <table>\n" +
"SHOW TABLES [LIKE <pattern>]\n" +
"";
}
}
| package com.facebook.presto.cli;
public final class Help
{
private Help() {}
public static String getHelpText()
{
return "" +
"Supported commands:\n" +
"QUIT\n" +
"DESCRIBE <table>\n" +
"SHOW COLUMNS FROM <table>\n" +
"SHOW FUNCTIONS\n" +
"SHOW PARTITIONS FROM <table>\n" +
"SHOW TABLES\n" +
"";
}
}
|
Fix a bug with new version of anyfetch-provider | 'use strict';
var path = require('path');
var retrieveFiles = require('./helpers/retrieve.js').delta;
/**
* Build a uuid for each DB file.
*
* @param {int} uid User ID (available on the tokens)
* @param {path} path File path
*/
var _identifier = function(uid, path) {
return 'https://dropbox.com/' + uid + path;
};
module.exports = function updateAccount(serviceData, cursor, queues, cb) {
// Retrieve all files since last call
delete serviceData.documentsPerUpdate;
retrieveFiles(serviceData, cursor, function(err, entries, newCursor) {
if(err) {
return cb(err);
}
entries.reverse().forEach(function(entry) {
var identifier = _identifier(serviceData.uid, entry[0]);
if(!entry[1]) {
if(cursor) {
queues.deletion.push({identifier: identifier, title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
}
}
else {
queues.addition.push({identifier: identifier, title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
}
});
cb(null, newCursor);
});
};
| 'use strict';
var path = require('path');
var retrieveFiles = require('./helpers/retrieve.js').delta;
/**
* Build a uuid for each DB file.
*
* @param {int} uid User ID (available on the tokens)
* @param {path} path File path
*/
var _identifier = function(uid, path) {
return 'https://dropbox.com/' + uid + path;
};
module.exports = function updateAccount(serviceData, cursor, queues, cb) {
// Retrieve all files since last call
retrieveFiles(serviceData, cursor, function(err, entries, newCursor) {
if(err) {
return cb(err);
}
entries.reverse().forEach(function(entry) {
var identifier = _identifier(serviceData.uid, entry[0]);
if(!entry[1]) {
if(cursor) {
queues.deletion.push({identifier: identifier, title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
}
}
else {
queues.addition.push({identifier: identifier, title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
}
});
cb(null, newCursor);
});
};
|
Remove Python 2.6 compat from format | # -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
| # -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
|
Update production build for react-0.14 | var config = module.exports = require("./webpack.config.js");
var webpack = require('webpack');
var _ = require('lodash');
config = _.merge(config, {
externals : {
"react" : "React",
"react-dom" : "ReactDOM"
}
});
var StringReplacePlugin = require("string-replace-webpack-plugin");
config.module.loaders.push({
test: /index.html$/,
loader: StringReplacePlugin.replace({
replacements: [
{
pattern: /<!-- externals to be replaced by webpack StringReplacePlugin -->/ig,
replacement: function (match, p1, offset, string) {
return '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-with-addons.js"></script><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js"></script>';
}
}
]})
}
);
var definePlugin = new webpack.DefinePlugin({
__PRODUCTION__ : true
});
config.plugins.push(
new StringReplacePlugin(),
definePlugin
)
| var config = module.exports = require("./webpack.config.js");
var webpack = require('webpack');
var _ = require('lodash');
config = _.merge(config, {
externals : {
"react" : "React"
}
});
var StringReplacePlugin = require("string-replace-webpack-plugin");
config.module.loaders.push({
test: /index.html$/,
loader: StringReplacePlugin.replace({
replacements: [
{
pattern: /<!-- externals to be replaced by webpack StringReplacePlugin -->/ig,
replacement: function (match, p1, offset, string) {
return '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react-with-addons.js"></script>';
}
}
]})
}
);
var definePlugin = new webpack.DefinePlugin({
__PRODUCTION__ : true
});
config.plugins.push(
new StringReplacePlugin(),
definePlugin
) |
Add number in string format
For python 2.6 compatibility | import unittest
from robber import expect
from robber.matchers.contain import Contain
class TestAbove(unittest.TestCase):
def test_matches(self):
expect(Contain({'key': 'value'}, 'key').matches()) == True
expect(Contain([1, 2, 3], 2).matches()) == True
expect(Contain((1, 2, 3), 3).matches()) == True
expect(Contain({'key': 'value'}, 'other').matches()) == False
expect(Contain([1, 2, 3], 4).matches()) == False
expect(Contain((1, 2, 3), 4).matches()) == False
def test_failure_message(self):
contain = Contain([1, 2, 3], 4)
expect(contain.failure_message()) == 'Expected {0} to contain 4'.format([1, 2, 3])
def test_register(self):
expect(expect.matcher('contain')) == Contain
| import unittest
from robber import expect
from robber.matchers.contain import Contain
class TestAbove(unittest.TestCase):
def test_matches(self):
expect(Contain({'key': 'value'}, 'key').matches()) == True
expect(Contain([1, 2, 3], 2).matches()) == True
expect(Contain((1, 2, 3), 3).matches()) == True
expect(Contain({'key': 'value'}, 'other').matches()) == False
expect(Contain([1, 2, 3], 4).matches()) == False
expect(Contain((1, 2, 3), 4).matches()) == False
def test_failure_message(self):
contain = Contain([1, 2, 3], 4)
expect(contain.failure_message()) == 'Expected {} to contain 4'.format([1, 2, 3])
def test_register(self):
expect(expect.matcher('contain')) == Contain
|
Fix bug, a callable defined as 'class::method' is not possible | <?php
/**
* Slim Framework (http://slimframework.com)
*
* @link https://github.com/codeguy/Slim
* @copyright Copyright (c) 2011-2015 Josh Lockhart
* @license https://github.com/codeguy/Slim/blob/master/LICENSE (MIT License)
*/
namespace Slim\Handlers\Strategies;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\InvocationStrategyInterface;
/**
* Default route callback strategy with route parameters as an array of arguments.
*/
class RequestResponse implements InvocationStrategyInterface
{
/**
* Invoke a route callable with request, response, and all route parameters
* as an array of arguments.
*
* @param array|callable $callable
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param array $routeArguments
*
* @return mixed
*/
public function __invoke(
callable $callable,
ServerRequestInterface $request,
ResponseInterface $response,
array $routeArguments
) {
foreach ($routeArguments as $k => $v) {
$request = $request->withAttribute($k, $v);
}
return call_user_func($callable, $request, $response, $routeArguments);
}
}
| <?php
/**
* Slim Framework (http://slimframework.com)
*
* @link https://github.com/codeguy/Slim
* @copyright Copyright (c) 2011-2015 Josh Lockhart
* @license https://github.com/codeguy/Slim/blob/master/LICENSE (MIT License)
*/
namespace Slim\Handlers\Strategies;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\InvocationStrategyInterface;
/**
* Default route callback strategy with route parameters as an array of arguments.
*/
class RequestResponse implements InvocationStrategyInterface
{
/**
* Invoke a route callable with request, response, and all route parameters
* as an array of arguments.
*
* @param array|callable $callable
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param array $routeArguments
*
* @return mixed
*/
public function __invoke(
callable $callable,
ServerRequestInterface $request,
ResponseInterface $response,
array $routeArguments
) {
foreach ($routeArguments as $k => $v) {
$request = $request->withAttribute($k, $v);
}
return $callable($request, $response, $routeArguments);
}
}
|
Allow EntityStateChanged for a procman in tests. | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.system.server.given.entity;
import io.spine.server.entity.EventFilter;
import io.spine.server.procman.ProcessManagerRepository;
import io.spine.system.server.PersonCreation;
import io.spine.system.server.PersonId;
/**
* A repository of {@link PersonProcman}.
*
* @author Dmytro Dashenkov
*/
public class PersonProcmanRepository
extends ProcessManagerRepository<PersonId, PersonProcman, PersonCreation> {
// Allow all events for the test purposes.
@Override
protected EventFilter eventFilter() {
return EventFilter.allowAll();
}
}
| /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.system.server.given.entity;
import io.spine.server.procman.ProcessManagerRepository;
import io.spine.system.server.PersonCreation;
import io.spine.system.server.PersonId;
/**
* A repository of {@link PersonProcman}.
*
* @author Dmytro Dashenkov
*/
public class PersonProcmanRepository
extends ProcessManagerRepository<PersonId, PersonProcman, PersonCreation> {
}
|
[WEB-559] Fix issue with button focus styles | export default ({ colors, borders }) => ({
primary: {
backgroundColor: colors.purpleMedium,
border: borders.input,
borderColor: colors.purpleMedium,
color: colors.white,
'&:hover,&:active': {
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
secondary: {
bg: colors.white,
color: colors.text.primary,
border: borders.input,
'&:hover,&:active': {
color: colors.white,
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
});
| export default ({ colors, borders }) => ({
primary: {
backgroundColor: colors.purpleMedium,
border: borders.input,
borderColor: colors.purpleMedium,
color: colors.white,
'&:hover,&:active,&:focus': {
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
secondary: {
bg: colors.white,
color: colors.text.primary,
border: borders.input,
'&:hover,&:active,&:focus': {
color: colors.white,
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
});
|
Fix to return json response to invalid tokens. Fix to exception throws not being catch correctly. | <?php
namespace Cvogit\LumenJWT\Http\Middleware;
use Closure;
use \InvalidArgumentException;
use \RuntimeException;
use Illuminate\Http\Request;
use Cvogit\LumenJWT\JWT;
use Cvogit\LumenJWT\Parser;
class JwtGuard
{
/**
* The parsed jwt
*
* @var \Cvogit\LumenJWT\JWT $jwt
*/
protected $jwt;
/**
* The parser
*
* @var \Cvogit\LumenJWT\Parser $parser
*/
protected $parser;
/**
* Create a new middleware instance.
*
* @param
* @return void
*/
public function __construct(JWT $jwt, Parser $parser)
{
$this->jwt = $jwt;
$this->parser = $parser;
}
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
try {
$token = $this->parser->parse($request);
} catch (RuntimeException $e) {
return response()->json(['message' => $e->getMessage()], 404);
}
try {
$payload = $this->jwt->decode($token);
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()], 404);
}
return $next($request);
}
} | <?php
namespace Cvogit\LumenJWT\Http\Middleware;
use Closure;
use \InvalidArgumentException;
use \RuntimeException;
use Illuminate\Http\Request;
use Cvogit\LumenJWT\JWT;
use Cvogit\LumenJWT\Parser;
class JwtGuard
{
/**
* The parsed jwt
*
*/
protected $jwt;
/**
* The parser
*
*/
protected $parser;
/**
* Create a new middleware instance.
*
* @param
* @return void
*/
public function __construct(JWT $jwt, Parser $parser)
{
$this->jwt = $jwt;
$this->parser = $parser;
}
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
try {
$token = $this->parser->parse($request);
} catch (RuntimeException $e) {
abort(404, $e->getMessage());
}
try {
$payload = $this->jwt->decode($token);
} catch(InvalidArgumentException $e){
abort(404, $e->getMessage());
}
if($payload["exp"] >= $payload["iat"])
return $next($request);
abort(404, "Token expired, please log in again.");
}
} |
Fix Schema table name variable | package com.test.smartnotes.database;
/**
* Created by saff on 08.06.17.
*/
public class NotesDbSchema {
public static final class NotesTable {
public static final String NAME = "NOTES";
public static final class Cols {
public static final String ID ="_id";
public static final String NOTE_TITLE ="NOTE_TITLE";
public static final String NOTE_TEXT ="NOTE_TEXT";
public static final String IMPORTANCE ="IMPORTANCE";
public static final String IMAGE_PATH ="IMAGE_PATH";
public static final String LONGITUDE ="LONGITUDE";
public static final String LATITUDE ="LATITUDE";
}
}
}
| package com.test.smartnotes.database;
/**
* Created by saff on 08.06.17.
*/
public class NotesDbSchema {
public static final class NotesTable {
public static final String DATABASE_NAME = "NOTES";
public static final class Cols {
public static final String ID ="_id";
public static final String NOTE_TITLE ="NOTE_TITLE";
public static final String NOTE_TEXT ="NOTE_TEXT";
public static final String IMPORTANCE ="IMPORTANCE";
public static final String IMAGE_PATH ="IMAGE_PATH";
public static final String LONGITUDE ="LONGITUDE";
public static final String LATITUDE ="LATITUDE";
}
}
}
|
Fix the debug logging flag | package log
import (
"fmt"
"io"
"os"
"time"
)
type Logger struct {
PrintDebug bool
Output io.Writer
DateFormat string
}
func NewLogger(opts ...func(*Logger)) *Logger {
l := &Logger{
PrintDebug: false,
Output: os.Stdout,
DateFormat: "15:04",
}
for _, opt := range opts {
opt(l)
}
return l
}
func (l *Logger) log(lvl, msg string, args ...interface{}) {
fmt.Fprintf(l.Output, "%s %s %s\n", time.Now().Format(l.DateFormat), lvl, fmt.Sprintf(msg, args...))
}
func (l *Logger) Debug(msg string, args ...interface{}) {
if l.PrintDebug {
l.log("debug", msg, args...)
}
}
func (l *Logger) Info(msg string, args ...interface{}) {
l.log("info ", msg, args...)
}
| package log
import (
"fmt"
"io"
"os"
"time"
)
type Logger struct {
PrintDebug bool
Output io.Writer
DateFormat string
}
func NewLogger(opts ...func(*Logger)) *Logger {
l := &Logger{
PrintDebug: false,
Output: os.Stdout,
DateFormat: "15:04",
}
for _, opt := range opts {
opt(l)
}
return l
}
func (l *Logger) log(lvl, msg string, args ...interface{}) {
fmt.Fprintf(l.Output, "%s %s %s\n", time.Now().Format(l.DateFormat), lvl, fmt.Sprintf(msg, args...))
}
func (l *Logger) Debug(msg string, args ...interface{}) {
l.log("debug", msg, args...)
}
func (l *Logger) Info(msg string, args ...interface{}) {
l.log("info ", msg, args...)
}
|
feat(expo): Allow apiKey to be set in app.json rather than in code | const name = 'Bugsnag Expo'
const { version } = require('../package.json')
const url = 'https://github.com/bugsnag/bugsnag-js'
const { Constants } = require('expo')
const Client = require('@bugsnag/core/client')
const schema = { ...require('@bugsnag/core/config').schema, ...require('./config') }
const plugins = [
require('@bugsnag/plugin-react-native-global-error-handler'),
require('@bugsnag/plugin-react-native-unhandled-rejection')
]
module.exports = (opts) => {
// handle very simple use case where user supplies just the api key as a string
if (typeof opts === 'string') opts = { apiKey: opts }
// ensure opts is actually an object (at this point it
// could be null, undefined, a number, a boolean etc.)
opts = { ...opts }
// attempt to fetch apiKey from app.json if we didn't get one explicitly passed
if (!opts.apiKey &&
Constants.manifest.extra &&
Constants.manifest.extra.bugsnag &&
Constants.manifest.extra.bugsnag.apiKey) {
opts.apiKey = Constants.manifest.extra.bugsnag.apiKey
}
const bugsnag = new Client({ name, version, url })
bugsnag.setOptions(opts)
bugsnag.configure(schema)
plugins.forEach(pl => bugsnag.use(pl))
bugsnag._logger.debug(`Loaded!`)
return bugsnag
}
module.exports['default'] = module.exports
| const name = 'Bugsnag Expo'
const { version } = require('../package.json')
const url = 'https://github.com/bugsnag/bugsnag-js'
const Client = require('@bugsnag/core/client')
const schema = { ...require('@bugsnag/core/config').schema, ...require('./config') }
const plugins = [
require('@bugsnag/plugin-react-native-global-error-handler'),
require('@bugsnag/plugin-react-native-unhandled-rejection')
]
module.exports = (opts) => {
// handle very simple use case where user supplies just the api key as a string
if (typeof opts === 'string') opts = { apiKey: opts }
const bugsnag = new Client({ name, version, url })
bugsnag.setOptions(opts)
bugsnag.configure(schema)
plugins.forEach(pl => bugsnag.use(pl))
bugsnag._logger.debug(`Loaded!`)
return bugsnag
}
module.exports['default'] = module.exports
|
Add improved logging and instance iteration | 'use strict';
var co = require('co');
var util = require('util');
/**
* StaticPublisher yields a set of static endpoints as produced by the passed factory.
* @param {Array.<string>} instances Typically host:port strings which can be converted into endpoints.
* @param {function*} factory Converts instance strings into endpoints.
* @param {Object} logger
* @return {Object} A Publisher.
*/
function* staticPublisher(instances, factory, logger) {
var endpoints = [];
for (let i = 0; i < instances.length; i++) {
let instance = instances[i];
try {
let e = yield* factory(instance);
endpoints.push(e);
} catch (err) {
logger.log('ERROR', 'factory', instance, 'err', err);
}
}
if (endpoints.length === 0) {
throw new Error('no endpoints');
}
logger.log('DEBUG', util.format('staticPublisher is providing %d endpoint(s) based on %d instance(s)', endpoints.length, instances.length), instances);
while (true) {
yield endpoints;
}
}
module.exports.staticPublisher = staticPublisher;
| 'use strict';
var co = require('co');
var util = require('util');
/**
* StaticPublisher yields a set of static endpoints as produced by the passed factory.
* @param {Array.<string>} instances Typically host:port strings which can be converted into endpoints.
* @param {function*} factory Converts instance strings into endpoints.
* @param {Object} logger
* @return {Object} A Publisher.
*/
function* staticPublisher(instances, factory, logger) {
var endpoints = [];
for (let instance of instances) {
try {
let e = yield* factory(instance);
endpoints.push(e);
} catch (err) {
logger.log('instance', instance, 'err', err);
}
}
if (endpoints.length === 0) {
throw new Error('no endpoints');
}
while (true) {
yield endpoints;
}
}
module.exports.staticPublisher = staticPublisher;
|
Remove the unnecessary use of lodash
Former-commit-id: ce3aefbef958e30a55232235c2721743b347a505 | export const instruct = (array, instArray) => {
const tempObject = {};
for (let i = 0, max = instArray.length; i < max; i++) {
const guide = instArray[i];
tempObject[guide] = array[i];
}
return tempObject;
};
export const transformData = (object, instructions) => {
for (const key in instructions) {
if (object[key] instanceof Array)
object[key] = instruct(object[key], instructions[key]);
else if (object[key] instanceof Object && !(instructions[key] instanceof Array))
object[key] = transformData(object[key], instructions[key]);
}
return object;
};
export const toArray = (object, instruction) => {
const tempArray = [];
for (let i = 0, max = instruction.length; i < max; i++) {
const guide = instruction[i];
tempArray[i] = object[guide];
}
return tempArray;
};
| import isArray from 'lodash-es/isArray';
import isObject from 'lodash-es/isObject';
export const instruct = (array, instArray) => {
const tempObject = {};
for (let i = 0, max = instArray.length; i < max; i++) {
const guide = instArray[i];
tempObject[guide] = array[i];
}
return tempObject;
};
export const transformData = (object, instructions) => {
for (const key in instructions) {
if (isArray(object[key]))
object[key] = instruct(object[key], instructions[key]);
else if (isObject(object[key]) && !isArray(instructions[key]))
object[key] = transformData(object[key], instructions[key]);
}
return object;
};
export const toArray = (object, instruction) => {
const tempArray = [];
for (let i = 0, max = instruction.length; i < max; i++) {
const guide = instruction[i];
tempArray[i] = object[guide];
}
return tempArray;
};
|
Convert load_model tests to pytest functions | # flake8: noqa F401,F811
"""Diagram could not be loaded due to JuggleError (presumed cyclic resolving of
diagram items)."""
from gi.repository import GLib, Gtk
from gaphor.diagram.tests.fixtures import (
element_factory,
event_manager,
modeling_language,
)
from gaphor.storage.storage import load
def test_cyclic_diagram_bug(element_factory, modeling_language, test_models):
"""Load file.
This does not nearly resemble the error, since the model should be
loaded from within the mainloop (which will delay all updates).
"""
path = test_models / "dbus.gaphor"
load(path, element_factory, modeling_language)
def test_cyclic_diagram_bug_idle(element_factory, modeling_language, test_models):
"""Load file in gtk main loop.
This does not nearly resemble the error, since the model should be
loaded from within the mainloop (which will delay all updates).
"""
def handler():
try:
path = test_models / "dbus.gaphor"
load(path, element_factory, modeling_language)
finally:
Gtk.main_quit()
assert GLib.timeout_add(1, handler) > 0
Gtk.main()
| """Test GitHub issue #4.
Diagram could not be loaded due to JuggleError (presumed cyclic
resolving of diagram items).
"""
from gi.repository import GLib, Gtk
from gaphor.storage.storage import load
class TestCyclicDiagram:
def test_bug(self, case, test_models):
"""Load file.
This does not nearly resemble the error, since the model should
be loaded from within the mainloop (which will delay all
updates).
"""
path = test_models / "dbus.gaphor"
load(path, case.element_factory, case.modeling_language)
def test_bug_idle(self, case, test_models):
"""Load file in gtk main loop.
This does not nearly resemble the error, since the model should
be loaded from within the mainloop (which will delay all
updates).
"""
def handler():
try:
path = test_models / "dbus.gaphor"
load(path, case.element_factory, case.modeling_language)
finally:
Gtk.main_quit()
assert GLib.timeout_add(1, handler) > 0
Gtk.main()
|
Disable template test for now
fbshipit-source-id: d2da361 | /**
* @flow
*/
jasmine.DEFAULT_TIMEOUT_INTERVAL = 240000;
import path from 'path';
import uuid from 'uuid';
import rimraf from 'rimraf';
import {
clearXDLCacheAsync,
downloadTemplateApp,
extractTemplateApp,
} from '../Exp';
describe('Template Apps', () => {
it('should download the starter app template and extract it', async () => {
// This was working locally but failing on the mac ci machine
/*
process.env.UNSAFE_EXPO_HOME_DIRECTORY = path.join(
'/',
'tmp',
`.expo-${uuid.v1()}`
);
await clearXDLCacheAsync();
let dir = path.join('/', 'tmp', `.expo-${uuid.v1()}`);
let templateDownload = await downloadTemplateApp('tabs', dir, {
name: `test-template-${new Date().valueOf()}`,
progressFunction: () => {},
retryFunction: () => {},
});
expect(templateDownload).not.toBeNull();
// Extract the template we just downloaded
let projectRoot = await extractTemplateApp(
templateDownload.starterAppPath,
templateDownload.name,
templateDownload.root
);
rimraf.sync(process.env.UNSAFE_EXPO_HOME_DIRECTORY);
rimraf.sync(dir);
*/
});
});
| /**
* @flow
*/
jasmine.DEFAULT_TIMEOUT_INTERVAL = 240000;
import path from 'path';
import uuid from 'uuid';
import rimraf from 'rimraf';
import {
clearXDLCacheAsync,
downloadTemplateApp,
extractTemplateApp,
} from '../Exp';
describe('Template Apps', () => {
it('should download the starter app template and extract it', async () => {
process.env.UNSAFE_EXPO_HOME_DIRECTORY = path.join(
'/',
'tmp',
`.expo-${uuid.v1()}`
);
await clearXDLCacheAsync();
let dir = path.join('/', 'tmp', `.expo-${uuid.v1()}`);
let templateDownload = await downloadTemplateApp('tabs', dir, {
name: `test-template-${new Date().valueOf()}`,
progressFunction: () => {},
retryFunction: () => {},
});
expect(templateDownload).not.toBeNull();
// Extract the template we just downloaded
let projectRoot = await extractTemplateApp(
templateDownload.starterAppPath,
templateDownload.name,
templateDownload.root
);
rimraf.sync(process.env.UNSAFE_EXPO_HOME_DIRECTORY);
rimraf.sync(dir);
});
});
|
Use a better fitting nonce action for the Redirect site setting. | <?php # -*- coding: utf-8 -*-
/**
* Handles the site-specific Redirect setting.
*/
class Mlp_Redirect_Site_Settings {
/**
* @var string
*/
private $option_name;
/**
* Constructor.
*
* @param string $option_name
*/
public function __construct( $option_name ) {
$this->option_name = $option_name;
}
/**
* Create instances, and register callbacks.
*
* @return void
*/
public function setup() {
$nonce = new Inpsyde_Nonce_Validator( 'save_redirect_site_setting' );
$data = new Mlp_Redirect_Settings_Data( $nonce, $this->option_name );
$view = new Mlp_Redirect_Site_Settings_Form( $nonce, $data );
add_filter( 'mlp_blogs_add_fields', array( $view, 'render' ) );
add_filter( 'mlp_blogs_save_fields', array( $data, 'save' ) );
}
}
| <?php
/**
* Site specific settings.
*
* @version 2014.04.28
* @author Inpsyde GmbH, toscho
* @license GPL
* @package MultilingualPress
* @subpackage Redirect
*/
class Mlp_Redirect_Site_Settings {
/**
* @var string
*/
private $option_name;
/**
* Constructor.
*
* @param string $option_name
*/
public function __construct( $option_name ) {
$this->option_name = $option_name;
}
/**
* Create instances, and register callbacks.
*
* @return void
*/
public function setup() {
$nonce = new Inpsyde_Nonce_Validator( 'mlp_redirect' );
$data = new Mlp_Redirect_Settings_Data( $nonce, $this->option_name );
$view = new Mlp_Redirect_Site_Settings_Form( $nonce, $data );
add_filter( 'mlp_blogs_add_fields', array ( $view, 'render' ) );
add_filter( 'mlp_blogs_save_fields', array ( $data, 'save' ) );
}
} |
Move pages from registration to accounts/ | from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template
import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('registration.urls')),
(r'^$', direct_to_template,
{ 'template': 'index.html' }, 'index'),
)
if settings.STATIC_SERVE:
urlpatterns += patterns('',
url(
regex = r'^media/(?P<path>.*)$',
view = 'django.views.static.serve',
kwargs = {'document_root': settings.MEDIA_ROOT}),
)
| from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template
import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^registration/', include('registration.urls')),
(r'^$', direct_to_template,
{ 'template': 'index.html' }, 'index'),
)
if settings.STATIC_SERVE:
urlpatterns += patterns('',
url(
regex = r'^media/(?P<path>.*)$',
view = 'django.views.static.serve',
kwargs = {'document_root': settings.MEDIA_ROOT}),
)
|
Remove out-of-date comment about snapshot UX | from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.set_defaults(func=self.run)
subparser.add_argument('-n', '--name', action='store', default='',
help='Specify custom name for an ENVy.')
return subparser
def run(self, config, args):
envy = Envy(config)
envy.snapshot('%s-snapshot' % envy.name)
| from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.set_defaults(func=self.run)
subparser.add_argument('-n', '--name', action='store', default='',
help='Specify custom name for an ENVy.')
return subparser
#TODO(jakedahn): The entire UX for this needs to be talked about, refer to
# https://github.com/bcwaldon/cloudenvy/issues/27 for any
# discussion, if you're curious.
def run(self, config, args):
envy = Envy(config)
envy.snapshot('%s-snapshot' % envy.name)
|
Add help tabs to test page type and load properties box again | <?php
class Test_Page_Type extends Papi_Page_Type {
/**
* Define our Page Type meta data.
*
* @return array
*/
public function meta() {
return [
'fill_labels' => true,
'name' => 'Test page',
'template' => 'pages/test-page.php'
];
}
/**
* Add help tabs.
*
* @return array
*/
public function help() {
return [
'Page type' => 'Class cursus vehicula dolor. Tellus inceptos semper pede reprehenderit habitant.',
'More details' => 'Convallis morbi fames vivamus cum. Ac metus vivamus sollicitudin.'
];
}
/**
* Remove meta boxes.
*
* @return array
*/
public function remove() {
return ['editor', 'commentsdiv', 'commentstatusdiv', 'authordiv', 'slugdiv'];
}
/**
* Register properties.
*/
public function register() {
$this->box( 'boxes/properties.php' );
}
}
| <?php
class Test_Page_Type extends Papi_Page_Type {
/**
* Define our Page Type meta data.
*
* @return array
*/
public function meta() {
return [
'fill_labels' => true,
'name' => 'Test page',
'template' => 'pages/test-page.php',
'show_screen_options'=>false
];
}
/**
* Add help tabs.
*
* @return array
*/
public function help() {
return [
'hej' => 'du'
];
}
/**
* Remove meta boxes.
*
* @return array
*/
public function remove() {
return ['editor', 'commentsdiv', 'commentstatusdiv', 'authordiv', 'slugdiv'];
}
/**
* Register properties.
*/
public function register() {
$this->box( 'Content', [
papi_property( [
'type' => 'string',
'title' => 'Name'
] )
] );
}
}
|
Use relative path for log readability | import fs from 'fs'
/**
* @class
*/
export default class Action {
/**
* @param {String} name
*/
constructor({ name }) {
this.name = name;
}
/**
* @return {String}
*/
getDirectoryPath() {
return `./actions/${this.name}`;
}
/**
* @return {Function}
*/
getHandler() {
const handlerScriptPath = `${this.getDirectoryPath()}/index.js`;
delete(require.cache[handlerScriptPath]);
return require(handlerScriptPath).handler;
}
/**
* @return {String}
*/
getHttpMethod() {
return this.getPackage().fluct.httpMethod;
}
/**
* @return {Object}
*/
getPackage() {
if (!this.package) {
this.package = JSON.parse(
fs.readFileSync(`${this.getDirectoryPath()}/package.json`)
);
}
return this.package;
}
/**
* @return {String}
*/
getPath() {
return this.getPackage().fluct.path;
}
/**
* @param {http.IncomingMessage} request
* @param {http.ServerResponse} response
*/
run(request, response) {
this.getHandler()(
{},
{
done: (value) => {
response.send(value);
}
}
);
}
}
| import fs from 'fs'
/**
* @class
*/
export default class Action {
/**
* @param {String} name
*/
constructor({ name }) {
this.name = name;
}
/**
* @return {String}
*/
getDirectoryPath() {
return `${process.cwd()}/actions/${this.name}`;
}
/**
* @return {Function}
*/
getHandler() {
const handlerScriptPath = `${this.getDirectoryPath()}/index.js`;
delete(require.cache[handlerScriptPath]);
return require(handlerScriptPath).handler;
}
/**
* @return {String}
*/
getHttpMethod() {
return this.getPackage().fluct.httpMethod;
}
/**
* @return {Object}
*/
getPackage() {
if (!this.package) {
this.package = JSON.parse(
fs.readFileSync(`${this.getDirectoryPath()}/package.json`)
);
}
return this.package;
}
/**
* @return {String}
*/
getPath() {
return this.getPackage().fluct.path;
}
/**
* @param {http.IncomingMessage} request
* @param {http.ServerResponse} response
*/
run(request, response) {
this.getHandler()(
{},
{
done: (value) => {
response.send(value);
}
}
);
}
}
|
BHV-12598: Call the super and set the content property directly.
Enyo-DCO-1.1-Signed-off-by: Aaron Tam <aaron.tam@lge.com> | (function (enyo, scope) {
/**
* {@link moon.Divider} is a simply styled component that may be used as a separator
* between groups of components.
*
* @class moon.Divider
* @mixes moon.MarqueeSupport
* @mixes moon.MarqueeItem
* @ui
* @public
*/
enyo.kind(
/** @lends moon.Divider.prototype */ {
/**
* @private
*/
name: 'moon.Divider',
/**
* @private
*/
classes: 'moon-divider moon-divider-text',
/**
* @private
*/
mixins: ['moon.MarqueeSupport', 'moon.MarqueeItem'],
/**
* @private
*/
marqueeOnSpotlight: false,
/**
* @private
*/
marqueeOnRender: true,
/**
* @private
*/
contentChanged: function () {
this.inherited(arguments);
this.content = this.content.split(' ').map(enyo.cap).join(' ');
}
});
})(enyo, this);
| (function (enyo, scope) {
/**
* {@link moon.Divider} is a simply styled component that may be used as a separator
* between groups of components.
*
* @class moon.Divider
* @mixes moon.MarqueeSupport
* @mixes moon.MarqueeItem
* @ui
* @public
*/
enyo.kind(
/** @lends moon.Divider.prototype */ {
/**
* @private
*/
name: 'moon.Divider',
/**
* @private
*/
classes: 'moon-divider moon-divider-text',
/**
* @private
*/
mixins: ['moon.MarqueeSupport', 'moon.MarqueeItem'],
/**
* @private
*/
marqueeOnSpotlight: false,
/**
* @private
*/
marqueeOnRender: true,
/**
* @private
*/
contentChanged: function () {
this.set('content', this.content.split(' ').map(enyo.cap).join(' '));
}
});
})(enyo, this);
|
Revert "fix import loop in local installation; update mne dependency version" | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Setup configuration."""
from setuptools import setup, find_packages
import ephypype
VERSION = ephypype.__version__
if __name__ == "__main__":
setup(
name='ephypype',
version=VERSION,
packages=find_packages(),
author=['David Meunier',
'Annalisa Pascarella',
'Dmitrii Altukhov'],
description='Definition of functions used\
as Node for electrophy (EEG/MEG)\
pipelines within nipype framework',
lisence='BSD 3',
install_requires=['mne>=0.14',
'nipype',
'configparser',
'h5py']
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Setup configuration."""
from setuptools import setup, find_packages
if __name__ == "__main__":
setup(
name='ephypype',
# version=VERSION,
version='0.1.dev0',
packages=find_packages(),
author=['David Meunier',
'Annalisa Pascarella',
'Dmitrii Altukhov'],
description='Definition of functions used\
as Node for electrophy (EEG/MEG)\
pipelines within nipype framework',
lisence='BSD 3',
install_requires=['mne>=0.16',
'nipype',
'configparser',
'h5py']
)
|
Fix create database issue on Postgresql | <?php
use yii\db\Migration;
class m160516_095943_init extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql' || $this->db->driverName === 'mariadb') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%Cart}}', [
'sessionId' => $this->string(),
'cartData' => $this->text(),
], $tableOptions);
$this->addPrimaryKey('cart_pk', '{{%Cart}}', 'sessionId');
}
public function down()
{
$this->dropTable('{{%Cart}}');
}
}
| <?php
use yii\db\Migration;
class m160516_095943_init extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql' || $this->db->driverName === 'mariadb') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%Cart}}', [
'sessionId' => $this->string(),
'cartData' => $this->text(),
'PRIMARY KEY (`sessionId`)',
], $tableOptions);
}
public function down()
{
$this->dropTable('{{%Cart}}');
}
}
|
Use bare image name dependent on base image name | # -*- coding: utf-8 -*-
#
# 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.
"""
Provides bare images for standalone clusters.
"""
import re
from tests.bare_image_provider import TagBareImageProvider
from tests.product.constants import BASE_IMAGES_TAG
from tests.product.constants import BASE_IMAGE_NAME
class NoHadoopBareImageProvider(TagBareImageProvider):
def __init__(self):
# encode base image name into name of created test image, to prevent image name clash.
decoration = 'nohadoop_' + re.sub(r"[^A-Za-z0-9]", "_", BASE_IMAGE_NAME)
super(NoHadoopBareImageProvider, self).__init__(
BASE_IMAGE_NAME, BASE_IMAGE_NAME,
BASE_IMAGES_TAG, decoration)
| # -*- coding: utf-8 -*-
#
# 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.
"""
Provides bare images for standalone clusters.
"""
from tests.bare_image_provider import TagBareImageProvider
from tests.product.constants import BASE_IMAGES_TAG
from tests.product.constants import BASE_IMAGE_NAME
class NoHadoopBareImageProvider(TagBareImageProvider):
def __init__(self):
super(NoHadoopBareImageProvider, self).__init__(
BASE_IMAGE_NAME, BASE_IMAGE_NAME,
BASE_IMAGES_TAG, 'nohadoop')
|
Add import parser for url and evidence | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Handlers for special object mappings."""
from flask import current_app
from ggrc import models
from ggrc.login import get_current_user_id
from ggrc.converters import errors
from ggrc.converters import get_importables
from ggrc.converters.handlers import handlers
class RequestLinkHandler(handlers.ColumnHandler):
def parse_item(self):
documents = []
for line in self.raw_value.splitlines():
link, title = line.split(None, 1) if " " in line else (line, line)
documents.append(models.Document(
link=link,
title=title,
modified_by_id=get_current_user_id(),
context=self.row_converter.obj.context,
))
return documents
def set_obj_attr(self):
self.value = self.parse_item()
class RequestEvidenceHandler(RequestLinkHandler):
def get_value(self):
pass
def insert_object(self):
pass
def set_value(self):
"""This should be ignored with second class attributes."""
class RequestUrlHandler(RequestLinkHandler):
def get_value(self):
pass
def insert_object(self):
pass
def set_value(self):
"""This should be ignored with second class attributes."""
| # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Handlers for special object mappings."""
from flask import current_app
from ggrc import models
from ggrc.login import get_current_user_id
from ggrc.converters import errors
from ggrc.converters import get_importables
from ggrc.converters.handlers import handlers
class RequestLinkHandler(handlers.ColumnHandler):
def parse_item(self):
pass
def set_obj_attr(self):
pass
class RequestEvidenceHandler(RequestLinkHandler):
def get_value(self):
pass
def insert_object(self):
pass
def set_value(self):
"""This should be ignored with second class attributes."""
class RequestUrlHandler(RequestLinkHandler):
def get_value(self):
pass
def insert_object(self):
pass
def set_value(self):
"""This should be ignored with second class attributes."""
|
Order `most_read` queryset by slug. | import logging
from datetime import timedelta
from django.db import models
from django.utils import timezone
from .google_analytics import get_most_read_pages
logger = logging.getLogger(__name__)
class InterviewManager(models.Manager):
def active(self, *args, **kwargs):
return super(InterviewManager, self).filter(draft=False).filter(publish__lte=timezone.now())
def newest(self, *args, **kwargs):
return self.active().first()
def last_week(self, *args, **kwargs):
some_day_last_week = timezone.now().date() - timedelta(days=7)
monday_of_last_week = some_day_last_week - timedelta(days=(some_day_last_week.isocalendar()[2] - 1))
monday_of_this_week = monday_of_last_week + timedelta(days=7)
return super(InterviewManager, self).filter(draft=False).filter(publish__gte=monday_of_last_week,
publish__lt=monday_of_this_week)[:1]
def most_read(self, *args, **kwargs):
slugs = get_most_read_pages()
if slugs:
return self.active().filter(slug__in=slugs).order_by('slug')
return super(InterviewManager, self).none()
| import logging
from datetime import timedelta
from django.db import models
from django.utils import timezone
from .google_analytics import get_most_read_pages
logger = logging.getLogger(__name__)
class InterviewManager(models.Manager):
def active(self, *args, **kwargs):
return super(InterviewManager, self).filter(draft=False).filter(publish__lte=timezone.now())
def newest(self, *args, **kwargs):
return self.active().first()
def last_week(self, *args, **kwargs):
some_day_last_week = timezone.now().date() - timedelta(days=7)
monday_of_last_week = some_day_last_week - timedelta(days=(some_day_last_week.isocalendar()[2] - 1))
monday_of_this_week = monday_of_last_week + timedelta(days=7)
return super(InterviewManager, self).filter(draft=False).filter(publish__gte=monday_of_last_week,
publish__lt=monday_of_this_week)[:1]
def most_read(self, *args, **kwargs):
slugs = get_most_read_pages()
if slugs:
return self.active().filter(slug__in=slugs)
return super(InterviewManager, self).none()
|
Break the build to test Hudson
git-svn-id: ec6ef1d57ec0831ce4cbff3b75527511e63bfbe3@736933 13f79535-47bb-0310-9956-ffa450edef68 | /*
* 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.jsecurity.util;
BREAK BUILD
/**
* Interface implemented by components that can be named, such as via configuration, and wish to have that name
* set once it has been configured.
*
* @author Les Hazlewood
* @since 0.9
*/
public interface Nameable {
/**
* Sets the (preferably application unique) name for this component.
* @param name the preferably application unique name for this component.
*/
void setName(String name);
}
| /*
* 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.jsecurity.util;
/**
* Interface implemented by components that can be named, such as via configuration, and wish to have that name
* set once it has been configured.
*
* @author Les Hazlewood
* @since 0.9
*/
public interface Nameable {
/**
* Sets the (preferably application unique) name for this component.
* @param name the preferably application unique name for this component.
*/
void setName(String name);
}
|
Revert table ordering tweaks to alert list
This causes weird behaviour in GMail because of how it hides duplicated
content. The header toggles between under/over the alert list on every
other email. | <?php namespace FOO; ?>
<div style="<?= $panel_style ?>; display: table; width: 100%">
<div style="display:table-header-group;">
<h2 style="<?= $panel_content_style ?>">
<a style="<?= $link_style ?>" href="<?= $base_url ?>/search/<?= $search['id'] ?>"><?= Util::escape($search['name']) ?></a>
<small style="<?= $sub_style ?>">[<?= count($alerts) ?> Alert<?= count($alerts) != 1 ? 's':'' ?>]</small>
</h2>
<p style="<?= $panel_content_style ?>">
<?= nl2br(Util::escape($search['description'])) ?>
<?php if($search->isTimeBased()): ?>
<br>
<br>
<b>Time range: </b><?= $search['range'] ?> minute(s)
<?php endif ?>
</p>
</div>
<div style="<?= $table_container_style ?>">
<?php if($vertical): ?>
<?php require(__DIR__ . '/alert_list.php'); ?>
<?php else: ?>
<?php require(__DIR__ . '/alert_table.php'); ?>
<?php endif ?>
</div>
</div>
| <?php namespace FOO; ?>
<div style="<?= $panel_style ?>; display: table; width: 100%">
<div style="<?= $table_container_style ?>">
<?php if($vertical): ?>
<?php require(__DIR__ . '/alert_list.php'); ?>
<?php else: ?>
<?php require(__DIR__ . '/alert_table.php'); ?>
<?php endif ?>
</div>
<div style="display:table-header-group;">
<h2 style="<?= $panel_content_style ?>">
<a style="<?= $link_style ?>" href="<?= $base_url ?>/search/<?= $search['id'] ?>"><?= Util::escape($search['name']) ?></a>
<small style="<?= $sub_style ?>">[<?= count($alerts) ?> Alert<?= count($alerts) != 1 ? 's':'' ?>]</small>
</h2>
<p style="<?= $panel_content_style ?>">
<?= nl2br(Util::escape($search['description'])) ?>
<?php if($search->isTimeBased()): ?>
<br>
<br>
<b>Time range: </b><?= $search['range'] ?> minute(s)
<?php endif ?>
</p>
</div>
</div>
|
Remove extra semi-colon in line 13 | package seedu.ezdo.model.todo;
import com.joestelmach.natty.Parser;
/**
* Represents the date associated with tasks.
*/
public abstract class TaskDate {
public final String value;
public static final String TASKDATE_VALIDATION_REGEX =
"^$|([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)";
public TaskDate(String taskDate) {
Parser parser = new Parser();
this.value = parser.parse(taskDate).get(0).getDates().get(0).toString();
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskDate // instanceof handles nulls
&& this.value.equals(((TaskDate) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
/**
* Returns true if a given string is a valid task date.
*/
public static boolean isValidTaskDate(String test) {
return test.matches(TASKDATE_VALIDATION_REGEX);
}
}
| package seedu.ezdo.model.todo;
import com.joestelmach.natty.Parser;
/**
* Represents the date associated with tasks.
*/
public abstract class TaskDate {
public final String value;
public static final String TASKDATE_VALIDATION_REGEX =
"^$|([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)";;
public TaskDate(String taskDate) {
Parser parser = new Parser();
this.value = parser.parse(taskDate).get(0).getDates().get(0).toString();
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskDate // instanceof handles nulls
&& this.value.equals(((TaskDate) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
/**
* Returns true if a given string is a valid task date.
*/
public static boolean isValidTaskDate(String test) {
return test.matches(TASKDATE_VALIDATION_REGEX);
}
}
|
Fix `goimports` fail, no idea how it compiles on local machine. | package python
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sourcegraph.com/sourcegraph/srclib/toolchain"
)
func runCmdLogError(cmd *exec.Cmd) {
err := runCmdStderr(cmd)
if err != nil {
log.Printf("Error running `%s`: %s", strings.Join(cmd.Args, " "), err)
}
}
func runCmdStderr(cmd *exec.Cmd) error {
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stderr
return cmd.Run()
}
func getVENVBinPath() (string, error) {
if os.Getenv("IN_DOCKER_CONTAINER") == "" {
tc, err := toolchain.Lookup("sourcegraph.com/sourcegraph/srclib-python")
if err != nil {
return "", err
}
return filepath.Join(tc.Dir, ".env", "bin"), nil
}
return "", nil
}
| package python
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sourcegraph.com/sourcegraph/toolchain"
)
func runCmdLogError(cmd *exec.Cmd) {
err := runCmdStderr(cmd)
if err != nil {
log.Printf("Error running `%s`: %s", strings.Join(cmd.Args, " "), err)
}
}
func runCmdStderr(cmd *exec.Cmd) error {
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stderr
return cmd.Run()
}
func getVENVBinPath() (string, error) {
if os.Getenv("IN_DOCKER_CONTAINER") == "" {
tc, err := toolchain.Lookup("sourcegraph.com/sourcegraph/srclib-python")
if err != nil {
return "", err
}
return filepath.Join(tc.Dir, ".env", "bin"), nil
}
return "", nil
}
|
Fix scenarios where WP_Error::get_error_code() return string | <?php
class Aplazame_Aplazame_Http_WpClient implements Aplazame_Sdk_Http_ClientInterface {
public function send( Aplazame_Sdk_Http_RequestInterface $request ) {
$rawHeaders = array();
foreach ( $request->getHeaders() as $header => $value ) {
$rawHeaders[ $header ] = implode( ', ', $value );
}
$args = array(
'headers' => $rawHeaders,
'method' => $request->getMethod(),
'body' => $request->getBody(),
);
$wpResponse = wp_remote_request( $request->getUri(), $args );
if ( is_wp_error( $wpResponse ) ) {
throw new RuntimeException( $wpResponse->get_error_message(), (int) $wpResponse->get_error_code() );
}
$responseBody = wp_remote_retrieve_body( $wpResponse );
$response = new Aplazame_Sdk_Http_Response(
wp_remote_retrieve_response_code( $wpResponse ),
$responseBody
);
return $response;
}
}
| <?php
class Aplazame_Aplazame_Http_WpClient implements Aplazame_Sdk_Http_ClientInterface {
public function send( Aplazame_Sdk_Http_RequestInterface $request ) {
$rawHeaders = array();
foreach ( $request->getHeaders() as $header => $value ) {
$rawHeaders[ $header ] = implode( ', ', $value );
}
$args = array(
'headers' => $rawHeaders,
'method' => $request->getMethod(),
'body' => $request->getBody(),
);
$wpResponse = wp_remote_request( $request->getUri(), $args );
if ( is_wp_error( $wpResponse ) ) {
throw new RuntimeException( $wpResponse->get_error_message(), $wpResponse->get_error_code() );
}
$responseBody = wp_remote_retrieve_body( $wpResponse );
$response = new Aplazame_Sdk_Http_Response(
wp_remote_retrieve_response_code( $wpResponse ),
$responseBody
);
return $response;
}
}
|
FIX: Remove accidentally introduced '23' at the start of the file | <?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {
static $has_one = array(
'MainImage' => 'Image'
);
// for rendering thumbnail when linked in facebook
function getOGImage() {
return $this->MainImage();
}
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'));
$dirname = strtolower($this->ClassName).'s';
$uf->setFolderName($dirname);
return $fields;
}
public function getPortletTitle() {
return $this->Title;
}
// FIXME - make this more efficient
public function getPortletImage() {
$result = null;
if ($this->MainImageId) {
$result = DataObject::get_by_id('Image', $this->MainImageID);
}
return $result;
}
public function getPortletCaption() {
return '';
}
}
class PageWithImage_Controller extends Page_Controller {
} | <?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {
static $has_one = array(
'MainImage' => 'Image'
);
// for rendering thumbnail when linked in facebook
function getOGImage() {
return $this->MainImage();
}
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'));
$dirname = strtolower($this->ClassName).'s';
$uf->setFolderName($dirname);
return $fields;
}
public function getPortletTitle() {
return $this->Title;
}
// FIXME - make this more efficient
public function getPortletImage() {
$result = '';
if ($this->MainImageID) {
$result = DataObject::get_by_id('Image', $this->MainImageID);
}
return $result;
}
public function getPortletCaption() {
return '';
}
}
class PageWithImage_Controller extends Page_Controller {
} |
[test-studio] Configure up non-existing widget in test-studio | export default {
widgets: [
{name: 'sanity-tutorials', layout: {width: 'full'}},
{name: 'document-list'},
{name: 'document-list', options: {title: 'Last edited', order: '_updatedAt desc'}},
{name: 'document-list', options: {title: 'Last created books', types: ['book']}},
{name: 'project-users'},
{name: 'widget-which-does-not-exist'},
{
name: 'project-info',
layout: {
width: 'medium',
height: 'auto'
},
options: {
data: [
{title: 'Frontend', value: 'https://asdf.heroku.com/greedy-goblin', category: 'apps'},
{title: 'Strange endpoint', value: 'https://example.com/v1/strange', category: 'apis'},
{title: 'With strawberry jam?', value: 'Yes', category: 'Waffles'},
{title: 'Gummy bears?', value: 'nope', category: 'Cheweies'},
{title: 'With rømme?', value: 'maybe', category: 'Waffles'}
]
}
},
{name: 'cats'}
]
}
| export default {
widgets: [
{name: 'sanity-tutorials', layout: {width: 'full'}},
{name: 'document-list'},
{name: 'document-list', options: {title: 'Last edited', order: '_updatedAt desc'}},
{name: 'document-list', options: {title: 'Last created books', types: ['book']}},
{name: 'project-users'},
{
name: 'project-info',
layout: {
width: 'medium',
height: 'auto'
},
options: {
data: [
{title: 'Frontend', value: 'https://asdf.heroku.com/greedy-goblin', category: 'apps'},
{title: 'Strange endpoint', value: 'https://example.com/v1/strange', category: 'apis'},
{title: 'With strawberry jam?', value: 'Yes', category: 'Waffles'},
{title: 'Gummy bears?', value: 'nope', category: 'Cheweies'},
{title: 'With rømme?', value: 'maybe', category: 'Waffles'}
]
}
},
{name: 'cats'}
]
}
|
Create different instances of the cluster for producers and consumers | const { createLogger, LEVELS: { INFO } } = require('./loggers')
const logFunctionConsole = require('./loggers/console')
const Cluster = require('./cluster')
const createProducer = require('./producer')
const createConsumer = require('./consumer')
module.exports = class Client {
constructor({
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
logLevel = INFO,
logFunction = logFunctionConsole,
}) {
this.logger = createLogger({ level: logLevel, logFunction })
this.createCluster = () =>
new Cluster({
logger: this.logger,
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
})
}
/**
* @public
*/
producer({ createPartitioner, retry } = {}) {
return createProducer({
cluster: this.createCluster(),
logger: this.logger,
createPartitioner,
retry,
})
}
/**
* @public
*/
consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) {
return createConsumer({
cluster: this.createCluster(),
logger: this.logger,
groupId,
createPartitionAssigner,
sessionTimeout,
retry,
})
}
}
| const { createLogger, LEVELS: { INFO } } = require('./loggers')
const logFunctionConsole = require('./loggers/console')
const Cluster = require('./cluster')
const createProducer = require('./producer')
const createConsumer = require('./consumer')
module.exports = class Client {
constructor({
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
logLevel = INFO,
logFunction = logFunctionConsole,
}) {
this.logger = createLogger({ level: logLevel, logFunction })
this.cluster = new Cluster({
logger: this.logger,
brokers,
ssl,
sasl,
clientId,
connectionTimeout,
retry,
})
}
producer({ createPartitioner, retry } = {}) {
return createProducer({
cluster: this.cluster,
logger: this.logger,
createPartitioner,
retry,
})
}
consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) {
return createConsumer({
cluster: this.cluster,
logger: this.logger,
groupId,
createPartitionAssigner,
sessionTimeout,
retry,
})
}
}
|
Modify datasource example to actually show driver name | package org.wildfly.swarm.examples.ds.war;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* @author Bob McWhirter
*/
@Path("/")
public class MyResource {
@GET
@Produces("text/plain")
public String get() throws NamingException, SQLException {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jboss/datasources/ExampleDS");
Connection conn = ds.getConnection();
try {
return "Howdy using driver: " + conn.getMetaData().getDriverName();
} finally {
conn.close();
}
}
}
| package org.wildfly.swarm.examples.ds.war;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* @author Bob McWhirter
*/
@Path("/")
public class MyResource {
@GET
@Produces("text/plain")
public String get() throws NamingException, SQLException {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jboss/datasources/ExampleDS");
Connection conn = ds.getConnection();
try {
return "Howdy using connection: " + conn;
} finally {
conn.close();
}
}
}
|
Change selector to outside onclik event | const basketItemViews = {
remove: function remove(el) {
el.addEventListener("click", function() {
el.parentNode.remove();
});
},
addToBasket: function addToBasket(el, props) {
const container = document.querySelector(`.${props.target}`);
el.addEventListener("click", function() {
fetch(props.file)
.then(res => res.text())
.then(data => {
const wrapper = document.createElement("div");
wrapper.innerHTML = data;
container.appendChild(wrapper);
viewloader.execute(basketItemViews, wrapper, true);
})
.catch(err => console.log(err));
});
}
};
viewloader.execute(basketItemViews);
| const basketItemViews = {
remove: function remove(el) {
el.addEventListener("click", function() {
el.parentNode.remove();
});
},
addToBasket: function addToBasket(el, props) {
el.addEventListener("click", function() {
fetch(props.file)
.then(res => res.text())
.then(data => {
const wrapper = document.createElement("div");
wrapper.innerHTML = data;
const container = document.querySelector(`.${props.target}`);
container.appendChild(wrapper);
viewloader.execute(views, wrapper, true);
})
.catch(err => console.log(err));
});
}
};
viewloader.execute(basketItemViews);
|
Fix lint error and refactor return of magicNumbers | class DCFUtility {
static magicNumbers(magicNumber) {
const magicNumbers = {
int0: 0,
int1: 1,
int16: 16,
hex0x3: 0x3,
hex0x8: 0x8,
escCode: 27
};
Object.freeze(magicNumbers);
return magicNumber in magicNumbers ? magicNumbers[magicNumber] : undefined;
}
static uuidv4() {
const NUMERIC_0 = DCFUtility.magicNumbers('int0');
const NUMERIC_16 = DCFUtility.magicNumbers('int16');
const HEX0x3 = DCFUtility.magicNumbers('hex0x3');
const HEX0x8 = DCFUtility.magicNumbers('hex0x8');
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (uuid) => {
let rand = Math.random() * NUMERIC_16 | NUMERIC_0,
uuidv4 = uuid === 'x' ? rand : rand & HEX0x3 | HEX0x8;
return uuidv4.toString(NUMERIC_16);
});
}
}
| class DCFUtility {
static magicNumbers(magicNumber) {
const magicNumbers = {
int0: 0,
int1: 1,
int16: 16,
hex0x3: 0x3,
hex0x8: 0x8,
escCode: 27
};
Object.freeze(magicNumbers);
if (magicNumber in magicNumbers) {
return magicNumbers[magicNumber];
}
return undefined;
}
static uuidv4() {
const NUMERIC_0 = DCFUtility.magicNumbers('int0');
const NUMERIC_16 = DCFUtility.magicNumbers('int16');
const HEX0x3 = DCFUtility.magicNumbers('hex0x3');
const HEX0x8 = DCFUtility.magicNumbers('hex0x8');
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (uuid) => {
let rand = Math.random() * NUMERIC_16 | NUMERIC_0,
uuidv4 = uuid === 'x' ? rand : rand & HEX0x3 | HEX0x8;
return uuidv4.toString(NUMERIC_16);
});
}
}
|
Sort the child nodes in the labelling visitor, to make sure that they are sorted | package signature;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class CanonicalLabellingVisitor implements DAGVisitor {
private int[] labelling;
private int currentLabel;
private Comparator<DAG.Node> comparator;
public CanonicalLabellingVisitor(
int vertexCount, Comparator<DAG.Node> comparator) {
labelling = new int[vertexCount];
Arrays.fill(labelling, -1);
currentLabel = 0;
}
public void visit(DAG.Node node) {
// only label if this vertex has not yet been labeled
if (this.labelling[node.vertexIndex] == -1) {
this.labelling[node.vertexIndex] = this.currentLabel;
this.currentLabel++;
}
Collections.sort(node.children, comparator);
for (DAG.Node child : node.children) {
child.accept(this);
}
}
public int[] getLabelling() {
return this.labelling;
}
}
| package signature;
import java.util.Arrays;
public class CanonicalLabellingVisitor implements DAGVisitor {
private int[] labelling;
private int currentLabel;
public CanonicalLabellingVisitor(int vertexCount) {
this.labelling = new int[vertexCount];
Arrays.fill(this.labelling, -1);
this.currentLabel = 0;
}
public void visit(DAG.Node node) {
// only label if this vertex has not yet been labeled
if (this.labelling[node.vertexIndex] == -1) {
this.labelling[node.vertexIndex] = this.currentLabel;
this.currentLabel++;
}
for (DAG.Node child : node.children) {
child.accept(this);
}
}
public int[] getLabelling() {
return this.labelling;
}
}
|
Use integer parameter to set the fields unsigned | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateFavoritesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('favorites', function (Blueprint $table) {
$table->integer('video_id', false, true);
$table->foreign('video_id')->references('id')->on('videos');
$table->integer('user_id', false, true);
$table->foreign('user_id')->references('id')->on('users');
$table->timestamp('registered_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('favorites');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateFavoritesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('favorites', function ($table) {
$table->integer('video_id')->unsigned();
$table->foreign('video_id')->references('id')->on('videos');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamp('registered_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('favorites');
}
}
|
EF: Fix typo in expirtyTime property name. | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
foam.CLASS({
package: 'com.chrome.origintrials.model',
name: 'Token',
properties: [
{
class: 'String',
name: 'origin'
},
{
class: 'String',
name: 'feature'
},
{
class: 'String',
name: 'emailAddress'
},
{
class: 'String',
name: 'name'
},
{
class: 'String',
name: 'rowNumber'
},
{
class: 'String',
name: 'token'
},
{
class: 'DateTime',
name: 'expiryTime'
},
{
class: 'String',
name: 'id',
},
{
class: 'Boolean',
name: 'isSubdomain'
}
]
});
| /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
foam.CLASS({
package: 'com.chrome.origintrials.model',
name: 'Token',
properties: [
{
class: 'String',
name: 'origin'
},
{
class: 'String',
name: 'feature'
},
{
class: 'String',
name: 'emailAddress'
},
{
class: 'String',
name: 'name'
},
{
class: 'String',
name: 'rowNumber'
},
{
class: 'String',
name: 'token'
},
{
class: 'DateTime',
name: 'expryTime'
},
{
class: 'String',
name: 'id',
},
{
class: 'Boolean',
name: 'isSubdomain'
}
]
});
|
Disable an externals tests on Py3. | from django.test import TestCase
from django.utils import six
from ..externals import External
from types import FunctionType
import unittest
class TestExternals(TestCase):
def test_load(self):
external = External('foo')
with self.assertRaises(ImportError):
external._load('')
def test_load_class(self):
external = External('foo')
self.assertIsInstance(external.load_class(''), object)
self.assertTrue(external.load_class('', fallback=True))
def test_load_method(self):
external = External('foo')
self.assertIsNone(external.load_method('')())
self.assertTrue(external.load_method('', fallback=True))
@unittest.skipIf(six.PY3, "Covered by Python 2.")
def test_context_manager(self):
from contextlib import GeneratorContextManager
external = External('foo')
self.assertIs(type(external.context_manager('')), FunctionType)
self.assertIsInstance(external.context_manager('')(), GeneratorContextManager)
self.assertTrue(external.context_manager('', fallback=True))
with external.context_manager('')():
self.assertTrue(True)
| from django.test import TestCase
from ..externals import External
try:
from contextlib import GeneratorContextManager
except ImportError:
from contextlib import _GeneratorContextManager as GeneratorContextManager
from types import FunctionType
class TestExternals(TestCase):
def test_load(self):
external = External('foo')
with self.assertRaises(ImportError):
external._load('')
def test_load_class(self):
external = External('foo')
self.assertIsInstance(external.load_class(''), object)
self.assertTrue(external.load_class('', fallback=True))
def test_load_method(self):
external = External('foo')
self.assertIsNone(external.load_method('')())
self.assertTrue(external.load_method('', fallback=True))
def test_context_manager(self):
external = External('foo')
self.assertIs(type(external.context_manager('')), FunctionType)
self.assertIsInstance(external.context_manager('')(), GeneratorContextManager)
self.assertTrue(external.context_manager('', fallback=True))
with external.context_manager('')():
self.assertTrue(True)
|
Update copyright year of changed file
See gh-27804 | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework.adapter;
import java.io.Serializable;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.ThrowsAdvice;
/**
* Adapter to enable {@link org.springframework.aop.ThrowsAdvice}
* to be used in the Spring AOP framework.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
@SuppressWarnings("serial")
class ThrowsAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof ThrowsAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
return new ThrowsAdviceInterceptor(advisor.getAdvice());
}
}
| /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework.adapter;
import java.io.Serializable;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.ThrowsAdvice;
/**
* Adapter to enable {@link org.springframework.aop.ThrowsAdvice}
* to be used in the Spring AOP framework.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
@SuppressWarnings("serial")
class ThrowsAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof ThrowsAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
return new ThrowsAdviceInterceptor(advisor.getAdvice());
}
}
|
Return proper filename for static file | <?php
/**
* StaticFile.php
*
* Created By: jonathan
* Date: 26/09/2017
* Time: 15:04
*/
namespace Stati\Entity;
use Symfony\Component\Finder\SplFileInfo;
class StaticFile extends SplFileInfo
{
public function get($item)
{
if ($item === 'path') {
return $this->getRelativePathname();
}
if ($item === 'modified_time') {
return $this->getMTime();
}
if ($item === 'name') {
return $this->getFilename();
}
if ($item === 'basename') {
return pathinfo($this->getRelativePathname(), PATHINFO_BASENAME);
}
if ($item === 'extname') {
return '.'.pathinfo($this->getRelativePathname(), PATHINFO_EXTENSION);
}
return null;
}
public function field_exists($item)
{
return in_array($item, ['path', 'modified_time', 'name', 'basename', 'extname']);
}
public function __get($item)
{
return $this->get($item);
}
}
| <?php
/**
* StaticFile.php
*
* Created By: jonathan
* Date: 26/09/2017
* Time: 15:04
*/
namespace Stati\Entity;
use Symfony\Component\Finder\SplFileInfo;
class StaticFile extends SplFileInfo
{
public function get($item)
{
if ($item === 'path') {
return $this->getRelativePathname();
}
if ($item === 'modified_time') {
return $this->getMTime();
}
if ($item === 'name') {
return $this->getBasename();
}
if ($item === 'basename') {
return pathinfo($this->getRelativePathname(), PATHINFO_BASENAME);
}
if ($item === 'extname') {
return '.'.pathinfo($this->getRelativePathname(), PATHINFO_EXTENSION);
}
return null;
}
public function __get($item)
{
return $this->get($item);
}
}
|
Fix oversight with placeholder value of variable | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
/**
* Handles requests through the browser ie at the live site
*/
class WebController extends Controller
{
public function viewLinks($teamSlug)
{
$teamName="HngX";
$teamId="Txjrd24";
$query="";
$results=[];
//parse $teamId and $teamName from $teamSlug
if (isset($_GET["query"])) {
$query=$_GET["query"];
//$results=search($teamId, $query);
return view('listing', ["teamName" => $teamName, "query" => $query, "results" => $results]);
} else {
//$results=getAllLinks($teamId);
return view('listing', ["teamName" => $teamName, "results" => $results]);
}
}
/** Retrieves all a team's links
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function getAllLinks($team)
{
}
/** Searches for a team's links matching a given search query
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function search($team, $queryString)
{
//parse query string
//perform search
}
}
| <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
/**
* Handles requests through the browser ie at the live site
*/
class WebController extends Controller
{
public function viewLinks($teamSlug)
{
$teamName="HngX";
$teamId="Txjrd24";
$query="";
//parse $teamId and $teamName from $teamSlug
if (isset($_GET["query"])) {
$query=$_GET["query"];
//$results=search($teamId, $query);
return view('listing', ["teamName" => $teamName, "query" => $query, "results" => $results]);
} else {
//$results=getAllLinks($teamId);
return view('listing', ["teamName" => $teamName, "results" => $results]);
}
}
/** Retrieves all a team's links
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function getAllLinks($team)
{
}
/** Searches for a team's links matching a given search query
*
* @param $team The id of the team
* @param $queryString The query string
*/
public function search($team, $queryString)
{
//parse query string
//perform search
}
}
|
Add NYT module and refacotr weather | var express = require('express'),
routes = require('./routes'),
path = require('path'),
weather = require('./routes/weather'),
npr = require('./routes/npr'),
nyt = require('./routes/nyt');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('port', process.env.PORT || 5000);
app.set('views', __dirname + '/app');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, '/app')));
app.get('/', routes.index);
app.listen(process.env.PORT || 5000);
// JSON API
app.get('/weather', weather.today);
app.get('/npr/top', npr.top);
app.get('/npr/health', npr.health);
app.get('/npr/econ', npr.econ);
app.get('/nyt/home', nyt.home);
app.get('/nyt/health', nyt.health);
| var express = require('express'),
routes = require('./routes'),
path = require('path'),
weather = require('./routes/weather'),
npr = require('./routes/npr'),
nyt = require('./routes/nyt'),
reddit = require('./routes/reddit');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('port', process.env.PORT || 5000);
app.set('views', __dirname + '/app');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, '/app')));
app.get('/', routes.index);
app.listen(process.env.PORT || 5000);
// JSON API
app.get('/weather', weather.today);
app.get('/npr/top', npr.top);
app.get('/npr/health', npr.health);
app.get('/npr/econ', npr.econ);
app.get('/nyt/home', nyt.home);
app.get('/nyt/health', nyt.health);
app.get('/reddit', reddit.relationships);
|
Replace execfile with something compatible with both Py2/3. | import os
import subprocess
import virtualenv
def execute_file(path):
global_vars = {"__file__": path}
with open(path, 'rb') as pyfile:
exec(compile(pyfile.read(), path, 'exec'), global_vars)
class VirtualEnvManager(object):
def __init__(self, path):
self.venv_home = path
def install(self, requirements_file=None):
if os.path.exists(self.venv_home):
return True
virtualenv.create_environment(self.venv_home)
if requirements_file:
args = [os.path.join(self.venv_home, 'bin/python'), '-m', 'pip',
'install', '-r', requirements_file]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
return False
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
execute_file(script)
def deactivate(self):
pass
| import os
import subprocess
import virtualenv
class VirtualEnvManager(object):
def __init__(self, path):
self.venv_home = path
def install(self, requirements_file=None):
if os.path.exists(self.venv_home):
return True
virtualenv.create_environment(self.venv_home)
if requirements_file:
args = [os.path.join(self.venv_home, 'bin/python'), '-m', 'pip',
'install', '-r', requirements_file]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
return False
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
execfile(script, dict(__file__=script))
def deactivate(self):
pass
|
Initialize reallocated unsafe direct memory to 0. | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.catalyst.buffer.util;
/**
* Direct memory allocator.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class DirectMemoryAllocator implements MemoryAllocator<NativeMemory> {
@Override
public DirectMemory allocate(long size) {
DirectMemory memory = new DirectMemory(DirectMemory.UNSAFE.allocateMemory(size), size, this);
DirectMemory.UNSAFE.setMemory(memory.address(), size, (byte) 0);
return memory;
}
@Override
public DirectMemory reallocate(NativeMemory memory, long size) {
DirectMemory newMemory = new DirectMemory(DirectMemory.UNSAFE.reallocateMemory(memory.address(), size), size, this);
if (newMemory.size() > memory.size()) {
DirectMemory.UNSAFE.setMemory(newMemory.address(), newMemory.size() - memory.size(), (byte) 0);
}
return newMemory;
}
}
| /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.catalyst.buffer.util;
/**
* Direct memory allocator.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class DirectMemoryAllocator implements MemoryAllocator<NativeMemory> {
@Override
public DirectMemory allocate(long size) {
DirectMemory memory = new DirectMemory(DirectMemory.UNSAFE.allocateMemory(size), size, this);
DirectMemory.UNSAFE.setMemory(memory.address(), size, (byte) 0);
return memory;
}
@Override
public DirectMemory reallocate(NativeMemory memory, long size) {
return new DirectMemory(DirectMemory.UNSAFE.reallocateMemory(memory.address(), size), size, this);
}
}
|
Fix evaluation date & test period | # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_periods():
tax_benefit_system = FranceTaxBenefitSystem()
scenario = tax_benefit_system.new_scenario()
scenario.init_single_entity(period='2017-11',
parent1=dict(salaire_de_base=2300,
effectif_entreprise=1,
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
contrat_de_travail_fin='2017-12-01',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new_simulation()
assert_equal(simulation.calculate('coefficient_proratisation','2017-11'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-12'),0)
assert_equal(simulation.calculate('coefficient_proratisation','2017-10'),0)
assert_equal(simulation.calculate_add('coefficient_proratisation','2017'),1)
| # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_periods():
tax_benefit_system = FranceTaxBenefitSystem()
scenario = tax_benefit_system.new_scenario()
scenario.init_single_entity(period='2017-11',
parent1=dict(salaire_de_base=2300,
effectif_entreprise=1,
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
contrat_de_travail_fin='2017-11-30',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new_simulation()
assert_equal(simulation.calculate('coefficient_proratisation','2017-11'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-12'),0)
assert_equal(simulation.calculate('coefficient_proratisation','2017-10'),0)
assert_equal(simulation.calculate_add('coefficient_proratisation','2017'),1)
|
Prepare for release of 8.3dev-602. | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.23 2007/12/02 08:30:15 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public final static int buildNumber = 602;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
| /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.22 2007/07/31 06:05:43 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public final static int buildNumber = 601;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
|
Fix containsProperty and getPropertyNames on MapPropertySources | package com.ulisesbocchio.jasyptspringboot.wrapper;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertySource;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.util.Assert;
import java.util.Map;
/**
* @author Ulises Bocchio
*/
public class EncryptableMapPropertySourceWrapper extends MapPropertySource implements EncryptablePropertySource<Map<String, Object>> {
EncryptablePropertyResolver resolver;
private MapPropertySource delegate;
public EncryptableMapPropertySourceWrapper(MapPropertySource delegate, EncryptablePropertyResolver resolver) {
super(delegate.getName(), delegate.getSource());
Assert.notNull(delegate, "PropertySource delegate cannot be null");
Assert.notNull(resolver, "EncryptablePropertyResolver cannot be null");
this.resolver = resolver;
this.delegate = delegate;
}
@Override
public Object getProperty(String name) {
return getProperty(resolver, delegate, name);
}
@Override
public PropertySource<Map<String, Object>> getDelegate() {
return delegate;
}
@Override
public boolean containsProperty(String name) {
return delegate.containsProperty(name);
}
@Override
public String[] getPropertyNames() {
return delegate.getPropertyNames();
}
}
| package com.ulisesbocchio.jasyptspringboot.wrapper;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertySource;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.util.Assert;
import java.util.Map;
/**
* @author Ulises Bocchio
*/
public class EncryptableMapPropertySourceWrapper extends MapPropertySource implements EncryptablePropertySource<Map<String, Object>> {
EncryptablePropertyResolver resolver;
private MapPropertySource delegate;
public EncryptableMapPropertySourceWrapper(MapPropertySource delegate, EncryptablePropertyResolver resolver) {
super(delegate.getName(), delegate.getSource());
Assert.notNull(delegate, "PropertySource delegate cannot be null");
Assert.notNull(resolver, "EncryptablePropertyResolver cannot be null");
this.resolver = resolver;
this.delegate = delegate;
}
@Override
public Object getProperty(String name) {
return getProperty(resolver, delegate, name);
}
@Override
public PropertySource<Map<String, Object>> getDelegate() {
return delegate;
}
}
|
Make feedback form use smtphost too | <?php
/**
* Log the feedback information
* The token can be traced to a student ID for feedback follow-up
* The user agent can be used to debug front-end/visual bugs
*/
// We can send the user back to the page they were on once completed
$ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/';
if (isset($_POST['feedbacktxt']) && isset($_POST['token'])) {
ini_set('SMTP', 'smtphost.aber.ac.uk');
ini_set('sendmail_from', Config::MAIL_FROM_ADDR);
$feedbacktxt = $_POST['feedbacktxt'];
$token = $_POST['token'];
$ua = $_SERVER['HTTP_USER_AGENT'];
$time = time();
$msg = "Feedback:\r\n".$feedbacktxt."\r\n\r\nToken: ".$token."\r\nUser Agent: ".$ua."\r\nTimestamp: ".$time;
mail('ben@bbrks.me', '[AWESOME FEEDBACK]', $msg);
echo 'Thank you for your feedback. Redirecting in 3 seconds.';
} else {
echo '<strong>Error:</strong> No feedback was sent! Redirecting in 3 seconds.';
}
echo '<meta http-equiv="refresh" content="3; url='.$ref.'" />';
| <?php
/**
* Log the feedback information
* The token can be traced to a student ID for feedback follow-up
* The user agent can be used to debug front-end/visual bugs
*/
// We can send the user back to the page they were on once completed
$ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/';
if (isset($_POST['feedbacktxt']) && isset($_POST['token'])) {
$feedbacktxt = $_POST['feedbacktxt'];
$token = $_POST['token'];
$ua = $_SERVER['HTTP_USER_AGENT'];
$time = time();
$msg = "Feedback:\r\n".$feedbacktxt."\r\n\r\nToken: ".$token."\r\nUser Agent: ".$ua."\r\nTimestamp: ".$time;
$headers = 'From: AWESOME Feedback Form <awesome@bbrks.me>';
mail('ben@bbrks.me', '[AWESOME FEEDBACK]', $msg, $headers);
echo 'Thank you for your feedback. Redirecting in 3 seconds.';
} else {
echo '<strong>Error:</strong> No feedback was sent! Redirecting in 3 seconds.';
}
echo '<meta http-equiv="refresh" content="3; url='.$ref.'" />';
|
Fix dir of files to be updated in `replace()` function for babel plugin | #!/usr/bin/env node
const {readFileSync, writeFileSync} = require('fs')
const {join} = require('path')
function replace(name)
{
const {dest, dir = '', packageName, src} = this
const path = join('node_modules', packageName, dir, `${name}.js`)
const data = readFileSync(path, 'utf8')
writeFileSync(path, data.replace(src, dest))
}
// Enable `react-native-web` in webpack by directly modifying files in `react-scripts`
const files =
[
'jest/babelTransform',
'webpack.config'
]
files.forEach(replace,
{
dest: 'babelrc: false,\nplugins: [\'react-native-web\'],',
dir: 'config',
packageName: 'react-scripts',
src: 'babelrc: false,'
})
// Replace usage of `react-native-web` for `react-native-web_improved`
replace.call({
dest: 'react-native-web_improved',
dir: 'src',
packageName: 'babel-plugin-react-native-web',
src: 'react-native-web'
}, 'index')
| #!/usr/bin/env node
const {readFileSync, writeFileSync} = require('fs')
function replace(name)
{
const {dest, packageName, src} = this
const path = `node_modules/${packageName}/config/${name}.js`
const data = readFileSync(path, 'utf8')
writeFileSync(path, data.replace(src, dest))
}
// Enable `react-native-web` in webpack by directly modifying files in `react-scripts`
const files =
[
'jest/babelTransform',
'webpack.config'
]
files.forEach(replace,
{
dest: 'babelrc: false,\nplugins: [\'react-native-web\'],',
packageName: 'react-scripts',
src: 'babelrc: false,'
})
// Replace usage of `react-native-web` for `react-native-web_improved`
replace.call({
dest: 'react-native-web_improved',
packageName: 'babel-plugin-react-native-web',
src: 'react-native-web'
}, 'index')
|
test: Enable long stack traces for testing | /**
* Created by Aaron on 7/6/2015.
*/
import assert from 'assert';
import Promise from 'bluebird';
Promise.longStackTraces();
export function runTests( build, tests ) {
assert( build === 'compat' || build === 'modern', 'Only modern and compat builds are supported' );
let Scriptor;
describe( `requiring ${build} build`, () => {
Scriptor = require( `../../build/${build}/index.js` );
} );
if( typeof tests === 'function' ) {
tests( Scriptor, build );
} else if( Array.isArray( tests ) ) {
for( let test of tests ) {
assert( typeof test === 'function', 'tests must be a function or array of functions' );
test( Scriptor, build );
}
} else {
throw new TypeError( 'tests must be a function or array of functions' );
}
}
| /**
* Created by Aaron on 7/6/2015.
*/
import assert from 'assert';
export function runTests( build, tests ) {
assert( build === 'compat' || build === 'modern', 'Only modern and compat builds are supported' );
let Scriptor;
describe( `requiring ${build} build`, () => {
Scriptor = require( `../../build/${build}/index.js` );
} );
if( typeof tests === 'function' ) {
tests( Scriptor, build );
} else if( Array.isArray( tests ) ) {
for( let test of tests ) {
assert( typeof test === 'function', 'tests must be a function or array of functions' );
test( Scriptor, build );
}
} else {
throw new TypeError( 'tests must be a function or array of functions' );
}
}
|
Add watch task for continuous testing during development | var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var mocha = require('gulp-mocha');
gulp.task('lint', function () {
return gulp
.src(['./*.js', './lib/**/*.js', './test/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter(stylish))
.pipe(jshint.reporter('fail'));
});
gulp.task('test', ['lint'], function () {
return gulp
.src('./test/**/*.js', { read: false })
.pipe(mocha({
reporter: 'spec',
globals: {
should: require('should')
}
}));
});
gulp.task('watch', function() {
gulp.watch('lib/**/*.js', ['test']);
gulp.watch('test/**/*.js', ['test']);
});
gulp.task('default', ['test']); | var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var mocha = require('gulp-mocha');
gulp.task('lint', function () {
return gulp
.src(['./*.js', './lib/**/*.js', './test/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter(stylish))
.pipe(jshint.reporter('fail'));
});
gulp.task('test', ['lint'], function () {
return gulp
.src('./test/**/*.js', { read: false })
.pipe(mocha({
reporter: 'spec',
globals: {
should: require('should')
}
}));
});
gulp.task('default', ['test']); |
Clean up imports of factory class | /*
* Copyright 2016-2019 Stefan Kalscheuer
*
* 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 de.stklcode.jvault.connector.factory;
import de.stklcode.jvault.connector.builder.VaultConnectorBuilder;
/**
* Abstract Vault Connector Factory interface.
* Provides builder pattern style factory for Vault connectors.
*
* @author Stefan Kalscheuer
* @since 0.1
* @deprecated As of 0.8.0 please refer to {@link VaultConnectorBuilder} with identical API.
*/
@Deprecated
public abstract class VaultConnectorFactory implements VaultConnectorBuilder {
/**
* Get Factory implementation for HTTP Vault Connector.
*
* @return HTTP Connector Factory
* @deprecated As of 0.8.0 please refer to {@link VaultConnectorBuilder#http()}.
*/
@Deprecated
public static HTTPVaultConnectorFactory httpFactory() {
return new HTTPVaultConnectorFactory();
}
}
| /*
* Copyright 2016-2019 Stefan Kalscheuer
*
* 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 de.stklcode.jvault.connector.factory;
import de.stklcode.jvault.connector.VaultConnector;
import de.stklcode.jvault.connector.builder.VaultConnectorBuilder;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
/**
* Abstract Vault Connector Factory interface.
* Provides builder pattern style factory for Vault connectors.
*
* @author Stefan Kalscheuer
* @since 0.1
* @deprecated As of 0.8.0 please refer to {@link VaultConnectorBuilder} with identical API.
*/
@Deprecated
public abstract class VaultConnectorFactory implements VaultConnectorBuilder {
/**
* Get Factory implementation for HTTP Vault Connector.
*
* @return HTTP Connector Factory
* @deprecated As of 0.8.0 please refer to {@link VaultConnectorBuilder#http()}.
*/
@Deprecated
public static HTTPVaultConnectorFactory httpFactory() {
return new HTTPVaultConnectorFactory();
}
}
|
Fix __COPYRIGHT__ and __REVISION__ in new Darwin module. | """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import posix
import os
def generate(env):
posix.generate(env)
env['SHLIBSUFFIX'] = '.dylib'
| """engine.SCons.Platform.darwin
Platform-specific initialization for Mac OS X systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 Steven Knight
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
import posix
import os
def generate(env):
posix.generate(env)
env['SHLIBSUFFIX'] = '.dylib'
|
Use app make to ensure new instances | <?php
namespace Concrete\Core\File\ImportProcessor;
use Concrete\Core\Entity\File\Version;
use Concrete\Core\Support\Facade\Image;
use Imagine\Filter\Basic\Autorotate;
use Imagine\Filter\Transformation;
use Imagine\Image\Metadata\ExifMetadataReader;
use Concrete\Core\Support\Facade\Application;
class AutorotateImageProcessor implements ProcessorInterface
{
public function shouldProcess(Version $version)
{
return function_exists('exif_read_data')
&& $version->getTypeObject()->getName() == 'JPEG';
}
public function process(Version $version)
{
$fr = $version->getFileResource();
$app = Application::getFacadeApplication();
$imagine = $app->make(Image::getFacadeAccessor());
$imagine->setMetadataReader(new ExifMetadataReader);
$image = $imagine->load($fr->read());
$transformation = new Transformation($imagine);
$transformation->applyFilter($image, new Autorotate());
$version->updateContents($image->get('jpg'));
}
}
| <?php
namespace Concrete\Core\File\ImportProcessor;
use Concrete\Core\Entity\File\Version;
use Concrete\Core\Support\Facade\Image;
use Imagine\Filter\Basic\Autorotate;
use Imagine\Filter\Transformation;
use Imagine\Image\Metadata\ExifMetadataReader;
class AutorotateImageProcessor implements ProcessorInterface
{
public function shouldProcess(Version $version)
{
return function_exists('exif_read_data')
&& $version->getTypeObject()->getName() == 'JPEG';
}
public function process(Version $version)
{
$fr = $version->getFileResource();
$imagine = Image::getFacadeRoot()->setMetadataReader(new ExifMetadataReader);
$image = $imagine->load($fr->read());
$transformation = new Transformation($imagine);
$transformation->applyFilter($image, new Autorotate());
$version->updateContents($image->get('jpg'));
}
} |
Make _filename and save non-enumerable and fixed indentation
PR: https://github.com/brendanashworth/flatfile/pull/1 | var fs = require('fs');
// This is the flatfile.db() function. It instantiates a local database asynchronously.
var db = function(filename, callback) {
fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
if (err) {
// If an error occurred, stop execution and return the error for handling.
callback(err, null);
}
// Parse data
data = JSON.parse(data);
// Adds various library-specific data handles
data._filename = filename;
// Adds the save function
data.save = function(callback) {
var filename = data._filename,
dataCopy = JSON.parse(JSON.stringify(data)); // We have to do it this way in order to clone the object instead of reference it.
// Remove the library-specific data handles
delete dataCopy._filename;
delete dataCopy.save;
// Get string
dataCopy = JSON.stringify(dataCopy);
// Write to the file
fs.writeFile(filename, dataCopy, function(err) {
callback(err);
});
};
// Make _filename and save non-enumerable so that they dont mess up data.length
Object.defineProperties(data, {
'_filename': {
enumerable: false
},
'save': {
enumerable: false
}
});
callback(null, data);
});
};
module.exports = {
db: db
};
| var fs = require('fs');
// This is the flatfile.db() function. It instantiates a local database asynchronously.
var db = function(filename, callback) {
fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
if (err) {
// If an error occurred, stop execution and return the error for handling.
callback(err, null);
}
// Parse data
data = JSON.parse(data);
// Adds various library-specific data handles
data._filename = filename;
// Adds the save function
data.save = function(callback) {
var filename = data._filename,
dataCopy = JSON.parse(JSON.stringify(data)); // We have to do it this way in order to clone the object instead of reference it.
// Remove the library-specific data handles
delete dataCopy._filename;
delete dataCopy.save;
// Get string
dataCopy = JSON.stringify(dataCopy);
// Write to the file
fs.writeFile(filename, dataCopy, function(err) {
callback(err);
});
};
callback(null, data);
});
};
module.exports = {
db: db
}; |
Make each location a link to the edit page instead of using a button | <!-- resources/views/admin/location_index.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Locations</h2>
<p>Click a location to edit</p>
<table class="table">
<tbody>
@foreach ($locations->chunk(2) as $chunk )
<tr>
@foreach ($chunk as $location)
<td>{{ $location->id }}</td>
<td><a href="/admin/locations/{{ $location->id }}/edit">{{ $location->location }}</a></td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
<h2>Add a Location</h2>
<!-- Add a new location -->
<form class="form-inline" action="/admin/locations" method="POST">
<div class="form-group">
{{ csrf_field() }}
<label for="location">New Location:</label> <input type="TEXT" class="form-control" id="location" name="location" size="20" placeholder="Location" />
<button type="SUBMIT" class="btn btn-default">Add location</button> / <a href="/">Main</a>
</div>
</form>
@endsection
| <!-- resources/views/admin/location_index.blade.php -->
@extends('layouts.app')
@section('content')
<h2>Locations</h2>
<table class="table"
<tbody>
@foreach ($locations->chunk(2) as $chunk )
<tr>
@foreach ($chunk as $location)
<td>{{ $location->id }}</td>
<td>{{ $location->location }}</td>
<td>
<form action="/admin/locations/{{ $location->id }}/edit" method="POST">
<button type="submit">Edit</button>
</form>
</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
<h2>Add a Location</h2>
<!-- Add a new location -->
<form action="/admin/locations" method="POST">
{{ csrf_field() }}
New Location: <input type="TEXT" name="location" size="20" />
<button type="SUBMIT">Add location</button> / <a href="/">Main</a>
</form>
@endsection
|
Substitute the default prelude in browser-pack, brfs doesn't seem to pick it up | var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
var fs = require('fs');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
var textReplacements = [
[/rfile\('.\/template.js'\)/, JSON.stringify(fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8'))],
[/fs\.readFileSync\(defaultPreludePath, 'utf8'\)/, JSON.stringify(fs.readFileSync('node_modules/browserify/node_modules/browser-pack/_prelude.js', 'utf8'))],
];
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
var data = '';
return through(write, end);
function write(buf) { data += buf; }
function end() {
for (var i = 0; i < textReplacements.length; i += 1) {
var regex = textReplacements[i][0];
var replacement = textReplacements[i][1];
data = data.replace(regex, replacement);
}
this.queue(data);
this.queue(null);
};
}, { global: true });
b.transform('brfs');
b.add('./webnpm.js');
b.bundle().pipe(process.stdout);
| var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
var fs = require('fs');
require('browserify/lib/builtins').fs = 'create-webfs.js'; // TODO: find a better way to replace this module
var b = browserify();
var textReplacements = [
[/rfile\('.\/template.js'\)/, JSON.stringify(fs.readFileSync('node_modules//browserify/node_modules/umd/template.js', 'utf8'))],
];
// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
var data = '';
return through(write, end);
function write(buf) { data += buf; }
function end() {
for (var i = 0; i < textReplacements.length; i += 1) {
var regex = textReplacements[i][0];
var replacement = textReplacements[i][1];
data = data.replace(regex, replacement);
}
this.queue(data);
this.queue(null);
};
}, { global: true });
b.transform('brfs');
b.add('./webnpm.js');
b.bundle().pipe(process.stdout);
|
twitch: Add user_read as default scope | from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class TwitchAccount(ProviderAccount):
def get_profile_url(self):
return 'http://twitch.tv/' + self.account.extra_data.get('name')
def get_avatar_url(self):
return self.account.extra_data.get('logo')
def to_str(self):
dflt = super(TwitchAccount, self).to_str()
return self.account.extra_data.get('name', dflt)
class TwitchProvider(OAuth2Provider):
id = 'twitch'
name = 'Twitch'
account_class = TwitchAccount
def extract_uid(self, data):
return str(data['_id'])
def extract_common_fields(self, data):
return {
"username": data.get("name"),
"name": data.get("display_name"),
"email": data.get("email"),
}
def get_default_scope(self):
return ["user_read"]
provider_classes = [TwitchProvider]
| from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class TwitchAccount(ProviderAccount):
def get_profile_url(self):
return 'http://twitch.tv/' + self.account.extra_data.get('name')
def get_avatar_url(self):
return self.account.extra_data.get('logo')
def to_str(self):
dflt = super(TwitchAccount, self).to_str()
return self.account.extra_data.get('name', dflt)
class TwitchProvider(OAuth2Provider):
id = 'twitch'
name = 'Twitch'
account_class = TwitchAccount
def extract_uid(self, data):
return str(data['_id'])
def extract_common_fields(self, data):
return dict(username=data.get('name'),
name=data.get('display_name'),
email=data.get('email'))
provider_classes = [TwitchProvider]
|
Update timer for star rating | import test from 'tape-async'
import helper from 'tipsi-appium-helper'
const { driver, select, idFromXPath } = helper
test('<StarRating />', async (t) => {
const starsAndTextId = select({
ios: idFromXPath(`//
XCUIElementTypeScrollView/*/*/XCUIElementTypeOther[2]/
XCUIElementTypeOther/XCUIElementTypeStaticText
`),
android: idFromXPath(`//
android.widget.ScrollView[1]/android.view.ViewGroup[1]/*/
android.widget.TextView
`),
})
try {
await helper.openExampleFor('<StarRating />')
const elements = await driver
.waitForVisible(starsAndTextId, 20000)
.elements(starsAndTextId)
t.same(
elements.value.length,
27,
'Should render five <StarRating /> components'
)
} catch (error) {
await helper.screenshot()
await helper.source()
throw error
}
})
| import test from 'tape-async'
import helper from 'tipsi-appium-helper'
const { driver, select, idFromXPath } = helper
test('<StarRating />', async (t) => {
const starsAndTextId = select({
ios: idFromXPath(`//
XCUIElementTypeScrollView/*/*/XCUIElementTypeOther[2]/
XCUIElementTypeOther/XCUIElementTypeStaticText
`),
android: idFromXPath(`//
android.widget.ScrollView[1]/android.view.ViewGroup[1]/*/
android.widget.TextView
`),
})
try {
await helper.openExampleFor('<StarRating />')
const elements = await driver
.waitForVisible(starsAndTextId, 5000)
.elements(starsAndTextId)
t.same(
elements.value.length,
27,
'Should render five <StarRating /> components'
)
} catch (error) {
await helper.screenshot()
await helper.source()
throw error
}
})
|
Allow tasks to throw an exception so that it can be caught and passed to
the task observer.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@24 6335cc39-0255-0410-8fd6-9bcaacd3b74c | //
// $Id: Task.java,v 1.2 2000/12/07 05:41:30 mdb Exp $
package com.samskivert.swing.util;
/**
* A swing application requests that a task be invoked by the task
* master. The task master invokes the task on a separate thread and
* informs the swing application when the task has completed via the task
* observer interface. It does so in a way that plays nicely with the
* swing event dispatch thread (the swing application is notified of the
* task's completion on the event dispatch thread so that it can wiggle
* its user interface elements to its heart's desire).
*/
public interface Task
{
/**
* This method is called by the task master to invoke the task. The
* task should run to completion and return some value.
*/
public Object invoke () throws Exception;
/**
* This method is called by the task master when it has received a
* request to cancel this task. If the task can be cancelled, abort
* should return true and the currently running call to
* <code>invoke()</code> should immediately return (the return value
* will be ignored). If the task cannot be cancelled, abort should
* return false and the task master will simply abandon the task and
* the thread on which it is running.
*/
public boolean abort ();
}
| //
// $Id: Task.java,v 1.1 2000/12/06 03:25:19 mdb Exp $
package com.samskivert.swing.util;
/**
* A swing application requests that a task be invoked by the task
* master. The task master invokes the task on a separate thread and
* informs the swing application when the task has completed via the task
* observer interface. It does so in a way that plays nicely with the
* swing event dispatch thread (the swing application is notified of the
* task's completion on the event dispatch thread so that it can wiggle
* its user interface elements to its heart's desire).
*/
public interface Task
{
/**
* This method is called by the task master to invoke the task. The
* task should run to completion and return some value.
*/
public Object invoke ();
/**
* This method is called by the task master when it has received a
* request to cancel this task. If the task can be cancelled, abort
* should return true and the currently running call to
* <code>invoke()</code> should immediately return (the return value
* will be ignored). If the task cannot be cancelled, abort should
* return false and the task master will simply abandon the task and
* the thread on which it is running.
*/
public boolean abort ();
}
|
Set prefetch count to 1000. | class AMQPMixin(object):
amqp_setup = False
def setupAMQP(self, config):
if not self.amqp_setup:
# Create AMQP Connection
# AMQP connection parameters
self.amqp_host = config["amqp_host"]
self.amqp_port = config.get("amqp_port", 5672)
self.amqp_username = config["amqp_username"]
self.amqp_password = config["amqp_password"]
self.amqp_queue = config["amqp_queue"]
self.amqp_exchange = config["amqp_exchange"]
self.amqp_prefetch_count = 1000
self.amqp_setup = True
| class AMQPMixin(object):
amqp_setup = False
def setupAMQP(self, config):
if not self.amqp_setup:
# Create AMQP Connection
# AMQP connection parameters
self.amqp_host = config["amqp_host"]
self.amqp_port = config.get("amqp_port", 5672)
self.amqp_username = config["amqp_username"]
self.amqp_password = config["amqp_password"]
self.amqp_queue = config["amqp_queue"]
self.amqp_exchange = config["amqp_exchange"]
self.amqp_prefetch_count = 100
self.amqp_setup = True
|
Use pseudoRandomBytes, which maps to OpenSSL's RAND_pseudo_bytes which for uid generation is fine | /**
* Module dependencies
*/
var crypto = require('crypto');
/**
* 62 characters in the ascii range that can be used in URLs without special
* encoding.
*/
var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
/**
* Make a Buffer into a string ready for use in URLs
*
* @param {String}
* @returns {String}
* @api private
*/
function tostr(bytes) {
var chars, r, i;
r = [];
for (i = 0; i < bytes.length; i++) {
r.push(UIDCHARS[bytes[i] % UIDCHARS.length]);
}
return r.join('');
}
/**
* Generate an Unique Id
*
* @param {Number} length The number of chars of the uid
* @param {Number} cb (optional) Callback for async uid generation
* @api public
*/
function uid(length, cb) {
if (typeof cb === 'undefined') {
return tostr(crypto.pseudoRandomBytes(length));
} else {
crypto.pseudoRandomBytes(length, function(err, bytes) {
if (err) return cb(err);
cb(null, tostr(bytes));
})
}
}
/**
* Exports
*/
module.exports = uid;
| /**
* Module dependencies
*/
var crypto = require('crypto');
/**
* 62 characters in the ascii range that can be used in URLs without special
* encoding.
*/
var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
/**
* Make a Buffer into a string ready for use in URLs
*
* @param {String}
* @returns {String}
* @api private
*/
function tostr(bytes) {
var chars, r, i;
r = [];
for (i = 0; i < bytes.length; i++) {
r.push(UIDCHARS[bytes[i] % UIDCHARS.length]);
}
return r.join('');
}
/**
* Generate an Unique Id
*
* @param {Number} length The number of chars of the uid
* @param {Number} cb (optional) Callback for async uid generation
* @api public
*/
function uid(length, cb) {
if (typeof cb === 'undefined') {
return tostr(crypto.randomBytes(length));
} else {
crypto.randomBytes(length, function(err, bytes) {
if (err) return cb(err);
cb(null, tostr(bytes));
})
}
}
/**
* Exports
*/
module.exports = uid;
|
Set default location when no GPS data exists. | <?php
require("./creds.php");
// Connect to Database
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
// Get Latitude/Longitude data from MySQL
$geoqry = mysql_query("SELECT kff1006, kff1005
FROM $db_table
ORDER BY time DESC
LIMIT 5000") or die(mysql_error());
$latlong = array();
while($geo = mysql_fetch_array($geoqry)) {
if (($geo["0"] != 0) && ($geo["1"] != 0)) {
$latlong[] = array("latitude" => $geo["0"], "longitude" => $geo["1"]);
}
}
// Create array of Latitude/Longitude strings in Google Maps JavaScript format
$mapdata = array();
foreach($latlong as $d) {
$mapdata[] = "new google.maps.LatLng(" . $d['latitude'] . ", " . $d['longitude'] . ")";
}
$imapdata = implode(",\n ", $mapdata);
// Centering location for the map is the most recent location
if (isset($latlong[0])) {
$centerlat = $latlong[0]["latitude"];
$centerlong = $latlong[0]["longitude"];
}
else {
$centerlat = 38.5;
$centerlong = -98;
}
?>
| <?php
require("./creds.php");
// Connect to Database
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
// Get Latitude/Longitude data from MySQL
$geoqry = mysql_query("SELECT kff1006, kff1005
FROM $db_table
ORDER BY time DESC
LIMIT 5000") or die(mysql_error());
$latlong = array();
while($geo = mysql_fetch_array($geoqry)) {
if (($geo["0"] != 0) && ($geo["1"] != 0)) {
$latlong[] = array("latitude" => $geo["0"], "longitude" => $geo["1"]);
}
}
// Create array of Latitude/Longitude strings in Google Maps JavaScript format
$mapdata = array();
foreach($latlong as $d) {
$mapdata[] = "new google.maps.LatLng(" . $d['latitude'] . ", " . $d['longitude'] . ")";
}
$imapdata = implode(",\n ", $mapdata);
// Centering location for the map is the most recent location
$centerlat = $latlong[0]["latitude"];
$centerlong = $latlong[0]["longitude"];
?>
|
Use Pillow instead of PIL | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = "django-dummyimage",
version = "0.1.1",
description = "Dynamic Dummy Image Generator For Django!",
author = "Rolando Espinoza La fuente",
author_email = "darkrho@gmail.com",
url = "https://github.com/darkrho/django-dummyimage",
license = "BSD",
packages = find_packages(),
zip_safe=False, # because we're including media that Django needs
include_package_data = True,
install_requires = [
'Django',
'Pillow',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Django',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = "django-dummyimage",
version = "0.1.1",
description = "Dynamic Dummy Image Generator For Django!",
author = "Rolando Espinoza La fuente",
author_email = "darkrho@gmail.com",
url = "https://github.com/darkrho/django-dummyimage",
license = "BSD",
packages = find_packages(),
zip_safe=False, # because we're including media that Django needs
include_package_data = True,
install_requires = [
'Django',
'PIL',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Django',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
],
)
|
Create the ManagedRunner with all the new args. | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for ``admin.acceptance``.
"""
from zope.interface.verify import verifyObject
from twisted.trial.unittest import SynchronousTestCase
from ..acceptance import IClusterRunner, ManagedRunner
from flocker.provision import PackageSource
from flocker.acceptance.testtools import DatasetBackend
class ManagedRunnerTests(SynchronousTestCase):
"""
Tests for ``ManagedRunner``.
"""
def test_interface(self):
"""
``ManagedRunner`` provides ``IClusterRunner``.
"""
runner = ManagedRunner(
node_addresses=[b'192.0.2.1'],
package_source=PackageSource(
version=b"",
os_version=b"",
branch=b"",
build_serve=b"",
),
distribution=b'centos-7',
dataset_backend=DatasetBackend.zfs,
dataset_backend_configuration={},
)
self.assertTrue(
verifyObject(IClusterRunner, runner)
)
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for ``admin.acceptance``.
"""
from zope.interface.verify import verifyObject
from twisted.trial.unittest import SynchronousTestCase
from ..acceptance import IClusterRunner, ManagedRunner
class ManagedRunnerTests(SynchronousTestCase):
"""
Tests for ``ManagedRunner``.
"""
def test_interface(self):
"""
``ManagedRunner`` provides ``IClusterRunner``.
"""
runner = ManagedRunner(
node_addresses=[b'192.0.2.1'],
distribution=b'centos-7'
)
self.assertTrue(
verifyObject(IClusterRunner, runner)
)
|
Correct the order of coordinates.
Geojson expects lon, lat. | import pandas as pd
import geojson
from geojson import FeatureCollection, Feature, Point
# read in original data
csv = pd.read_csv("versaille_stock.csv", sep="\t")
# fetch properties, remove Long and Lat
props = list(csv.columns.values)
props = [p for p in props if p not in ["Longitude",
"Latitude"]]
features = []
for row in csv.iterrows():
accession = row[1]
lat = accession["Latitude"]
lon = accession["Longitude"]
# automatically populate accession properties
feature_props = {p: accession[p] for p in props}
f = Feature(
geometry = Point((lon,lat))
)
features.append(f)
fc = FeatureCollection(features)
with open("accession_locations.json", "w") as fh:
geojson.dump(fc, fh) | import pandas as pd
import geojson
from geojson import FeatureCollection, Feature, Point
# read in original data
csv = pd.read_csv("versaille_stock.csv", sep="\t")
# fetch properties, remove Long and Lat
props = list(csv.columns.values)
props = [p for p in props if p not in ["Longitude",
"Latitude"]]
features = []
for row in csv.iterrows():
accession = row[1]
lat = accession["Latitude"]
lon = accession["Longitude"]
# automatically populate accession properties
feature_props = {p: accession[p] for p in props}
f = Feature(
geometry = Point((lat,lon))
)
features.append(f)
fc = FeatureCollection(features)
with open("accession_locations.json", "w") as fh:
geojson.dump(fc, fh) |
Move epom key to config. | <?php
class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract {
/**
* @return string
*/
private function _getAccessKey() {
return self::_getConfig()->accessKey;
}
public function getHtml($zoneData, array $variables) {
$zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']);
$variables = $this->_variableKeysToUnderscore($variables);
$variables['key'] = $this->_getAccessKey();
$html = '<div id="epom-' . $zoneId . '" class="epom-ad" data-zone-id="' . $zoneId . '" data-variables="' .
CM_Util::htmlspecialchars(json_encode($variables, JSON_FORCE_OBJECT)) . '"></div>';
return $html;
}
private function _variableKeysToUnderscore($variables) {
foreach ($variables as $key => $value) {
unset ($variables[$key]);
$underscoreKey = str_replace('-', '_', $key);
$variables[$underscoreKey] = $value;
}
return $variables;
}
}
| <?php
class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract {
public function getHtml($zoneData, array $variables) {
$zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']);
$variables = $this->_variableKeysToUnderscore($variables);
$variables['key'] = '2ea5b261f06ca771033a5fa9e22493f1';
$html = '<div id="epom-' . $zoneId . '" class="epom-ad" data-zone-id="' . $zoneId . '" data-variables="' .
CM_Util::htmlspecialchars(json_encode($variables, JSON_FORCE_OBJECT)) . '"></div>';
return $html;
}
private function _variableKeysToUnderscore($variables) {
foreach ($variables as $key => $value) {
unset ($variables[$key]);
$underscoreKey = str_replace('-', '_', $key);
$variables[$underscoreKey] = $value;
}
return $variables;
}
}
|
Allow Contacts: Phone column to be hidden | <div class="table-responsive"><table class="table table-striped">
<?php
$position_label = get_option( 'staff_position_label', 'Position' );
echo sprintf( '<thead><tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr></thead>',
__( 'Name', 'proud-teaser' ),
__( $position_label, 'proud-teaser' ),
empty($this->hide['agency']) ? _x( 'Agency', 'post type singular name', 'wp-agency' ) : '',
empty($this->hide['phone']) ? __( 'Phone', 'proud-teaser' ) : '',
__( 'Contact', 'proud-teaser' ),
empty($this->hide['social']) ? __( 'Social', 'proud-teaser' ) : ''
);
?>
<tbody>
| <div class="table-responsive"><table class="table table-striped">
<?php
$position_label = get_option( 'staff_position_label', 'Position' );
echo sprintf( '<thead><tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr></thead>',
__( 'Name', 'proud-teaser' ),
__( $position_label, 'proud-teaser' ),
empty($this->hide['agency']) ? _x( 'Agency', 'post type singular name', 'wp-agency' ): '',
__( 'Phone', 'proud-teaser' ),
__( 'Contact', 'proud-teaser' ),
empty($this->hide['social']) ? __( 'Social', 'proud-teaser' ) : ''
);
?>
<tbody>
|
Update dsub version to 0.4.5.dev0
PiperOrigin-RevId: 358198209 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.5.dev0'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.4'
|
Debug Google Cloud Run support | #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax: entrypoint.py <command>
#
# Author: Chris Williams <diodesign@tuta.io>
#
import os
import sys
global command_result
from flask import Flask
app = Flask(__name__)
# for Google Cloud Run
@app.route('/')
def ContainerService():
return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
if __name__ == "__main__":
if (os.environ.get('K_SERVICE')) != '':
print('Running HTTP service for Google Cloud')
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
else:
print('Running locally')
stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:])))
output = stream.read()
output
| #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Use this to signal the build was successful and the container\
# can be run via the command line.
#
# On all other environments: Log to stdout
#
# syntax: entrypoint.py <command>
#
# Author: Chris Williams <diodesign@tuta.io>
#
import os
import sys
global command_result
from flask import Flask
app = Flask(__name__)
# for Google Cloud Run
@app.route('/')
def ContainerService():
return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
if __name__ == "__main__":
if (os.environ.get('K_SERVICE')) != '':
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
else:
stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:])))
output = stream.read()
output
|
Fix syntax on findByPage findBySlug | (function() {
angular.module('c4cWebsite.actions')
.factory('ActionService', ['$q', 'Tabletop', actionService]);
/**
* Returns a promise when the action service is loaded
*/
function actionService($q, Tabletop) {
var service = init(),
actionSheet;
return service;
function init() {
var service = {
findBySlug: findBySlug,
findByPage: findByPage,
}
var deferred = $q.defer();
Tabletop.then(function(TabletopSheets) {
actionSheet = TabletopSheets[0]["Actions"].all();
deferred.resolve(service);
});
return deferred.promise;
};
/**
* Find an action by slug
*/
function findBySlug(slug) {
for (var i=0; i<actionSheet.length; i++) {
var row = actionSheet[i];
if (row["Slug"] == slug)
return row;
}
};
/**
* Find an action by slug
*/
function findByPage(page) {
for (var i=0; i<actionSheet.length; i++) {
var row = actionSheet[i];
if (row["page slug"] == page)
return row;
}
};
};
})(); | (function() {
angular.module('c4cWebsite.actions')
.factory('ActionService', ['$q', 'Tabletop', actionService]);
/**
* Returns a promise when the action service is loaded
*/
function actionService($q, Tabletop) {
var service = init(),
actionSheet;
return service;
function init() {
var service = {
findBySlug: findBySlug,
findByPage: findByPage,
}
var deferred = $q.defer();
Tabletop.then(function(TabletopSheets) {
actionSheet = TabletopSheets[0]["Actions"].all();
deferred.resolve(service);
});
return deferred.promise;
};
/**
* Find an action by slug
*/
function findBySlug(slug) {
angular.forEach(actionSheet, function(row) {
if (row["Slug"] == slug)
return row;
});
};
/**
* Find an action by slug
*/
function findByPage(page) {
angular.forEach(actionSheet, function(row) {
if (row["page slug"] == page)
return row;
});
};
};
})(); |
Read More module: fixed upgrader versioning | <?php
if (!defined('UPGRADING') or !UPGRADING)
exit;
/**
* Function: read_more_add_config
* Adds config settings into an array.
*
* Versions: 2022.02 => 2022.03
*/
function read_more_add_config(): void {
$set = Config::current()->set("module_read_more",
array("apply_to_feeds" => false, "default_text" => ""),
true);
if ($set === false)
error(__("Error"), __("Could not write the configuration file."));
}
read_more_add_config();
| <?php
if (!defined('UPGRADING') or !UPGRADING)
exit;
/**
* Function: read_more_add_config
* Adds config settings into an array.
*
* Versions: 2022.01 => 2022.02
*/
function read_more_add_config(): void {
$set = Config::current()->set("module_read_more",
array("apply_to_feeds" => false, "default_text" => ""),
true);
if ($set === false)
error(__("Error"), __("Could not write the configuration file."));
}
read_more_add_config();
|
Support multi syntax for CSS formatting | import fs from "fs"
import gulp from "gulp"
import postcss from "postcss"
import stylelint from "gulp-stylelint"
import stylefmt from "stylefmt"
import { extname } from "path"
import scss from "postcss-scss"
import sugarss from "sugarss"
import { getGitFiles } from "./core"
gulp.task("lint:css", () => {
return gulp
.src(getGitFiles(/\.(css|sass|scss|sss)$/), { base: "." })
.pipe(stylelint({
reporters: [{ formatter: "string", console: true }]
}))
})
gulp.task("fix:css", () => {
var cssFiles = getGitFiles(/\.(css|sass|scss|sss)$/)
cssFiles.forEach((fileName) => {
var fileContent = fs.readFileSync(fileName, "utf-8")
var fileExtension = extname(fileName)
var fileSyntax = null
if (fileExtension === ".scss") {
fileSyntax = scss
}
if (fileExtension === ".sss") {
fileSyntax = sugarss
}
postcss([ stylefmt ])
.process(fileContent, {
from: fileName,
syntax: fileSyntax
})
.then((result) => {
return fs.writeFileSync(fileName, result.css, "utf-8")
})
.catch((error) => {
throw new Error(`Error during CSS formatting: ${error}`)
})
})
})
| import fs from "fs"
import gulp from "gulp"
import postcss from "postcss"
import stylelint from "gulp-stylelint"
import stylefmt from "stylefmt"
import { getGitFiles } from "./core"
gulp.task("lint:css", () => {
return gulp
.src(getGitFiles(/\.(css|sass|scss|sss)$/), { base: "." })
.pipe(stylelint({
reporters: [{ formatter: "string", console: true }]
}))
})
gulp.task("fix:css", () => {
var cssFiles = getGitFiles(/\.(css|sass|scss|sss)$/)
cssFiles.forEach((fileName) => {
var fileContent = fs.readFileSync(fileName, "utf-8")
// TODO: Support different syntax/formats
postcss([ stylefmt ])
.process(fileContent)
.then((result) => {
return fs.writeFileSync(fileName, result.css, "utf-8")
})
.catch((error) => {
throw new Error(`Error during CSS formatting: ${error}`)
})
})
})
|
Package name must be string, not Unicode | from distutils.core import setup
import gutter
setup(
name = u'gutter',
version = gutter.__version__,
author = gutter.__author__,
author_email = u'william@subtlecoolness.com',
url = u'https://gutter.readthedocs.org/',
description = u'Rainwave client framework',
packages = ['gutter'],
classifiers = [
u'Development Status :: 3 - Alpha',
u'Intended Audience :: Developers',
u'License :: OSI Approved :: MIT License',
u'Natural Language :: English',
u'Programming Language :: Python',
u'Programming Language :: Python :: 2.7',
u'Topic :: Software Development :: Libraries'
],
license = open(u'LICENSE').read()
)
| from distutils.core import setup
import gutter
setup(
name = u'gutter',
version = gutter.__version__,
author = gutter.__author__,
author_email = u'william@subtlecoolness.com',
url = u'https://gutter.readthedocs.org/',
description = u'Rainwave client framework',
packages = [u'gutter'],
classifiers = [
u'Development Status :: 3 - Alpha',
u'Intended Audience :: Developers',
u'License :: OSI Approved :: MIT License',
u'Natural Language :: English',
u'Programming Language :: Python',
u'Programming Language :: Python :: 2.7',
u'Topic :: Software Development :: Libraries'
],
license = open(u'LICENSE').read()
)
|
Reorder fields for occurence inline | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineAdmin):
model = Occurrence
extra = 1
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
|
fix: Create locale dir if doesn\' exist | const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const emojify = require('node-emoji').emojify
const program = require('commander')
const getConfig = require('lingui-conf').default
const plurals = require('make-plural')
const config = getConfig()
program.parse(process.argv)
function validateLocales (locales) {
const unknown = locales.filter(locale => !(locale in plurals))
if (unknown.length) {
console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`))
process.exit(1)
}
}
function addLocale (locales) {
if (fs.existsSync(config.localeDir)) {
fs.mkdirSync(config.localeDir)
}
locales.forEach(locale => {
const localeDir = path.join(config.localeDir, locale)
if (fs.existsSync(localeDir)) {
console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`))
} else {
fs.mkdirSync(localeDir)
console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`))
}
})
}
validateLocales(program.args)
console.log(emojify(':white_check_mark: Adding locales:'))
addLocale(program.args)
console.log()
console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
console.log(emojify(':sparkles: Done!'))
| const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const emojify = require('node-emoji').emojify
const program = require('commander')
const getConfig = require('lingui-conf').default
const plurals = require('make-plural')
const config = getConfig()
program.parse(process.argv)
function validateLocales (locales) {
const unknown = locales.filter(locale => !(locale in plurals))
if (unknown.length) {
console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`))
process.exit(1)
}
}
function addLocale (locales) {
locales.forEach(locale => {
const localeDir = path.join(config.localeDir, locale)
if (fs.existsSync(localeDir)) {
console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`))
} else {
fs.mkdirSync(localeDir)
console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`))
}
})
}
validateLocales(program.args)
console.log(emojify(':white_check_mark: Adding locales:'))
addLocale(program.args)
console.log()
console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
console.log(emojify(':sparkles: Done!'))
|
Update plus-sign as scope delimiter | <?php
# CLIENT ID
# https://i.imgur.com/GHI2ts5.png (screenshot)
$client_id = "";
# CLIENT SECRET
# https://i.imgur.com/r5dYANR.png (screenshot)
$secret_id = "";
# SCOPES SEPARATED BY + SIGN
# example: identify+email+guilds+connections
# $scopes = "identify+email";
$scopes = "";
# REDIRECT URL
# example: https://mydomain.com/includes/login.php
# example: https://mydomain.com/test/includes/login.php
$redirect_url = "";
# IMPORTANT READ THIS:
# - Set the `$bot_token` to your bot token if you want to use guilds.join scope to add a member to your server
# - Check login.php for more detailed info on this.
# - Leave it as it is if you do not want to use 'guilds.join' scope.
# https://i.imgur.com/2tlOI4t.png (screenshot)
$bot_token = null;
| <?php
# CLIENT ID
# https://i.imgur.com/GHI2ts5.png (screenshot)
$client_id = "";
# CLIENT SECRET
# https://i.imgur.com/r5dYANR.png (screenshot)
$secret_id = "";
# SCOPES SEPARATED BY SPACE
# example: identify email guilds connections
$scopes = "";
# REDIRECT URL
# example: https://mydomain.com/includes/login.php
# example: https://mydomain.com/test/includes/login.php
$redirect_url = "";
# IMPORTANT READ THIS:
# - Set the `$bot_token` to your bot token if you want to use guilds.join scope to add a member to your server
# - Check login.php for more detailed info on this.
# - Leave it as it is if you do not want to use 'guilds.join' scope.
# https://i.imgur.com/2tlOI4t.png (screenshot)
$bot_token = null;
|
feat: Set actions for select fields | import Ember from 'ember';
import $ from 'jquery';
export default Ember.Controller.extend({
transportApiSrv: Ember.inject.service('trasport-api'),
searchLocation: null,
destinations: null,
selectedDestination: null,
timetable: null,
setInitialState () {
const initialStation = this.get('model').stations[0];
this.set('searchLocation', initialStation.name);
$('.departures-select').children().eq(1).attr('selected', 'selected');
this.setDestinationSelectList(initialStation.station_code);
},
actions: {
destinationSelected (destination) {
let selectedService = this.get('destinations').filterBy('destination_name', destination);
this.set('timetable', selectedService);
},
departureSelected (departureStation) {
const $selectEl = $('.station-select');
$selectEl.attr('disabled', 'disabled');
$('select').material_select();
this.set('timetable', null);
this.setDestinationSelectList(departureStation).then(() => {
$selectEl.removeAttr('disabled');
});
}
},
setDestinationSelectList (stationCode) {
return this.get('transportApiSrv').getTrainSchedule({stationCode})
.then(response => {
this.set('destinations', response.departures.all);
Ember.run.later(() => {
$('select').material_select();
}, 500);
});
}
});
| import Ember from 'ember';
import $ from 'jquery';
export default Ember.Controller.extend({
transportApiSrv: Ember.inject.service('trasport-api'),
searchLocation: null,
destinations: null,
selectedDestination: null,
timetable: null,
setInitialState () {
const initialStation = this.get('model').stations[0];
this.set('searchLocation', initialStation.name);
$('.departures-select').children().eq(1).attr('selected', 'selected');
this.setDestinationSelectList(initialStation.station_code);
},
setDestinationSelectList (stationCode) {
return this.get('transportApiSrv').getTrainSchedule({stationCode})
.then(response => {
this.set('destinations', response.departures.all);
Ember.run.later(() => {
$('select').material_select();
}, 500);
});
}
});
|
Fix the url of message | 'use strict';
var express = require('express');
var supertest = require('supertest');
var logger = require('log4js').getLogger('Unit-Test');
var nconf = require('nconf');
nconf.argv()
.env()
.file({ file: 'config.json' });
var request = supertest(app);
exports['Check view health'] = function(test){
request.get('/message').end(function(err,res)){
test.equal(err,null,'It should not had any error!');
test.equal(res,200,'It should return 200!');
test.done();
}
}
exports['Test send message'] = {
'Test send message success':function(test){
request.post('/message'),
.send({'receiver':'','text':'Hello World'!})
.end(function(err,res)){
test.equal(err,null,'It should not had any error!')
test.equal(res,201,'It should return 201!');
}
}
}
| 'use strict';
var express = require('express');
var supertest = require('supertest');
var logger = require('log4js').getLogger('Unit-Test');
var nconf = require('nconf');
nconf.argv()
.env()
.file({ file: 'config.json' });
var request = supertest(app);
exports['Check view health'] = function(test){
request.get('/sendmessage').end(function(err,res)){
test.equal(err,null,'It should not had any error!');
test.equal(res,200,'It should return 200!');
test.done();
}
}
exports['Test send message'] = {
'Test send message success':function(test){
request.post('/sendmessage'),
.send({'receiver':'','text':'Hello World'!})
.end(function(err,res)){
test.equal(err,null,'It should not had any error!')
test.equal(res,201,'It should return 201!');
}
}
}
|
Change detection of checked checkbox
* If the checked attribute hasn’t been set, then later versions of
jQuery return “undefined” for .attr("checked")
* Switch to a more explicit check, .is(“:checked”) | $(document).ready(function() {
$.each(["business_size", "business_type", "location", "purpose", "sector", "stage", "support_type"], function(idx, facet) {
$("#business_support_" + facet + "_check_all").click(function(e) {
var $el = $(e.target);
$.each($el.parent().parent().find(":checkbox"), function(sidx, chkbx) {
$(chkbx).attr("checked", $el.is(":checked"));
});
});
});
/*
* Checks all child regions when a country is checked.
*/
var allLabels = $('#location').find('label');
var countries = allLabels.filter(function () {
return $(this).text().trim().match(/^England|Northern Ireland|Scotland|Wales$/);
});
countries.each (function (index, country) {
$(country).children(":checkbox").on("click", function () {
var countryLabel = $(country).text().trim();
var countryMatch = (countryLabel == "England" ? /England|London|Yorkshire/ : countryLabel);
var matches = allLabels.filter(function() {
var matchText = $(this).text().trim();
return matchText.match(countryMatch) && matchText != countryLabel;
});
var value = $(this).prop("checked");
matches.each (function (index, match) {
var checkbox = $(match).children(":checkbox");
checkbox.attr("checked", value);
});
});
});
});
| $(document).ready(function() {
$.each(["business_size", "business_type", "location", "purpose", "sector", "stage", "support_type"], function(idx, facet) {
$("#business_support_" + facet + "_check_all").click(function(e) {
var $el = $(e.target);
$.each($el.parent().parent().find(":checkbox"), function(sidx, chkbx) {
$(chkbx).attr("checked", ($el.attr("checked")?true:false));
});
});
});
/*
* Checks all child regions when a country is checked.
*/
var allLabels = $('#location').find('label');
var countries = allLabels.filter(function () {
return $(this).text().trim().match(/^England|Northern Ireland|Scotland|Wales$/);
});
countries.each (function (index, country) {
$(country).children(":checkbox").on("click", function () {
var countryLabel = $(country).text().trim();
var countryMatch = (countryLabel == "England" ? /England|London|Yorkshire/ : countryLabel);
var matches = allLabels.filter(function() {
var matchText = $(this).text().trim();
return matchText.match(countryMatch) && matchText != countryLabel;
});
var value = $(this).prop("checked");
matches.each (function (index, match) {
var checkbox = $(match).children(":checkbox");
checkbox.attr("checked", value);
});
});
});
});
|
Update the PyPI version to 8.0.1. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='8.0.1',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='8.0.0',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.