text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix missing negation / site detection | // ==UserScript==
// @include *
// @run-at document-start
// ==/UserScript==
/*
* Gmail-Basic-HTML-Select-All
*
* Add a "check all" button in HTML-Gmail's spam and trash folders.
*
* By kafene software <http://kafene.org/>
*/
window.addEventListener("DOMContentLoaded", function () {
if (!/^mail\.google\./i.test(window.location.host)) {
return;
}
var del = document.querySelector('input[type="submit"][value="Delete Forever"]');
if ('object' != typeof(del)) {
return;
}
var cbox = document.createElement('input');
cbox.setAttribute('type', 'checkbox');
cbox.addEventListener('click', function () {
var boxes = document.querySelectorAll('input[type="checkbox"]');
[].forEach.call(boxes, function (box) {
if (box == cbox) {
return;
} else if (box.checked) {
box.removeAttribute('checked');
} else {
box.setAttribute('checked', true);
}
});
});
del.parentNode.insertBefore(cbox, del);
});
| // ==UserScript==
// @include *
// @run-at document-start
// ==/UserScript==
/*
* Gmail-Basic-HTML-Select-All
*
* Add a "check all" button in HTML-Gmail's spam and trash folders.
*
* By kafene software <http://kafene.org/>
*/
window.addEventListener("DOMContentLoaded", function () {
if (/^mail\.google\./i.test(window.location.host)) {
return;
}
var del = document.querySelector('input[type="submit"][value="Delete Forever"]');
if (!del) {
return;
}
var cbox = document.createElement('input');
cbox.setAttribute('type', 'checkbox');
cbox.addEventListener('click', function () {
var boxes = document.querySelectorAll('input[type="checkbox"]');
[].forEach.call(boxes, function (box) {
if (box == cbox) { return; }
if (box.checked) {
box.removeAttribute('checked');
} else {
box.setAttribute('checked', true);
}
});
});
del.parentNode.insertBefore(cbox, del);
});
|
Fix mock ads for development |
import {
VERTICAL_AD_SLOT_DOM_ID,
SECOND_VERTICAL_AD_SLOT_DOM_ID,
HORIZONTAL_AD_SLOT_DOM_ID
} from 'js/ads/adSettings'
export default function (adId) {
var mockNetworkDelayMs = 0
const useMockDelay = false
if (useMockDelay) {
mockNetworkDelayMs = Math.random() * (1500 - 900) + 900
}
const mapDOMIdToHeight = {
[VERTICAL_AD_SLOT_DOM_ID]: 250,
[SECOND_VERTICAL_AD_SLOT_DOM_ID]: 250,
[HORIZONTAL_AD_SLOT_DOM_ID]: 90
}
const height = mapDOMIdToHeight[adId]
// Mock returning an ad.
setTimeout(() => {
const elem = document.getElementById(adId)
if (!elem) {
return
}
elem.setAttribute('style', `
color: white;
background: repeating-linear-gradient(
-55deg,
#222,
#222 20px,
#333 20px,
#333 40px
);
width: 100%;
height: ${height}px;
`)
}, mockNetworkDelayMs)
}
|
export default function (adId) {
var mockNetworkDelayMs = 0
const useMockDelay = false
if (useMockDelay) {
mockNetworkDelayMs = Math.random() * (1500 - 900) + 900
}
// Mock returning an ad.
setTimeout(() => {
const elem = document.getElementById(adId)
if (!elem) {
return
}
elem.setAttribute('style', `
color: white;
background: repeating-linear-gradient(
-55deg,
#222,
#222 20px,
#333 20px,
#333 40px
);
width: 100%;
height: 100%;
`)
}, mockNetworkDelayMs)
}
|
Update to only grab the gist ID, not the revision sha | // ==UserScript==
// @name gitFiddle
// @namespace http://jason.karns.name
// @include https://gist.github.com/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js
// @description When on a GitHub gist that looks like it contains jsFiddle content, add a quick link to easily load the fiddle.
// @author Jason Karns
// @version 0.1
// @date 2011-07-01
// @change initial release
// ==/UserScript==
jQuery(function($){
function gist_is_a_fiddle(){
return $("#file_fiddle\\.manifest, .file[id^='file_fiddle']", $("#files")).size() > 1;
}
function insert_fiddle_link(){
$("#repos .meta table tbody").append('<tr><td class="label">jsFiddle URL:</td><td><a class="gist-jsfiddle-link" href="'+fiddle_link()+'">'+fiddle_link()+'</td></tr>');
}
function fiddle_link(){
return "http://jsfiddle.net/gh/gist/jquery/1.6/" + location.pathname.match(/^\/([0-9]+)\//)[1];
}
if(gist_is_a_fiddle()) insert_fiddle_link();
});
| // ==UserScript==
// @name gitFiddle
// @namespace http://jason.karns.name
// @include https://gist.github.com/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js
// @description When on a GitHub gist that looks like it contains jsFiddle content, add a quick link to easily load the fiddle.
// @author Jason Karns
// @version 0.1
// @date 2011-07-01
// @change initial release
// ==/UserScript==
jQuery(function($){
function gist_is_a_fiddle(){
return $("#file_fiddle\\.manifest, .file[id^='file_fiddle']", $("#files")).size() > 1;
}
function insert_fiddle_link(){
$("#repos .meta table tbody").append('<tr><td class="label">jsFiddle URL:</td><td><a class="gist-jsfiddle-link" href="'+fiddle_link()+'">'+fiddle_link()+'</td></tr>');
}
function fiddle_link(){
return "http://jsfiddle.net/gh/gist/jquery/1.6" + location.pathname;
}
if(gist_is_a_fiddle()) insert_fiddle_link();
});
|
Update fetch service to use new API | <?php
namespace Guttmann\NautCli\Service;
use GuzzleHttp\Client;
class FetchLatestService
{
public function fetch(Client $client, $instance)
{
$response = $client->post('/naut/project/' . $instance . '/git/fetches');
$jsonResponse = json_decode($response->getBody()->getContents(), true);
$statusHref = $jsonResponse['data']['links']['self'];
echo 'Queued';
do {
$response = $client->get($statusHref);
$jsonResponse = json_decode($response->getBody()->getContents(), true);
$status = $jsonResponse['data']['attributes']['status'];
echo '.';
sleep(1);
} while ($status == 'Queued');
echo PHP_EOL . 'Running';
do {
$response = $client->get($statusHref);
$jsonResponse = json_decode($response->getBody()->getContents(), true);
$status = $jsonResponse['data']['attributes']['status'];
echo '.';
sleep(1);
} while ($status == 'Running');
echo PHP_EOL . 'Fetch complete.' . PHP_EOL;
}
} | <?php
namespace Guttmann\NautCli\Service;
use GuzzleHttp\Client;
class FetchLatestService
{
public function fetch(Client $client, $instance)
{
$response = $client->post('/naut/api/' . $instance . '/fetch');
$jsonResponse = json_decode($response->getBody()->getContents(), true);
$statusHref = $jsonResponse['href'];
echo 'Queued';
do {
$response = $client->get($statusHref);
$jsonResponse = json_decode($response->getBody()->getContents(), true);
$status = $jsonResponse['status'];
echo '.';
sleep(1);
} while ($status == 'Queued');
echo PHP_EOL . 'Running';
do {
$response = $client->get($statusHref);
$jsonResponse = json_decode($response->getBody()->getContents(), true);
$status = $jsonResponse['status'];
echo '.';
sleep(1);
} while ($status == 'Running');
echo PHP_EOL . 'Fetch complete.' . PHP_EOL;
}
} |
Check that the permission migrations work | import pytest
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from guardian.shortcuts import get_perms
from grandchallenge.workstations.models import Workstation
from tests.factories import UserFactory
@pytest.mark.django_db(transaction=True)
def test_workstation_group_migration():
executor = MigrationExecutor(connection)
app = "workstations"
migrate_from = [(app, "0001_initial")]
migrate_to = [(app, "0004_auto_20190813_1302")]
executor.migrate(migrate_from)
old_apps = executor.loader.project_state(migrate_from).apps
user = UserFactory()
OldWorkstation = old_apps.get_model(app, "Workstation")
old_ws = OldWorkstation.objects.create(title="foo")
assert not hasattr(old_ws, "editors_group")
assert not hasattr(old_ws, "users_group")
# Reload
executor.loader.build_graph()
# Migrate forwards
executor.migrate(migrate_to)
new_ws = Workstation.objects.get(title="foo")
new_ws.add_user(user=user)
assert new_ws.editors_group
assert new_ws.users_group
assert new_ws.slug == old_ws.slug
assert new_ws.title == old_ws.title
assert "view_workstation" in get_perms(user, new_ws)
| import pytest
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
@pytest.mark.django_db(transaction=True)
def test_workstation_group_migration():
executor = MigrationExecutor(connection)
app = "workstations"
migrate_from = [(app, "0001_initial")]
migrate_to = [(app, "0004_auto_20190813_1302")]
executor.migrate(migrate_from)
old_apps = executor.loader.project_state(migrate_from).apps
Workstation = old_apps.get_model(app, "Workstation")
old_ws = Workstation.objects.create(title="foo")
assert not hasattr(old_ws, "editors_group")
assert not hasattr(old_ws, "users_group")
# Reload
executor.loader.build_graph()
# Migrate forwards
executor.migrate(migrate_to)
new_apps = executor.loader.project_state(migrate_to).apps
Workstation = new_apps.get_model(app, "Workstation")
new_ws = Workstation.objects.get(title="foo")
assert new_ws.editors_group
assert new_ws.users_group
assert new_ws.slug == old_ws.slug
assert new_ws.title == old_ws.title
|
Fix urlencode in webhook url | import urllib.parse
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
from django.core.signing import TimestampSigner
class BaseEngine:
def __init__(self):
self.signer = TimestampSigner()
def get_webhook_url(self):
return "{}://{}{}?token={}".format(
"https",
get_current_site(None).domain,
reverse("virus_scan:webhook"),
urllib.parse.quote(self.signer.sign(self.name)),
)
def send_scan(self, this_file, filename):
raise NotImplementedError(
"Provide 'send' in {name}".format(name=self.__class__.__name__)
)
def receive_scan(self, engine_id):
raise NotImplementedError(
"Provide 'receive_scan' in {name}".format(name=self.__class__.__name__)
)
| from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
from django.core.signing import TimestampSigner
class BaseEngine:
def __init__(self):
self.signer = TimestampSigner()
def get_webhook_url(self):
return "{}://{}{}?token={}".format(
"https",
get_current_site(None).domain,
reverse("virus_scan:webhook"),
self.signer.sign(self.name),
)
def send_scan(self, this_file, filename):
raise NotImplementedError(
"Provide 'send' in {name}".format(name=self.__class__.__name__)
)
def receive_scan(self, engine_id):
raise NotImplementedError(
"Provide 'receive_scan' in {name}".format(name=self.__class__.__name__)
)
|
Change calc mode to mode text function name | var mode = 0; //primary
function mode_text() {
var modes = ["primary", "secondary", "tertiary"];
return modes[mode];
}
function send_data() {
$.ajax({
url: "calculate/"+primary+"/"+secondary+"/"+tertiary,
context: document.body,
type: "post",
beforeSend :function() {
//loading
}
}).done(function(data) {
});
}
$(function() {
$(".add").button();
$(".edit").button();
$(".delete").button().click(function() {
var res = confirm("Are you sure you want to delete this item?");
if (res)
window.location.href=$(this).attr('href');
else
return false;
});
$(".view").button();
$(".submit").button();
$("#ingredients_table table").tablesorter();
$("#effects_table table").tablesorter();
$("#calc_ingredients tbody").find('tr').each(function(){
$(this).click(function(){
$('#'+mode_text()).html($(this).text());
send_data();
});
});
$("#primary").click(function(){
$(this).text('--');
mode = 0;
});
$("#secondary").click(function(){
$(this).text('--');
mode = 1;
});
$("#tertiary").click(function(){
$(this).text('--');
mode = 2;
});
});
| var mode = 0; //primary
function calc_mode() {
var modes = ["primary", "secondary", "tertiary"];
return modes[mode];
}
function send_data() {
$.ajax({
url: "calculate/"+primary+"/"+secondary+"/"+tertiary,
context: document.body,
type: "post",
beforeSend :function() {
//loading
}
}).done(function(data) {
});
}
$(function() {
$(".add").button();
$(".edit").button();
$(".delete").button().click(function() {
var res = confirm("Are you sure you want to delete this item?");
if (res)
window.location.href=$(this).attr('href');
else
return false;
});
$(".view").button();
$(".submit").button();
$("#ingredients_table table").tablesorter();
$("#effects_table table").tablesorter();
$("#calc_ingredients tbody").find('tr').each(function(){
$(this).click(function(){
$('#'+calc_mode()).html($(this).text());
send_data();
});
});
$("#primary").click(function(){
$(this).text('--');
mode = 0;
});
$("#secondary").click(function(){
$(this).text('--');
mode = 1;
});
$("#tertiary").click(function(){
$(this).text('--');
mode = 2;
});
});
|
Add missing reader telephone column title | <table class="table table-striped">
<thead>
<tr>
<th>
<?php echo 'Identyfikator' . Html::anchor(Uri::update_query_string(array('by' => 'id')), '', array('class' => 'glyphicon glyphicon-sort')); ?>
</th>
<th>
<?php echo 'Imię i nazwisko' . Html::anchor(Uri::update_query_string(array('by' => 'name')), '', array('class' => 'glyphicon glyphicon-sort')); ?>
</th>
<th>
Telefon
</th>
</tr>
</thead>
<tbody>
<?php foreach ($readers as $reader) {
?>
<tr>
<td><?php echo $reader->id; ?></td>
<td>
<a href="info/<?php echo $reader->id . $current_view?>">
<?php
echo $reader->name;
if (isset($reader->birth_date) && ($reader->birth_date != "")) {
echo ' (' . $reader->birth_date. ')';
}
?></a></td>
<td><?php echo $reader->phone; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="text-center"><?php echo html_entity_decode($pagination); ?></div>
| <table class="table table-striped">
<thead>
<tr>
<th>
<?php echo 'Identyfikator ' . Html::anchor(Uri::update_query_string(array('by' => 'id')), '', array('class' => 'glyphicon glyphicon-sort')); ?>
</th>
<th>
<?php echo 'Imię i nazwisko ' . Html::anchor(Uri::update_query_string(array('by' => 'name')), '', array('class' => 'glyphicon glyphicon-sort')); ?>
</th>
</tr>
</thead>
<tbody>
<?php foreach ($readers as $reader) {
?>
<tr>
<td><?php echo $reader->id; ?></td>
<td>
<a href="info/<?php echo $reader->id . $current_view?>">
<?php
echo $reader->name;
if (isset($reader->birth_date) && ($reader->birth_date != "")) {
echo ' (' . $reader->birth_date. ')';
}
?></a></td>
<td><?php echo $reader->phone; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="text-center"><?php echo html_entity_decode($pagination); ?></div>
|
[minor] Make sure we're listing to the right event | 'use strict';
/**
* Minimum viable WebSocket server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var Engine = require('engine.io').Server
, Spark = this.Spark
, primus = this.primus;
this.service = new Engine();
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service.on('connection', function connection(socket) {
var spark = new Spark(
socket.request.headers
, socket.request.connection.address()
, socket.id
);
spark.on('ougoing::end', function end() {
socket.end();
}).on('outgoing::data', function write(data) {
socket.write(data);
});
socket.on('close', spark.emits('end'));
socket.on('data', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('upgrade', function upgrade(req, socket, head) {
this.service.handleUpgrade(req, socket, head);
}).on('request', function request(req, res) {
this.service.handleRequest(req, res);
});
};
| 'use strict';
/**
* Minimum viable WebSocket server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var Engine = require('engine.io').Server
, Spark = this.Spark
, primus = this.primus;
this.service = new Engine();
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service.on('connection', function connection(socket) {
var spark = new Spark(
socket.request.headers
, socket.request.connection.address()
, socket.id
);
spark.on('ougoing::end', function end() {
socket.end();
}).on('outgoing::data', function write(data) {
socket.write(data);
});
socket.on('end', spark.emits('end'));
socket.on('data', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('upgrade', function upgrade(req, socket, head) {
this.service.handleUpgrade(req, socket, head);
}).on('request', function request(req, res) {
this.service.handleRequest(req, res);
});
};
|
Use the COLOR and TINTS constants | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { COLORS, TINTS } from '../../../constants';
const withTheme = theme => WrappedComponent => {
class WithTheme extends PureComponent {
render() {
const { color, size, tint, className, ...others } = this.props;
const classNames = cx(theme[`is-${color}`], theme[`is-${size}`], theme[`is-${tint}`], className);
return <WrappedComponent className={classNames} {...others} />;
}
}
WithTheme.propTypes = {
/** The color of the component */
color: PropTypes.PropTypes.oneOf(COLORS),
/** The size of the component */
size: PropTypes.oneOf(['tiny', 'small', 'medium', 'large', 'fullscreen']),
/** The tint of the component */
tint: PropTypes.oneOf(TINTS),
};
WithTheme.defaultProps = {
color: 'neutral',
size: 'medium',
tint: 'normal',
};
WithTheme.displayName = `WithTheme(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
return WithTheme;
};
export default withTheme;
| import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
const withTheme = theme => WrappedComponent => {
class WithTheme extends PureComponent {
render() {
const { color, size, tint, className, ...others } = this.props;
const classNames = cx(theme[`is-${color}`], theme[`is-${size}`], theme[`is-${tint}`], className);
return <WrappedComponent className={classNames} {...others} />;
}
}
WithTheme.propTypes = {
/** The color of the component */
color: PropTypes.PropTypes.oneOf(['aqua', 'gold', 'mint', 'neutral', 'ruby', 'teal', 'violet']),
/** The size of the component */
size: PropTypes.oneOf(['tiny', 'small', 'medium', 'large', 'fullscreen']),
/** The tint of the component */
tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']),
};
WithTheme.defaultProps = {
color: 'neutral',
size: 'medium',
tint: 'normal',
};
WithTheme.displayName = `WithTheme(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
return WithTheme;
};
export default withTheme;
|
Add vaccine reducer blink/start/stop cases | import { VACCINE_ACTIONS } from '../actions/VaccineActions';
const initialState = () => ({
isScanning: false,
scannedSensorAddresses: [],
sendingBlinkTo: '',
});
export const VaccineReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case VACCINE_ACTIONS.BLINK_START: {
const { payload } = action;
const { macAddress } = payload;
return { ...state, sendingBlinkTo: macAddress };
}
case VACCINE_ACTIONS.BLINK_STOP: {
return { ...state, sendingBlinkTo: '' };
}
case VACCINE_ACTIONS.SCAN_START: {
return {
...state,
isScanning: true,
scannedSensorAddresses: [],
};
}
case VACCINE_ACTIONS.SCAN_STOP: {
return {
...state,
isScanning: false,
};
}
case VACCINE_ACTIONS.SENSOR_FOUND: {
const { payload } = action;
const { macAddress } = payload;
const { scannedSensorAddresses = [] } = state;
return {
...state,
scannedSensorAddresses: [...scannedSensorAddresses, macAddress],
};
}
default:
return state;
}
};
| import { VACCINE_ACTIONS } from '../actions/VaccineActions';
const initialState = () => ({
isScanning: false,
scannedSensorAddresses: [],
});
export const VaccineReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case VACCINE_ACTIONS.SCAN_START: {
return {
...state,
isScanning: true,
};
}
case VACCINE_ACTIONS.SCAN_STOP: {
return {
...state,
isScanning: false,
};
}
case VACCINE_ACTIONS.SENSOR_FOUND: {
const { payload } = action;
const { macAddress } = payload;
const { scannedSensorAddresses = [] } = state;
return {
...state,
scannedSensorAddresses: [...scannedSensorAddresses, macAddress],
};
}
default:
return state;
}
};
|
Allow autoupdater to close everything | // @flow
import os from 'os'
import { app, autoUpdater, dialog } from 'electron'
import type { AppManager } from '../AppManager'
const version = app.getVersion()
const platform = `${os.platform()}_${os.arch()}`
const updateURL = `https://chatinder.herokuapp.com/update/${platform}/${version}`
export function updateApp(instance: AppManager) {
autoUpdater.setFeedURL(updateURL)
// Ask the user if update is available
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
let message = `${app.getName()} ${releaseName} is now available. It will be installed the next time you restart the application.`
if (releaseNotes) {
const splitNotes = releaseNotes.split(/[^\r]\n/)
message += '\n\nRelease notes:\n'
splitNotes.forEach(notes => {
message += notes + '\n\n'
})
}
// Ask user to update the app
dialog.showMessageBox(
{
type: 'question',
buttons: ['Install and Relaunch', 'Later'],
defaultId: 0,
message: `A new version of ${app.getName()} has been downloaded`,
detail: message
},
response => {
if (response === 0) {
instance.forceQuit = true
setTimeout(() => autoUpdater.quitAndInstall(), 1)
}
}
)
})
// init for updates
autoUpdater.checkForUpdates()
}
| // @flow
import os from 'os'
import { app, autoUpdater, dialog } from 'electron'
const version = app.getVersion()
const platform = `${os.platform()}_${os.arch()}`
const updateURL = `https://chatinder.herokuapp.com/update/${platform}/${version}`
export function updateApp() {
autoUpdater.setFeedURL(updateURL)
// Ask the user if update is available
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
let message = `${app.getName()} ${releaseName} is now available. It will be installed the next time you restart the application.`
if (releaseNotes) {
const splitNotes = releaseNotes.split(/[^\r]\n/)
message += '\n\nRelease notes:\n'
splitNotes.forEach(notes => {
message += notes + '\n\n'
})
}
// Ask user to update the app
dialog.showMessageBox(
{
type: 'question',
buttons: ['Install and Relaunch', 'Later'],
defaultId: 0,
message: `A new version of ${app.getName()} has been downloaded`,
detail: message
},
response => {
if (response === 0) {
setTimeout(() => autoUpdater.quitAndInstall(), 1)
}
}
)
})
// init for updates
autoUpdater.checkForUpdates()
}
|
Fix bug that meant member details not displaying if no first name had been entered. | /* @flow */
import { FETCHED_MEMBER } from '../../../shared/redux/modules/member.js'
import { mergeAll, converge, unapply, compose, objOf, prop } from 'ramda'
import type { Action, Reducer } from 'redux'
type State = {}
const reducer: Reducer<State, Action> =
(state = { id: 0, address: [], name: '' }, { type, payload }) => {
switch (type) {
case FETCHED_MEMBER:
return converge
( unapply(mergeAll)
, [ compose(objOf('name'), getName)
, compose(objOf('address'), getAddress)
, compose(objOf('id'), prop('id'))
]
)(payload)
default:
return state
}
}
const getName = ({ title, full_name }) => title + ' ' + full_name
const getAddress = (
{ title
, first_name = ''
, last_name = ''
, address1
, address2
, address3
, address4
, county
, postcode
}
) =>
[ `${title} ${(first_name && first_name[0]) || ''} ${last_name}`
, address1
, address2
, address3
, address4
, county
, postcode ]
export default reducer
| /* @flow */
import { FETCHED_MEMBER } from '../../../shared/redux/modules/member.js'
import { mergeAll, converge, unapply, compose, objOf, prop } from 'ramda'
import type { Action, Reducer } from 'redux'
type State = {}
const reducer: Reducer<State, Action> =
(state = { id: 0, address: [], name: '' }, { type, payload }) => {
switch (type) {
case FETCHED_MEMBER:
return converge
( unapply(mergeAll)
, [ compose(objOf('name'), getName)
, compose(objOf('address'), getAddress)
, compose(objOf('id'), prop('id'))
]
)(payload)
default:
return state
}
}
const getName = ({ title, full_name }) => title + ' ' + full_name
const getAddress = (
{ title
, first_name = ''
, last_name = ''
, address1
, address2
, address3
, address4
, county
, postcode
}
) =>
[ `${title} ${first_name[0] || ''} ${last_name}`, address1, address2,
address3, address4, county, postcode ]
export default reducer
|
Fix typo tkrn -> trkn (patch by m krueger)
git-svn-id: c4d2d6f4036cbf3d898a71de5246e4e6216e7677@1083 7decde4b-c250-0410-a0da-51896bc88be6 | package com.googlecode.mp4parser.boxes.apple;
import java.nio.ByteBuffer;
/**
* Created by sannies on 10/15/13.
*/
public class AppleTrackNumberBox extends AppleDataBox {
public AppleTrackNumberBox() {
super("trkn", 0);
}
int a;
int b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
protected byte[] writeData() {
ByteBuffer bb = ByteBuffer.allocate(8);
bb.putInt(a);
bb.putInt(b);
return bb.array();
}
@Override
protected void parseData(ByteBuffer data) {
a = data.getInt();
b = data.getInt();
}
@Override
protected int getDataLength() {
return 8;
}
}
| package com.googlecode.mp4parser.boxes.apple;
import java.nio.ByteBuffer;
/**
* Created by sannies on 10/15/13.
*/
public class AppleTrackNumberBox extends AppleDataBox {
public AppleTrackNumberBox() {
super("tkrn", 0);
}
int a;
int b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
protected byte[] writeData() {
ByteBuffer bb = ByteBuffer.allocate(8);
bb.putInt(a);
bb.putInt(b);
return bb.array();
}
@Override
protected void parseData(ByteBuffer data) {
a = data.getInt();
b = data.getInt();
}
@Override
protected int getDataLength() {
return 8;
}
}
|
Add scaled sphere to check that works | package main
import "trace"
const (
imageW = 640
imageH = 480
)
func main() {
c := trace.NewContext(imageW, imageH)
o2w := trace.NewM44()
o2w.Translate(trace.NewV3(-2, 0, -5))/*.scale(trace.NewV3(1.0, 2.0, 1.0))*/
c.AddPrimitive(trace.NewSphere(o2w))
o2w = trace.NewM44()
o2w.Translate(trace.NewV3(0, 0, -5)).Scale(trace.NewV3(1, 2, 1))
c.AddPrimitive(trace.NewSphere(o2w))
o2w = trace.NewM44()
o2w.Translate(trace.NewV3(2, 0, -5))
c.AddPrimitive(trace.NewTriangle(o2w))
image := trace.Render(c)
trace.WriteImageToPPM(image, "render")
}
| package main
import "trace"
const (
imageW = 640
imageH = 480
)
func createRandomImage() [][]trace.Color {
image := make([][]trace.Color, imageH)
for i := range image {
image[i] = make([]trace.Color, imageW)
for j := range image[i] {
image[i][j].R = float64(i) / float64(imageH)
image[i][j].G = float64(j) / float64(imageW)
image[i][j].B = 0.0
//log.Printf("%d %d %+v | ", i, j, image[i][j])
}
//log.Printf("\n")
}
return image
}
func main() {
c := trace.NewContext(imageW, imageH)
o2w := trace.NewM44()
o2w.Translate(trace.NewV3(-2, 0, -5))/*.scale(trace.NewV3(1.0, 2.0, 1.0))*/
c.AddPrimitive(trace.NewSphere(o2w))
o2w = trace.NewM44()
o2w.Translate(trace.NewV3(2, 0, -5))
c.AddPrimitive(trace.NewTriangle(o2w))
image := trace.Render(c)
//image := createRandomImage()
trace.WriteImageToPPM(image, "render")
}
|
Fix validation issue on events | var mongoose = require('mongoose');
var schema = require('validate');
var Event = mongoose.model('Event', {
name: String,
start: Date,
end: Date,
group: {type: String, enum: ['attendee', 'staff', 'admin'], default: 'attendee'},
notify: {type: Boolean, default: true}
});
var validate = function (event) {
var test = schema({
name: {
type: 'string',
required: true,
message: 'You must provide a name for the event.'
},
start: {
type: 'date',
required: true,
message: 'You must provide a start time.'
},
end: {
type: 'date',
required: true,
message: 'You must provide an end time.'
},
group: {
type: 'string'
},
notify: {
type: 'boolean'
}
}, {typecast: true});
return test.validate(event);
};
module.exports = Event;
module.exports.validate = validate; | var mongoose = require('mongoose');
var schema = require('validate');
var Event = mongoose.model('Event', {
name: String,
start: Date,
end: Date,
group: String,
notify: Boolean
});
var validate = function (event) {
var test = schema({
name: {
type: 'string',
required: true,
message: 'You must provide a name for the event.'
},
start: {
type: 'date',
required: true,
message: 'You must provide a start time.'
},
end: {
type: 'date',
required: true,
message: 'You must provide an end time.'
},
group: {
type: 'string',
required: false
},
notify: {
type: 'boolean',
required: false
}
}, {typecast: true});
return test.validate(event);
};
module.exports = Event;
module.exports.validate = validate; |
Convert 'comports' to a list before getting its length (the value may be
a generator). | from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import io
import struct
import unittest
import threading
import time
import serial
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestIsCorrectVariant(unittest.TestCase):
def test_isMbVariant(self):
self.assertTrue (serial.__version__.index('mb2') > 0 )
def test_hasScanEndpoints(self):
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
def test_variantDoesBlocking(self):
#grab a port
#try to grab it again
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
print('autograbbing a port')
comports = lp.comports()
if( len(list(comports)) < 1):
print('no comport availabe')
self.assertFalse(True, "no comports, cannot execute test")
portname = comports[-1][0] #item 0 in last comport as the port to test
print("Connecting to serial" + portname)
s = serial.Serial(portname)
with self.assertRaises(serial.SerialException) as ex:
s = serial.Serial(portname)
if __name__ == '__main__':
unittest.main()
| from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import io
import struct
import unittest
import threading
import time
import serial
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestIsCorrectVariant(unittest.TestCase):
def test_isMbVariant(self):
self.assertTrue (serial.__version__.index('mb2') > 0 )
def test_hasScanEndpoints(self):
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
def test_variantDoesBlocking(self):
#grab a port
#try to grab it again
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
print('autograbbing a port')
comports = lp.comports()
if( len(comports) < 1):
print('no comport availabe')
self.assertFalse(True, "no comports, cannot execute test")
portname = comports[-1][0] #item 0 in last comport as the port to test
print("Connecting to serial" + portname)
s = serial.Serial(portname)
with self.assertRaises(serial.SerialException) as ex:
s = serial.Serial(portname)
if __name__ == '__main__':
unittest.main()
|
Enable sort keys in json dumps to make sure json is stable | from lxml import objectify, etree
import simplejson as json
from converter.nsl.nsl_converter import NslConverter
from converter.nsl.other.nsl_other_converter import NslOtherConverter
import sys
xml = open("SEnsl_ssi.xml")
xml_string = xml.read()
xml_obj = objectify.fromstring(xml_string)
nsl_other_xml_string = open("SEnsl_other.xml").read()
nsl_other_xml_obj = objectify.fromstring(nsl_other_xml_string)
nsl_dict = NslConverter().convert(xml_obj)
nsl_other_dict = NslOtherConverter().convert(nsl_other_xml_obj)
for item in nsl_dict:
filename = ""
for code in item["substance_codes"]:
if code["code_system"] == "SENSLIDSENSL":
filename = code["code"]
break
with open('json/' + filename + ".json", 'w') as outfile:
json.dump(item, outfile, sort_keys=True)
for item in nsl_other_dict:
with open("json/other/" + item["se_nsl_id"] + ".json", "w") as outfile:
json.dump(item, outfile, sort_keys=True)
| from lxml import objectify, etree
import simplejson as json
from converter.nsl.nsl_converter import NslConverter
from converter.nsl.other.nsl_other_converter import NslOtherConverter
import sys
xml = open("SEnsl_ssi.xml")
xml_string = xml.read()
xml_obj = objectify.fromstring(xml_string)
nsl_other_xml_string = open("SEnsl_other.xml").read()
nsl_other_xml_obj = objectify.fromstring(nsl_other_xml_string)
nsl_dict = NslConverter().convert(xml_obj)
nsl_other_dict = NslOtherConverter().convert(nsl_other_xml_obj)
for item in nsl_dict:
filename = ""
for code in item["substance_codes"]:
if code["code_system"] == "SENSLIDSENSL":
filename = code["code"]
break
with open('json/' + filename + ".json", 'w') as outfile:
json.dump(item, outfile)
for item in nsl_other_dict:
with open("json/other/" + item["se_nsl_id"] + ".json", "w") as outfile:
json.dump(item, outfile)
|
Allow Rdio to use default signature handling | from werkzeug.urls import url_decode
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
# URLs to interact with the API
request_token_url = 'http://api.rdio.com/oauth/request_token'
authorize_url = None # Provided when the request token is granted
access_token_url = 'http://api.rdio.com/oauth/access_token'
api_domain = 'api.rdio.com'
available_permissions = [
(None, 'access and manage your music'),
]
https = False
def parse_token(self, content):
# Override standard token request to also get the authorization URL
data = url_decode(content)
if 'login_url' in data:
self.authorize_url = data['login_url']
return super(Rdio, self).parse_token(content)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/1/', method='POST', data={
'method': 'currentUser',
})
return unicode(r.json[u'result'][u'key'])
| from werkzeug.urls import url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY
import foauth.providers
class Rdio(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.rdio.com/'
docs_url = 'http://developer.rdio.com/docs/REST/'
category = 'Music'
# URLs to interact with the API
request_token_url = 'http://api.rdio.com/oauth/request_token'
authorize_url = None # Provided when the request token is granted
access_token_url = 'http://api.rdio.com/oauth/access_token'
api_domain = 'api.rdio.com'
available_permissions = [
(None, 'access and manage your music'),
]
https = False
signature_type = SIGNATURE_TYPE_BODY
def parse_token(self, content):
# Override standard token request to also get the authorization URL
data = url_decode(content)
if 'login_url' in data:
self.authorize_url = data['login_url']
return super(Rdio, self).parse_token(content)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/1/', method='POST', data={
'method': 'currentUser',
})
return unicode(r.json[u'result'][u'key'])
|
Reduce visibility of internal class | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jctools.queues;
import static org.jctools.util.UnsafeLongArrayAccess.*;
abstract class ConcurrentSequencedCircularArrayQueue<E> extends ConcurrentCircularArrayQueue<E>
{
protected final long[] sequenceBuffer;
public ConcurrentSequencedCircularArrayQueue(int capacity)
{
super(capacity);
int actualCapacity = (int) (this.mask + 1);
// pad data on either end with some empty slots. Note that actualCapacity is <= MAX_POW2_INT
sequenceBuffer = allocateLongArray(actualCapacity);
for (long i = 0; i < actualCapacity; i++)
{
soLongElement(sequenceBuffer, calcCircularLongElementOffset(i, mask), i);
}
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jctools.queues;
import static org.jctools.util.UnsafeLongArrayAccess.*;
public abstract class ConcurrentSequencedCircularArrayQueue<E> extends ConcurrentCircularArrayQueue<E>
{
protected final long[] sequenceBuffer;
public ConcurrentSequencedCircularArrayQueue(int capacity)
{
super(capacity);
int actualCapacity = (int) (this.mask + 1);
// pad data on either end with some empty slots. Note that actualCapacity is <= MAX_POW2_INT
sequenceBuffer = allocateLongArray(actualCapacity);
for (long i = 0; i < actualCapacity; i++)
{
soLongElement(sequenceBuffer, calcCircularLongElementOffset(i, mask), i);
}
}
}
|
Fix: Make compatible with Matt's additions | /* global guardianAPIKey, createUrl, fetchAPI, fromGuardianToStandardArticleFormat */
const buildArticleNode = template => article => {
template.querySelector('h2').textContent = article.title;
template.querySelector('p').innerHTML = article.tagline;
return document.importNode(template, true);
};
function buildArticleNodes(articles) {
const articleTemplate = document.getElementById('ArticleTemplate').content;
return articles.map(buildArticleNode(articleTemplate));
}
function displayArticleNodes(articleNodes) {
const guardianContent = document.getElementById('GuardianContent');
articleNodes.forEach(node => guardianContent.appendChild(node));
}
function main() {
const query = {
q: 'brexit',
'show-fields': 'standfirst',
'from-date': '2016-06-20',
'to-date': '2016-06-20',
pageSize: '50',
'order-by': 'newest',
'api-key': guardianAPIKey,
};
const guardianUrl = createUrl('http://content.guardianapis.com/', ['search'], query);
const trace = data => { console.log(data); return data; };
fetchAPI(guardianUrl)
.then(trace)
.then(fromGuardianToStandardArticleFormat)
.then(buildArticleNodes)
.then(displayArticleNodes);
}
main();
| /* global guardianAPIKey, createUrl, fetchAPI, fromGuardianToStandardArticleFormat */
const buildArticleNode = template => article => {
template.querySelector('h2').textContent = article.title;
template.querySelector('p').innerHTML = article.tagline;
return document.importNode(template, true);
};
function buildArticleNodes(articles) {
const articleTemplate = document.getElementById('ArticleTemplate').content;
return articles.map(buildArticleNode(articleTemplate));
}
function displayArticleNodes(articleNodes) {
const guardianContent = document.getElementById('GuardianContent');
articleNodes.forEach(node => guardianContent.appendChild(node));
}
function main() {
const query = {
q: 'brexit',
'show-fields': 'standfirst',
'api-key': guardianAPIKey,
};
const guardianUrl = createUrl('http://content.guardianapis.com/', ['search'], query);
const trace = data => { console.log(data); return data; };
fetchAPI(guardianUrl)
.then(trace)
.then(fromGuardianToStandardArticleFormat)
.then(buildArticleNodes)
.then(displayArticleNodes);
}
main();
|
Fix bug - error page could display message now | '''Copyright(C): Leaf Johnson 2011
This file is part of makeclub.
makeclub is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
makeclub is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with makeclub. If not, see <http://www.gnu.org/licenses/>.
'''
from google.appengine.ext.webapp import template
import os.path
tplt = os.path.join(os.path.dirname(__file__), '../templates/default/errors.html')
def renderErrorPage(msg, redirect=''):
vars = dict(message=msg, redirect=redirect)
return template.render(tplt, vars)
def errorPage(msg, redirect, response):
response.out.write (renderErrorPage(msg, redirect))
return False | '''Copyright(C): Leaf Johnson 2011
This file is part of makeclub.
makeclub is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
makeclub is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with makeclub. If not, see <http://www.gnu.org/licenses/>.
'''
from google.appengine.ext.webapp import template
import os.path
tplt = os.path.join(os.path.dirname(__file__), '../templates/default/errors.html')
def renderErrorPage(msg, redirect=''):
vars = dict(msg=msg, redirect=redirect)
return template.render(tplt, vars)
def errorPage(msg, redirect, response):
response.out.write (renderErrorPage(msg, redirect))
return False |
Fix active class not displaying on recent ember versions | import { reads, and } from '@ember/object/computed';
import LinkComponent from '@ember/routing/link-component';
import layout from '../templates/components/paper-link'
import { computed } from '@ember/object';
import FocusableMixin from 'ember-paper/mixins/focusable-mixin';
import ColorMixin from 'ember-paper/mixins/color-mixin';
import ProxiableMixin from 'ember-paper/mixins/proxiable-mixin';
export default LinkComponent.extend(FocusableMixin, ColorMixin, ProxiableMixin, {
layout,
// Add needed paper-button properties
classNames: ['md-default-theme', 'md-button', 'paper-link'],
raised: false,
iconButton: false,
fab: reads('mini'), // circular button
mini: false,
// For raised buttons: toggle disabled when button is active
disabled: and('raised', 'active'),
classNameBindings: [
'raised:md-raised',
'iconButton:md-icon-button',
'fab:md-fab',
'mini:md-mini'
],
// FocusableMixin overrides active so set back to link-to's active
active: computed('activeClass', '_active', function() {
return this._active ? this.activeClass : false;
}),
// FocusableMixin overrides to prevent changing 'active' property
down() {
this.set('pressed', true);
},
up() {
this.set('pressed', false);
}
});
| import { reads, and } from '@ember/object/computed';
import LinkComponent from '@ember/routing/link-component';
import layout from '../templates/components/paper-link'
import FocusableMixin from 'ember-paper/mixins/focusable-mixin';
import ColorMixin from 'ember-paper/mixins/color-mixin';
import ProxiableMixin from 'ember-paper/mixins/proxiable-mixin';
export default LinkComponent.extend(FocusableMixin, ColorMixin, ProxiableMixin, {
layout,
// Add needed paper-button properties
classNames: ['md-default-theme', 'md-button', 'paper-link'],
raised: false,
iconButton: false,
fab: reads('mini'), // circular button
mini: false,
// For raised buttons: toggle disabled when button is active
disabled: and('raised', 'active'),
classNameBindings: [
'raised:md-raised',
'iconButton:md-icon-button',
'fab:md-fab',
'mini:md-mini'
],
// FocusableMixin overrides active so set back to link-to's active
active: LinkComponent.active,
// FocusableMixin overrides to prevent changing 'active' property
down() {
this.set('pressed', true);
},
up() {
this.set('pressed', false);
}
});
|
Implement __getattr__ to reduce code | class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def __getattr__(self, on_planet):
if on_planet in SpaceAge.YEARS:
return lambda: round(self.years/SpaceAge.YEARS[on_planet], 2)
else:
raise AttributeError
| class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
return round(self.years/0.6151976, 2)
def on_mars(self):
return round(self.years/1.8808158, 2)
def on_jupiter(self):
return round(self.years/11.862615, 2)
def on_saturn(self):
return round(self.years/29.447498, 2)
def on_uranus(self):
return round(self.years/84.016846, 2)
def on_neptune(self):
return round(self.years/164.79132, 2)
|
Test that RawMeasurement timestamps never change. | package com.openxc.remote;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RawMeasurementTest {
RawMeasurement measurement;
@Test
public void testValue() {
measurement = new RawMeasurement(new Double(42.0));
}
@Test
public void testValidity() {
measurement = new RawMeasurement(new Double(42));
assertTrue(measurement.isValid());
measurement = new RawMeasurement();
assertFalse(measurement.isValid());
}
@Test
public void testHasAge() {
measurement = new RawMeasurement(new Double(42));
assertTrue(measurement.getTimestamp() > 0);
}
@Test
public void testStopsAging() {
measurement = new RawMeasurement(new Double(42));
double timestamp = measurement.getTimestamp();
pause(10);
assertEquals(timestamp, measurement.getTimestamp(), 0);
}
private void pause(int millis) {
try {
Thread.sleep(millis);
} catch(InterruptedException e) {}
}
}
| package com.openxc.remote;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class RawMeasurementTest {
RawMeasurement measurement;
@Test
public void testValue() {
measurement = new RawMeasurement(new Double(42.0));
}
@Test
public void testValidity() {
measurement = new RawMeasurement(new Double(42));
assertTrue(measurement.isValid());
measurement = new RawMeasurement();
assertFalse(measurement.isValid());
}
@Test
public void testHasAge() {
measurement = new RawMeasurement(new Double(42));
assertTrue(measurement.getTimestamp() > 0);
}
}
|
Call advanceTurn al para que el juego avance luego de mover los tokens | "use strict";
$('#start').click(function() {
let namePlayer1 = $('#p1name').val(),
namePlayer2 = $('#p2name').val();
if (namePlayer1.length === 0 || namePlayer2.length === 0) {
alert("You must enter your names!");
return;
}
let tokenPlayer1 = $('#tokens1 input').val(),
tokenPlayer2 = $('#tokens2 input').val();
if (tokenPlayer1 === tokenPlayer2) {
alert("You must choose different tokens!");
return;
}
selectToken(tokenPlayer1, namePlayer1);
selectToken(tokenPlayer2, namePlayer2);
advanceTurn();
//hideStartModal();
//showDiceModal();
//setupBoard();
});
$('#dice').click(function() {
let dice = rollDice();
// displayDiceResults(dice.dice1, dice.dice2);
// moveToken(currentPlayer, dice.dice1, dice.dice2);
advanceTurn();
}); | "use strict";
$('#start').click(function() {
let namePlayer1 = $('#p1name').val(),
namePlayer2 = $('#p2name').val();
if (namePlayer1.length === 0 || namePlayer2.length === 0) {
alert("You must enter your names!");
return;
}
let tokenPlayer1 = $('#tokens1 input').val(),
tokenPlayer2 = $('#tokens2 input').val();
if (tokenPlayer1 === tokenPlayer2) {
alert("You must choose different tokens!");
return;
}
selectToken(tokenPlayer1, namePlayer1);
selectToken(tokenPlayer2, namePlayer2);
advanceTurn();
//hideStartModal();
//showDiceModal();
//setupBoard();
});
$('#dice').click(function() {
let dice = rollDice();
// displayDiceResults(dice.dice1, dice.dice2);
// moveToken(currentPlayer, dice.dice1, dice.dice2);
}); |
Add tasks for asset moving on build | var gulp = require('gulp');
var webpack = require('webpack');
var clientConfig = require('./config/webpack.prod.client.js')
var serverConfig = require('./config/webpack.prod.server.js')
gulp.task('bundle-client', function(done) {
webpack( clientConfig ).run(onBundle(done))
});
gulp.task('bundle-server', function(done) {
webpack( serverConfig ).run(onBundle(done))
});
gulp.task('move-index', function() {
gulp.src('./src/index.html').pipe(gulp.dest('./app'))
});
gulp.task('move-assets', ['move-index'], function() {
gulp.src('./src/assets/**/*', {base: './src'}).pipe(gulp.dest('./app/'))
});
gulp.task('bundle', ['bundle-client', 'bundle-server']);
gulp.task('build', ['bundle', 'move-assets'])
function onBundle(done) {
return function(err, stats) {
if (err) console.log('Error', err);
else console.log(stats.toString());
done()
}
}
| var gulp = require('gulp');
var webpack = require('webpack');
var clientConfig = require('./config/webpack.prod.client.js')
var serverConfig = require('./config/webpack.prod.server.js')
gulp.task('bundle-client', function(done) {
webpack( clientConfig ).run(onBundle(done))
});
gulp.task('bundle-server', function(done) {
webpack( serverConfig ).run(onBundle(done))
});
gulp.task('copy-html', function() {
gulp.src('./src/index.html').pipe(gulp.dest('./app'))
});
gulp.task('bundle', ['bundle-client', 'bundle-server', 'copy-html']);
function onBundle(done) {
return function(err, stats) {
if (err) console.log('Error', err);
else console.log(stats.toString());
done()
}
}
|
Add public/js/app.js to watched source files | 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var config = {
js: ['src/**/*.js', 'public/js/app.js']
};
gulp.task('js', function () {
// set up the browserify instance on a task basis
var b = browserify({
entries: './public/js/app.js',
debug: true
});
return b.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});
gulp.task('develop', ['js'], function() {
gulp.watch(config.js, ['js']);
});
| 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var config = {
js: ['src/**/*.js']
};
gulp.task('js', function () {
// set up the browserify instance on a task basis
var b = browserify({
entries: './public/js/app.js',
debug: true
});
return b.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});
gulp.task('develop', ['js'], function() {
gulp.watch(config.js, ['js']);
});
|
Add event execution, allow integers as event name | from operator import isCallable
class Events(object):
def __init__(self):
self._events_ = {}
def addEvent(self, eventname, func):
if not isCallable(func):
raise RuntimeError("func argument must be a function!")
elif not isinstance(eventname, (basestring, int)):
raise RuntimeError("Event name must be a string!")
elif eventname in self._events_:
raise RuntimeError("Event name already exists!")
else:
self._events_[eventname] = func
def execEvent(self, eventname, *args, **kwargs):
if eventname not in self._events_:
raise RuntimeError("No such Event name '{0}'".format(eventname))
else:
self._events_[eventname](*args, **kwargs) | from operator import isCallable
class Events(object):
def __init__(self):
self._events_ = {}
def addEvent(self, eventname, func):
if not isCallable(func):
raise RuntimeError("func argument must be a function!")
elif not isinstance(eventname, basestring):
raise RuntimeError("Event name must be a string!")
elif eventname in self._events_:
raise RuntimeError("Event name already exists!")
else:
self._events_[eventname] = func
def execEvent(self, eventname, *args, **kwargs):
if eventname not in self._events_:
raise RuntimeError("No such Event name '{0}'".format(eventname)) |
Use DateTimeInterface and null coalescing | <?php
/**
* DateEnablement.php
*
* @copyright 2016 George D. Cooksey, III
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
namespace texdc\range;
use DateTimeInterface;
/**
* A date-based enablement.
*
* @author George D. Cooksey, III
*/
final class DateEnablement implements EnablementInterface
{
/**
* @var DateRangeInterface
*/
private $dateRange;
/**
* @param DateRangeInterface $aDateRange
*/
public function __construct(DateRangeInterface $aDateRange)
{
$this->dateRange = $aDateRange;
}
/**
* @param DateTimeInterface|null $onDate optional, will default to 'now'
* @return bool
*/
public function isEnabled(DateTimeInterface $onDate = null) : bool
{
return $this->dateRange->includes($onDate ?? new DateTime);
}
}
| <?php
/**
* DateEnablement.php
*
* @copyright 2016 George D. Cooksey, III
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
namespace texdc\range;
use DateTime;
/**
* A date-based enablement.
*
* @author George D. Cooksey, III
*/
final class DateEnablement implements EnablementInterface
{
/**
* @var DateRangeInterface
*/
private $dateRange;
/**
* @param DateRangeInterface $aDateRange
*/
public function __construct(DateRangeInterface $aDateRange)
{
$this->dateRange = $aDateRange;
}
/**
* @param DateTime|null $onDate optional, will default to 'now'
* @return bool
*/
public function isEnabled(DateTime $onDate = null) : bool
{
$onDate = $onDate ?: new DateTime;
return $this->dateRange->includes($onDate);
}
}
|
Test X509Certificate for invalid constructor argument | <?php
namespace SslurpTest;
use PHPUnit_Framework_TestCase as TestCase;
use Sslurp\X509Certificate;
class X509CertificateTest extends TestCase
{
public function testConsructorSupoprtsMultipleInputTypesAndCanGenerateProperKeyPin()
{
$certPath = __DIR__ . '/_files/mxr.mozilla.org.pem';
$certString = file_get_contents($certPath);
$certResource = openssl_x509_read($certString);
$expectedPin = '47cac6d8f2c2363675e6f433970f27523824d0ec';
$cert = new X509Certificate($certPath);
$this->assertSame($cert->getPin(), $expectedPin);
$cert = new X509Certificate($certString);
$this->assertSame($cert->getPin(), $expectedPin);
$cert = new X509Certificate($certResource);
$this->assertSame($cert->getPin(), $expectedPin);
}
public function testInvalidConstructorArgumentThrowsException()
{
$this->setExpectedException('InvalidArgumentException');
$cert = new X509Certificate(123);
}
}
| <?php
namespace SslurpTest;
use PHPUnit_Framework_TestCase as TestCase;
use Sslurp\X509Certificate;
class X509CertificateTest extends TestCase
{
public function testConsructorSupoprtsMultipleInputTypesAndCanGenerateProperKeyPin()
{
$certPath = __DIR__ . '/_files/mxr.mozilla.org.pem';
$certString = file_get_contents($certPath);
$certResource = openssl_x509_read($certString);
$expectedPin = '47cac6d8f2c2363675e6f433970f27523824d0ec';
$cert = new X509Certificate($certPath);
$this->assertSame($cert->getPin(), $expectedPin);
$cert = new X509Certificate($certString);
$this->assertSame($cert->getPin(), $expectedPin);
$cert = new X509Certificate($certResource);
$this->assertSame($cert->getPin(), $expectedPin);
}
}
|
Make load methods call proper ajax urls | var najax = require("najax");
var Promise = require('promise');
var Snowflake = function Snowflake(snowflakeUrl) {
var instance = this;
this.snowflakeUrl = snowflakeUrl;
this.platforms = {};
this.games = {};
this.loadGames = function () {
return this.ajax('Core', 'Game.GetAllGames').then(function (response) {
instance.games = JSON.parse(response);
}).catch(function (fail) {
console.log(fail);
});
};
this.loadPlatforms = function () {
return this.ajax('Core', 'Platform.GetAllPlatforms').then(function (response) {
instance.platforms = JSON.parse(response);
}).catch(function (fail) {
console.log(fail);
});
};
this.ajax = function (namespace, methodname) {
return Promise.resolve(najax(snowflakeUrl + '/' + namespace + '/' + methodname));
}
}
exports.Snowflake = Snowflake; | var najax = require("najax");
var Promise = require('promise');
var Snowflake = function Snowflake(snowflakeUrl) {
var instance = this;
this.snowflakeUrl = snowflakeUrl;
this.platforms = {};
this.games = {};
this.loadGames = function () {
return this.ajax('', '').then(function (response) {
instance.games = response;
}).catch(function (fail) {
console.log(fail);
});
};
this.loadPlatforms = function () {
};
this.ajax = function (namespace, methodname) {
return Promise.resolve(najax('http://www.google.com'));
}
}
exports.Snowflake = Snowflake; |
Rename variables inside the graphs.hasCycle function in order to improve readability | // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package graphs
type state byte
const (
undiscovered state = iota
discovered
processed
)
// Vertex represents a Graph vertex with its connection edges to another vertices.
type Vertex struct {
label string
state state // Default is undiscovered.
edges []*Vertex
}
func hasCycle(curr, prev *Vertex) bool {
if curr.state == discovered { // Base case.
return true
}
curr.state = discovered // In process.
for _, next := range curr.edges {
if next != prev && next.state != processed && hasCycle(next, curr) {
return true
}
}
curr.state = processed // Done.
return false
}
// IsMinimallyConnected returns true if graph is minimally connected.
// The time complexity is O(v+e) where v is the number of vertices and e is the
// number of edges. However, if given graph is an undirected graph with no cycles
// then the time complexity is O(v). The O(v) additional space is needed.
func IsMinimallyConnected(graph []*Vertex) bool {
if len(graph) == 0 {
return true
}
return !hasCycle(graph[0], nil)
}
| // Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package graphs
type state byte
const (
undiscovered state = iota
discovered
processed
)
// Vertex represents a Graph vertex with its connection edges to another vertices.
type Vertex struct {
label string
state state // Default is undiscovered.
edges []*Vertex
}
func hasCycle(c, p *Vertex) bool {
if c.state == discovered { // Base case.
return true
}
c.state = discovered // In process.
for _, n := range c.edges {
if n != p && n.state != processed && hasCycle(n, c) {
return true
}
}
c.state = processed // Done.
return false
}
// IsMinimallyConnected returns true if graph is minimally connected.
// The time complexity is O(v+e) where v is the number of vertices and e is the
// number of edges. However, if given graph is an undirected graph with no cycles
// then the time complexity is O(v). The O(v) additional space is needed.
func IsMinimallyConnected(graph []*Vertex) bool {
if len(graph) == 0 {
return true
}
return !hasCycle(graph[0], nil)
}
|
Add loading state to hll update lifecycle | import RiakObjectRoute from '../route';
export default RiakObjectRoute.extend({
actions: {
/**
* Adds an element to the HLL list.
* @event addSetElement
* @param {String} item
*/
addElement: function(item) {
let self = this;
let controller = this.get('controller');
let hll = this.currentModel;
let clusterName = hll.get('cluster').get('name');
let bucketTypeName = hll.get('bucketType').get('name');
let bucketName = hll.get('bucket').get('name');
let objectName = hll.get('name');
this.explorer.updateCRDT(hll, { add: item }).then(function() {
controller.set('showLoadingSpinner', true);
return self.explorer.getObject(clusterName, bucketTypeName, bucketName, objectName);
}).then(function() {
return controller.set('showLoadingSpinner', false);
});
}
}
});
| import RiakObjectRoute from '../route';
export default RiakObjectRoute.extend({
actions: {
/**
* Adds an element to the HLL list.
* @event addSetElement
* @param {String} item
*/
addElement: function(item) {
let self = this;
let hll = this.currentModel;
let clusterName = hll.get('cluster').get('name');
let bucketTypeName = hll.get('bucketType').get('name');
let bucketName = hll.get('bucket').get('name');
let objectName = hll.get('name');
this.explorer.updateCRDT(hll, { add: item }).then(function() {
return self.explorer.getObject(clusterName, bucketTypeName, bucketName, objectName);
});
}
}
});
|
Reformat code and optimize imports. | package org.ops4j.pax.web.service.internal.model;
import javax.servlet.Filter;
public class FilterModel extends BasicModel
{
private final Filter m_filter;
private final String[] m_urlPatterns;
private final String[] m_servletNames;
public FilterModel( final Filter filter,
final String[] urlPatterns,
final String[] servletNames,
final ContextModel contextModel )
{
super( contextModel );
if( urlPatterns == null && servletNames == null )
{
throw new IllegalArgumentException(
"Registered filter must have at least one url pattern or servlet mapping"
);
}
m_filter = filter;
m_urlPatterns = urlPatterns;
m_servletNames = servletNames;
}
public Filter getFilter()
{
return m_filter;
}
public String[] getUrlPatterns()
{
return m_urlPatterns;
}
public String[] getServletNames()
{
return m_servletNames;
}
}
| package org.ops4j.pax.web.service.internal.model;
import javax.servlet.Filter;
public class FilterModel extends BasicModel
{
private final Filter m_filter;
private final String[] m_urlPatterns;
private final String[] m_servletNames;
public FilterModel( final Filter filter,
final String[] urlPatterns,
final String[] servletNames,
final ContextModel contextModel )
{
super( contextModel );
if( urlPatterns == null && servletNames == null )
{
throw new IllegalArgumentException(
"Registered filter must have at least one url pattern or servlet mapping"
);
}
m_filter = filter;
m_urlPatterns = urlPatterns;
m_servletNames = servletNames;
}
public Filter getFilter()
{
return m_filter;
}
public String[] getUrlPatterns()
{
return m_urlPatterns;
}
public String[] getServletNames()
{
return m_servletNames;
}
}
|
Add contacts groups default parameter | var ActionAbstract = require('./action-abstract');
/**
* get list of groups
* @see http://dev.smsapi.pl/#!/contacts%2Fgroups/list
* @param {Object} options
* @extends ActionAbstract
* @constructor
*/
function ContactsGroupsList(options) {
ActionAbstract.call(this, options);
}
ContactsGroupsList.prototype = Object.create(ActionAbstract.prototype);
ContactsGroupsList.prototype.defaultParams = {
'with': 'contacts_count'
};
/**
* get/set id
* @param {String} id
* @return {ContactsGroupsList} or {String}
*/
ContactsGroupsList.prototype.id = function (id) {
return this.param('id', id);
};
/**
* get/set name
* @param {String} name
* @return {ContactsGroupsList} or {String}
*/
ContactsGroupsList.prototype.name = function (name) {
return this.param('name', name);
};
/**
* execute action
* @return {Promise}
*/
ContactsGroupsList.prototype.execute = function () {
return this.request()
.get('contacts/groups')
.data(this.params())
.execute();
};
module.exports = ContactsGroupsList;
| var ActionAbstract = require('./action-abstract');
/**
* get list of groups
* @see http://dev.smsapi.pl/#!/contacts%2Fgroups/list
* @param {Object} options
* @extends ActionAbstract
* @constructor
*/
function ContactsGroupsList(options) {
ActionAbstract.call(this, options);
}
ContactsGroupsList.prototype = Object.create(ActionAbstract.prototype);
/**
* get/set id
* @param {String} id
* @return {ContactsGroupsList} or {String}
*/
ContactsGroupsList.prototype.id = function (id) {
return this.param('id', id);
};
/**
* get/set name
* @param {String} name
* @return {ContactsGroupsList} or {String}
*/
ContactsGroupsList.prototype.name = function (name) {
return this.param('name', name);
};
/**
* execute action
* @return {Promise}
*/
ContactsGroupsList.prototype.execute = function () {
return this.request()
.get('contacts/groups')
.data(this.params())
.execute();
};
module.exports = ContactsGroupsList;
|
Fix navbar for adding options. | <?php
require_once 'Inquisition/admin/components/Option/Edit.php';
require_once 'CME/admin/components/Option/include/CMEOptionHelper.php';
/**
* @package CME
* @copyright 2014 silverorange
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
abstract class CMEOptionEdit extends InquisitionOptionEdit
{
// {{{ protected properties
/**
* @var CMEOptionHelper
*/
protected $helper;
// }}}
// init phase
// {{{ protected function initInternal()
protected function initInternal()
{
parent::initInternal();
$this->helper = $this->getOptionHelper();
$this->helper->initInternal();
}
// }}}
// {{{ abstract protected function getOptionHelper()
abstract protected function getOptionHelper();
// }}}
// build phase
// {{{ protected function buildNavBar()
protected function buildNavBar()
{
parent::buildNavBar();
// put add/edit title entry at the end
$title = $this->navbar->popEntry();
// Add dummy entry. The CMEOptionHelper will remove this. All other
// option admin components have a details component in the nav bar.
$this->navbar->createEntry('');
$this->helper->buildNavBar($this->navbar);
// remove dummy entry.
$this->navbar->popEntry();
$this->navbar->addEntry($title);
}
// }}}
}
?>
| <?php
require_once 'Inquisition/admin/components/Option/Edit.php';
require_once 'CME/admin/components/Option/include/CMEOptionHelper.php';
/**
* @package CME
* @copyright 2014 silverorange
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
abstract class CMEOptionEdit extends InquisitionOptionEdit
{
// {{{ protected properties
/**
* @var CMEOptionHelper
*/
protected $helper;
// }}}
// init phase
// {{{ protected function initInternal()
protected function initInternal()
{
parent::initInternal();
$this->helper = $this->getOptionHelper();
$this->helper->initInternal();
}
// }}}
// {{{ abstract protected function getOptionHelper()
abstract protected function getOptionHelper();
// }}}
// build phase
// {{{ protected function buildNavBar()
protected function buildNavBar()
{
parent::buildNavBar();
// put edit entry at the end
$title = $this->navbar->popEntry();
$this->helper->buildNavBar($this->navbar);
$this->navbar->addEntry($title);
}
// }}}
}
?>
|
Change the number of bytes in an Authorization Code from 128 to 32.
Signed-off-by: Marios Sotiropoulos <d835cc3d5a582fb720c036e3ecd99881c51ab932@uom.edu.gr> | <?php
namespace Ms\OauthBundle\Component\Authorization;
use Symfony\Component\Security\Core\Util\SecureRandom;
/**
* Description of AuthorizationService
*
* @author Marios
*/
class AuthorizationService implements AuthorizationServiceInterface {
/**
* @var SecureRandom
*/
private $randomStringGenerator;
/**
*
* @param SecureRandom $rsg
*/
function __construct(SecureRandom $rsg) {
if ($rsg === null) {
throw new InvalidArgumentException('No SecureRandom specified.');
}
$this->randomStringGenerator = $rsg;
}
/**
* @inheritdoc
*/
public function createAuthorizationCode() {
$rnd = $this->randomStringGenerator->nextBytes(32);
$rnd = base64_encode($rnd);
return trim($rnd, '=');
}
}
| <?php
namespace Ms\OauthBundle\Component\Authorization;
use Symfony\Component\Security\Core\Util\SecureRandom;
/**
* Description of AuthorizationService
*
* @author Marios
*/
class AuthorizationService implements AuthorizationServiceInterface {
/**
* @var SecureRandom
*/
private $randomStringGenerator;
/**
*
* @param SecureRandom $rsg
*/
function __construct(SecureRandom $rsg) {
if ($rsg === null) {
throw new InvalidArgumentException('No SecureRandom specified.');
}
$this->randomStringGenerator = $rsg;
}
/**
* @inheritdoc
*/
public function createAuthorizationCode() {
$rnd = $this->randomStringGenerator->nextBytes(128);
$rnd = base64_encode($rnd);
return trim($rnd, '=');
}
}
|
fix(server): Remove unique emails for teams | 'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
| 'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true,
unique: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
|
Verify that event end and start keys exist before accessing. | # -*- coding: utf-8 -*-
from django.db import IntegrityError
from scrapy.exceptions import DropItem
from titlecase import titlecase
from dateutil import parser, relativedelta
class EventPipeline(object):
def process_item(self, item, spider):
item['titleRaw'] = item['title']
item['title'] = titlecase(item['title'])
if 'end' in item and 'start' in item:
if (item['end'] < item['start']):
item['end'] = item['end'] + relativedelta.relativedelta(years =+ 1)
try:
item.save()
except IntegrityError:
raise DropItem('Duplicate: ' + item['venue'] + ' - ' + item['title'])
return item
| # -*- coding: utf-8 -*-
from django.db import IntegrityError
from scrapy.exceptions import DropItem
from titlecase import titlecase
from dateutil import parser, relativedelta
class EventPipeline(object):
def process_item(self, item, spider):
item['titleRaw'] = item['title']
item['title'] = titlecase(item['title'])
if (item['end'] < item['start']):
item['end'] = item['end'] + relativedelta.relativedelta(years =+ 1)
try:
item.save()
except IntegrityError:
raise DropItem('Duplicate: ' + item['venue'] + ' - ' + item['title'])
return item
|
[tests] Remove test for deprecated createmultsig option | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], []]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses")
# assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()])
# self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()])
#
# There are currently no deprecated RPC methods in master, so this
# test is currently empty.
pass
if __name__ == '__main__':
DeprecatedRpcTest().main()
| #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], ["-deprecatedrpc=createmultisig"]]
def run_test(self):
self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses")
assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()])
self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()])
if __name__ == '__main__':
DeprecatedRpcTest().main()
|
Add backslash in front of the class name | <?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Api;
/**
* Filters applicable on a resource.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
interface FilterInterface
{
/**
* Gets the description of this filter for the given resource.
*
* Returns an array with the filter parameter names as keys and array with the following data as values:
* - property: the property where the filter is applied
* - type: the type of the filter
* - required: if this filter is required
* - strategy: the used strategy
* - swagger (optional): additional parameters for the path operation,
* e.g. 'swagger' => [
* 'description' => 'My Description',
* 'name' => 'My Name',
* 'type' => 'integer',
* ]
* The description can contain additional data specific to a filter.
*
* @see \ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer::getFiltersParameters
*
* @param string $resourceClass
*
* @return array
*/
public function getDescription(string $resourceClass): array;
}
| <?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Api;
/**
* Filters applicable on a resource.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
interface FilterInterface
{
/**
* Gets the description of this filter for the given resource.
*
* Returns an array with the filter parameter names as keys and array with the following data as values:
* - property: the property where the filter is applied
* - type: the type of the filter
* - required: if this filter is required
* - strategy: the used strategy
* - swagger (optional): additional parameters for the path operation,
* e.g. 'swagger' => [
* 'description' => 'My Description',
* 'name' => 'My Name',
* 'type' => 'integer',
* ]
* The description can contain additional data specific to a filter.
*
* @see ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer::getFiltersParameters
*
* @param string $resourceClass
*
* @return array
*/
public function getDescription(string $resourceClass): array;
}
|
Fix bug in chunk arguments | from django.conf import settings
import re
import sys
class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""
def __init__(self):
self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)]
def chunk(self,l,n):
return (l[i:i+n] for i in xrange(0, len(l), n))
def is_disposable(self, email):
for email_group in self.chunk(self.emails, 20):
regex = "(.*" + ")|(.*".join(email_group) + ")"
if re.match(regex, email):
return True
return False | from django.conf import settings
import re
import sys
class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""
def __init__(self):
self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)]
def chunk(l,n):
return (l[i:i+n] for i in xrange(0, len(l), n))
def is_disposable(self, email):
for email_group in self.chunk(self.emails, 20):
regex = "(.*" + ")|(.*".join(email_group) + ")"
if re.match(regex, email):
return True
return False |
Remove spacer rectangles and flatten groups in source SVG files
Saves 30K on the iconsets! | #!/usr/bin/env node
var fs = require('fs');
var cheerio = require('cheerio');
var path = require('path');
var cheerioOptions = {xmlMode: true};
var files = process.argv.slice(2);
function read(file) {
var content = fs.readFileSync(file, 'utf8');
return cheerio.load(content, cheerioOptions);
}
function transmogrify($, name) {
// output with cleaned up icon name
var node = $('#Icon').attr('id', name);
// remove spacer rectangles
node.find('rect[fill],rect[style*="fill"]').remove();
// remove empty groups
var innerHTML = $.xml(node.find('*').filter(':not(g)'));
node.html(innerHTML);
// print icon svg
console.log($.xml(node));
}
function path2IconName(file) {
parts = path.basename(file).split('_');
// remove ic_
parts.shift();
// remove _24px.svg
parts.pop();
return parts.join('-');
}
files.forEach(function(file) {
var name = path2IconName(file);
var $ = read(file);
transmogrify($, name);
});
| #!/usr/bin/env node
var fs = require('fs');
var cheerio = require('cheerio');
var path = require('path');
var cheerioOptions = {xmlMode: true};
var files = process.argv.slice(2);
function read(file) {
var content = fs.readFileSync(file, 'utf8');
return cheerio.load(content, cheerioOptions);
}
function transmogrify($, name) {
// output with cleaned up icon name
var node = $('#Icon').attr('id', name);
// print icon svg
console.log($.xml(node));
}
function path2IconName(file) {
parts = path.basename(file).split('_');
// remove ic_
parts.shift();
// remove _24px.svg
parts.pop();
return parts.join('-');
}
files.forEach(function(file) {
var name = path2IconName(file);
var $ = read(file);
transmogrify($, name);
});
|
Add route for top targets | const requestsController = require('../../controllers/requests.js');
const requestHelper = require('../../helpers/requestHelper.js');
module.exports = {
'/:request/top/:size': {
get: function get(req, res, cb) {
const size = parseInt(req.params.size);
res.setHeader('Access-Control-Allow-Origin', '*');
if (typeof size == 'number' && size > 5) {
requestsController.getRowRequest(req.params.request, size, req, res);
} else {
res.json({ success: false, message: 'Invalid size parameter'});
}
},
},
'/game/:type': {
get: function get (req, res, cb) {
res.setHeader('Access-Control-Allow-Origin', '*');
requestsController.getGameRequest(req.params.type, req, res);
},
},
'/getTodayHits': {
get: function get(req, res, cb) {
res.setHeader('Access-Control-Allow-Origin', '*');
requestsController.getTodaysRequests(req, res);
},
},
'/getTopTargets': {
get: function get(req, res, cb) {
res.setHeader('Access-Control-Allow-Origin', '*');
requestsController.getTopTargets(req, res);
}
},
};
| const requestsController = require('../../controllers/requests.js');
const requestHelper = require('../../helpers/requestHelper.js');
module.exports = {
'/:request/top/:size': {
get: function get(req, res, cb) {
const size = parseInt(req.params.size);
res.setHeader('Access-Control-Allow-Origin', '*');
if (typeof size == 'number' && size > 5) {
requestsController.getRowRequest(req.params.request, size, req, res);
} else {
res.json({ success: false, message: 'Invalid size parameter'});
}
},
},
'/game/:type': {
get: function get (req, res, cb) {
res.setHeader('Access-Control-Allow-Origin', '*');
requestsController.getGameRequest(req.params.type, req, res);
},
},
'/getTodayHits': {
get: function get(req, res, cb) {
res.setHeader('Access-Control-Allow-Origin', '*');
requestsController.getTodaysRequests(req, res);
},
}
};
|
Remove y from base predictor. | from abc import abstractmethod
class PredictorBase(object):
""""
Abstract base class that implement the interface that we use for our
predictors. Classic supervised learning.
@author: Heiko
"""
@abstractmethod
def fit(self, X, y):
"""
Method to fit the model.
Parameters:
X - 2d numpy array of training data
y - 1d numpy array of training labels
"""
raise NotImplementedError()
@abstractmethod
def predict(self, X):
"""
Method to apply the model data
Parameters:
X - 2d numpy array of test data
"""
raise NotImplementedError()
| from abc import abstractmethod
class PredictorBase(object):
""""
Abstract base class that implement the interface that we use for our
predictors. Classic supervised learning.
@author: Heiko
"""
@abstractmethod
def fit(self, X, y):
"""
Method to fit the model.
Parameters:
X - 2d numpy array of training data
y - 1d numpy array of training labels
"""
raise NotImplementedError()
@abstractmethod
def predict(self, X, y):
"""
Method to apply the model data
Parameters:
X - 2d numpy array of test data
"""
raise NotImplementedError()
|
Fix for empty strings getting parsed as undefined for rawEnv | import R from 'ramda'
import {inheritedVal} from './inheritance'
const
getMetaToValFn = (envsWithMeta)=> (meta, entryKey)=>{
if (meta.inherits){
return inheritedVal({entryKey, envsWithMeta, inherits: meta.inherits})
} else if (meta.val || meta.val === ""){
return meta.val
} else if (meta.val === ""){
return undefined
}
}
export const
rawEnv = ({envsWithMeta, environment})=> {
return R.mapObjIndexed(
getMetaToValFn(envsWithMeta),
envsWithMeta[environment]
)
},
createEntry = ({envsWithMeta, entryKey, vals})=>{
return R.mapObjIndexed(
(env, name) => R.assoc(entryKey, vals[name], env),
envsWithMeta
)
},
updateEntry = ({envsWithMeta, entryKey, newKey})=>{
return R.mapObjIndexed(
(env)=> ({...R.dissoc(entryKey, env), [newKey]: env[entryKey]}),
envsWithMeta
)
},
removeEntry = ({envsWithMeta, entryKey})=>{
return R.mapObjIndexed(R.dissoc(entryKey), envsWithMeta)
},
updateEntryVal = ({envsWithMeta, entryKey, environment, update})=>{
return R.assocPath([environment, entryKey], update, envsWithMeta)
}
| import R from 'ramda'
import {inheritedVal} from './inheritance'
const
getMetaToValFn = (envsWithMeta)=> (meta, entryKey)=>{
return meta.inherits ?
inheritedVal({entryKey, envsWithMeta, inherits: meta.inherits}) :
(meta.val || undefined)
}
export const
rawEnv = ({envsWithMeta, environment})=> {
return R.mapObjIndexed(
getMetaToValFn(envsWithMeta),
envsWithMeta[environment]
)
},
createEntry = ({envsWithMeta, entryKey, vals})=>{
return R.mapObjIndexed(
(env, name) => R.assoc(entryKey, vals[name], env),
envsWithMeta
)
},
updateEntry = ({envsWithMeta, entryKey, newKey})=>{
return R.mapObjIndexed(
(env)=> ({...R.dissoc(entryKey, env), [newKey]: env[entryKey]}),
envsWithMeta
)
},
removeEntry = ({envsWithMeta, entryKey})=>{
return R.mapObjIndexed(R.dissoc(entryKey), envsWithMeta)
},
updateEntryVal = ({envsWithMeta, entryKey, environment, update})=>{
return R.assocPath([environment, entryKey], update, envsWithMeta)
}
|
Prepare for release for 8.3dev-601. | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.21 2006/12/01 12:06:21 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);
}
}
| /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.20 2006/12/01 12:02:39 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 static int buildNumber = 600;
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);
}
}
|
Return an empty dict if no data
Avoids a HTTP500 on slow instances where the file
may be created before data is written, causing the
YAML parser to return None.
Change-Id: I13b92941f3e368839a9665fe3197c706babd9335 | import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(max_length)
class StreamEcho(object):
def write(self, value):
return value
def description_filename(job_id):
logger = logging.getLogger('lava_results_app')
filename = os.path.join(settings.MEDIA_ROOT, 'job-output', 'job-%s' % job_id, 'description.yaml')
if not os.path.exists(filename):
logger.error("No description.yaml for job %s" % job_id)
return None
return filename
def description_data(job_id):
logger = logging.getLogger('lava_results_app')
filename = description_filename(job_id)
if not filename:
return {}
try:
data = yaml.load(open(filename, 'r'))
except yaml.YAMLError:
logger.error("Unable to parse description for %s" % job_id)
return {}
if not data:
return {}
return data
| import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(max_length)
class StreamEcho(object):
def write(self, value):
return value
def description_filename(job_id):
logger = logging.getLogger('lava_results_app')
filename = os.path.join(settings.MEDIA_ROOT, 'job-output', 'job-%s' % job_id, 'description.yaml')
if not os.path.exists(filename):
logger.error("No description.yaml for job %s" % job_id)
return None
return filename
def description_data(job_id):
logger = logging.getLogger('lava_results_app')
filename = description_filename(job_id)
if not filename:
return {}
try:
data = yaml.load(open(filename, 'r'))
except yaml.YAMLError:
logger.error("Unable to parse description for %s" % job_id)
return {}
return data
|
Remove homepage settings set for problems with Firefox comunity | 'use strict';
var data = require('sdk/self').data;
{{#if extend_ff_index}}
{{> extend_ff_index }}
{{/if}}
{{#if page_action}}
require('sdk/ui/button/action').ActionButton({
{{#if page_action.id}}id: "{{page_action.id}}",{{/if}}
label: "{{page_action.default_title}}",
icon: "./{{page_action.default_icon}}",
onClick: {{#if page_action.callback}}{{page_action.callback}}{{else}}function(state) {
tabs.open(data.url("{{page_action.default_popup}}"));
}{{/if}}
});
{{/if}}
{{#if content_scripts}}
require("sdk/page-mod").PageMod({
{{#if content_scripts.js}}
contentScriptFile: [
{{#each content_scripts.js}}
data.url("{{this}}"),
{{/each}}
],
{{/if}}
{{#if content_scripts.css}}
contentStyleFile: [
{{#each content_scripts.css}}
data.url("{{this}}"),
{{/each}}
],
{{/if}}
include: '{{host}}',
contentScriptWhen: 'ready'
});
{{/if}}
| 'use strict';
var data = require('sdk/self').data;
{{#if extend_ff_index}}
{{> extend_ff_index }}
{{/if}}
{{#if homepage_url}}
require("sdk/preferences/service").set('browser.startup.homepage', '{{homepage_url}}');
{{/if}}
{{#if page_action}}
require('sdk/ui/button/action').ActionButton({
{{#if page_action.id}}id: "{{page_action.id}}",{{/if}}
label: "{{page_action.default_title}}",
icon: "./{{page_action.default_icon}}",
onClick: {{#if page_action.callback}}{{page_action.callback}}{{else}}function(state) {
tabs.open(data.url("{{page_action.default_popup}}"));
}{{/if}}
});
{{/if}}
{{#if content_scripts}}
require("sdk/page-mod").PageMod({
{{#if content_scripts.js}}
contentScriptFile: [
{{#each content_scripts.js}}
data.url("{{this}}"),
{{/each}}
],
{{/if}}
{{#if content_scripts.css}}
contentStyleFile: [
{{#each content_scripts.css}}
data.url("{{this}}"),
{{/each}}
],
{{/if}}
include: '{{host}}',
contentScriptWhen: 'ready'
});
{{/if}}
|
Update location of local test file |
var loadFileUrl = function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // synchronous
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send();
if (xhr.status === 200) {
return xhr.response; // Note: not xhr.responseText
} else {
throw new Error("File not found");
}
}
describe("MobiRead", function() {
it("should complain of missing file", function() {
var loadMissing = function() {
data = loadFileUrl("nosuchfile");
}
expect(loadMissing).toThrow();
});
it("should load and parse a valid file", function() {
var data;
var loadIt = function() {
data = loadFileUrl("http://localhost/~dmd/jsebook/data/testbook.mobi");
}
expect(loadIt).not.toThrow();
});
it("should complain of wrong file type", function() {
});
});
|
var loadFileUrl = function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // synchronous
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send();
if (xhr.status === 200) {
return xhr.response; // Note: not xhr.responseText
} else {
throw new Error("File not found");
}
}
describe("MobiRead", function() {
it("should complain of missing file", function() {
var loadMissing = function() {
data = loadFileUrl("nosuchfile");
}
expect(loadMissing).toThrow();
});
it("should load and parse a valid file", function() {
var data;
var loadIt = function() {
data = loadFileUrl("http://localhost/~dmd/current/jsebook/data/testbook.mobi");
}
expect(loadIt).not.toThrow();
});
it("should complain of wrong file type", function() {
});
});
|
Add UTF-8 encoding to readme file | from setuptools import setup
with open('README.md', 'r', encoding='utf-8') as f:
readme = f.read()
setup(
version='1.3.4',
name='FuelSDKWrapper',
description='Simplify and enhance the FuelSDK for Salesforce Marketing Cloud (ExactTarget)',
long_description=readme,
long_description_content_type="text/markdown",
author='Seb Angel',
author_email='seb.angel.force@gmail.com',
py_modules=['FuelSDKWrapper'],
packages=[],
url='https://github.com/seb-angel/FuelSDK-Python-Wrapper',
license='MIT',
install_requires=[
'Salesforce-FuelSDK>=1.3.0',
'PyJWT>=0.1.9',
'requests>=2.18.4',
'suds-jurko>=0.6'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
| from setuptools import setup
with open('README.md') as f:
readme = f.read()
setup(
version='1.3.4',
name='FuelSDKWrapper',
description='Simplify and enhance the FuelSDK for Salesforce Marketing Cloud (ExactTarget)',
long_description=readme,
long_description_content_type="text/markdown",
author='Seb Angel',
author_email='seb.angel.force@gmail.com',
py_modules=['FuelSDKWrapper'],
packages=[],
url='https://github.com/seb-angel/FuelSDK-Python-Wrapper',
license='MIT',
install_requires=[
'Salesforce-FuelSDK>=1.3.0',
'PyJWT>=0.1.9',
'requests>=2.18.4',
'suds-jurko>=0.6'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
|
Disable animations on Android again
Summary: We don't yet have native driver support for animations in bridgeless mode on Android, which leads to some weird bugs (like an overlay that never disappears). Let's just disable animations on Android again.
Reviewed By: mdvacca
Differential Revision: D21537982
fbshipit-source-id: b4e8882a414fecbd52dd25e02325b5c588ee68c0 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import Platform from '../../Utilities/Platform';
import typeof AnimatedFlatList from './components/AnimatedFlatList';
import typeof AnimatedImage from './components/AnimatedImage';
import typeof AnimatedScrollView from './components/AnimatedScrollView';
import typeof AnimatedSectionList from './components/AnimatedSectionList';
import typeof AnimatedText from './components/AnimatedText';
import typeof AnimatedView from './components/AnimatedView';
const AnimatedMock = require('./AnimatedMock');
const AnimatedImplementation = require('./AnimatedImplementation');
const Animated = ((Platform.isTesting ||
(Platform.OS === 'android' && global.RN$Bridgeless)
? AnimatedMock
: AnimatedImplementation): typeof AnimatedMock);
module.exports = {
get FlatList(): AnimatedFlatList {
return require('./components/AnimatedFlatList');
},
get Image(): AnimatedImage {
return require('./components/AnimatedImage');
},
get ScrollView(): AnimatedScrollView {
return require('./components/AnimatedScrollView');
},
get SectionList(): AnimatedSectionList {
return require('./components/AnimatedSectionList');
},
get Text(): AnimatedText {
return require('./components/AnimatedText');
},
get View(): AnimatedView {
return require('./components/AnimatedView');
},
...Animated,
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import Platform from '../../Utilities/Platform';
import typeof AnimatedFlatList from './components/AnimatedFlatList';
import typeof AnimatedImage from './components/AnimatedImage';
import typeof AnimatedScrollView from './components/AnimatedScrollView';
import typeof AnimatedSectionList from './components/AnimatedSectionList';
import typeof AnimatedText from './components/AnimatedText';
import typeof AnimatedView from './components/AnimatedView';
const AnimatedMock = require('./AnimatedMock');
const AnimatedImplementation = require('./AnimatedImplementation');
const Animated = ((Platform.isTesting
? AnimatedMock
: AnimatedImplementation): typeof AnimatedMock);
module.exports = {
get FlatList(): AnimatedFlatList {
return require('./components/AnimatedFlatList');
},
get Image(): AnimatedImage {
return require('./components/AnimatedImage');
},
get ScrollView(): AnimatedScrollView {
return require('./components/AnimatedScrollView');
},
get SectionList(): AnimatedSectionList {
return require('./components/AnimatedSectionList');
},
get Text(): AnimatedText {
return require('./components/AnimatedText');
},
get View(): AnimatedView {
return require('./components/AnimatedView');
},
...Animated,
};
|
Disable OAI-PMH Identify test for baseURL.
Requires non-trivial work with Guice to get the test to work. | package org.gbif.registry.oaipmh;
import org.gbif.api.service.registry.DatasetService;
import org.gbif.api.service.registry.InstallationService;
import org.gbif.api.service.registry.NodeService;
import org.gbif.api.service.registry.OrganizationService;
import org.dspace.xoai.model.oaipmh.DeletedRecord;
import org.dspace.xoai.model.oaipmh.Identify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
/**
* Test the Identify verb of the OAI-PMH endpoint.
*/
@RunWith(Parameterized.class)
public class OaipmhIdentifyIT extends AbstractOaipmhEndpointIT {
public OaipmhIdentifyIT(NodeService nodeService, OrganizationService organizationService, InstallationService installationService, DatasetService datasetService) {
super(nodeService, organizationService, installationService, datasetService);
}
@Test
public void identify() {
Identify response = serviceProvider.identify();
assertEquals("GBIF Test Registry", response.getRepositoryName());
// TODO: assertEquals(baseUrl, response.getBaseURL());
assertEquals(DeletedRecord.PERSISTENT, response.getDeletedRecord());
}
}
| package org.gbif.registry.oaipmh;
import org.gbif.api.service.registry.DatasetService;
import org.gbif.api.service.registry.InstallationService;
import org.gbif.api.service.registry.NodeService;
import org.gbif.api.service.registry.OrganizationService;
import org.dspace.xoai.model.oaipmh.DeletedRecord;
import org.dspace.xoai.model.oaipmh.Identify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
/**
* Test the Identify verb of the OAI-PMH endpoint.
*/
@RunWith(Parameterized.class)
public class OaipmhIdentifyIT extends AbstractOaipmhEndpointIT {
public OaipmhIdentifyIT(NodeService nodeService, OrganizationService organizationService, InstallationService installationService, DatasetService datasetService) {
super(nodeService, organizationService, installationService, datasetService);
}
@Test
public void identify() {
Identify response = serviceProvider.identify();
assertEquals("GBIF Test Registry", response.getRepositoryName());
assertEquals(baseUrl, response.getBaseURL());
assertEquals(DeletedRecord.PERSISTENT, response.getDeletedRecord());
}
}
|
Add homepage to the recipe site | """recipe_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from recipes.views import IndexView
urlpatterns = [
url(r'^recipes/', include('recipes.urls')),
url(r'^$', IndexView.as_view(), name='index'),
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
| """recipe_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^recipes/', include('recipes.urls')),
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
|
Remove angular module from global scope | (function() {
var app = angular.module("vackerApp", []);
var YearController = function($scope, $http) {
var onYearsComplete = function(response) {
$scope.years = response.data;
};
var onHttpError = function(reason) {
alert("HTTP error: " + reason);
};
$http.get("http://localhost:5000/years")
.then(onYearsComplete, onHttpError);
$scope.get_thumbnail_url = function (year) {
return "http://localhost:5000/years/" + year + "/thumbnail";
};
};
app.controller("YearController", YearController);
})();
| // (function() {
var app = angular.module("vackerApp", []);
var YearController = function($scope, $http) {
var onYearsComplete = function(response) {
$scope.years = response.data;
};
var onHttpError = function(reason) {
alert("HTTP error: " + reason);
};
$http.get("http://localhost:5000/years")
.then(onYearsComplete, onHttpError);
$scope.get_thumbnail_url = function (year) {
return "http://localhost:5000/years/" + year + "/thumbnail";
};
};
app.controller("YearController", YearController);
// })
|
Use mustRun instead of run and catch exception
It does the same thing but it gives out a better exception object. | <?php
/* (c) Anton Medvedev <anton@elfet.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Deployer\Server;
use Symfony\Component\Process\Process;
class Local implements ServerInterface
{
/**
* {@inheritdoc}
*/
public function connect()
{
// We do not need to connect to local server.
}
/**
* {@inheritdoc}
*/
public function run($command)
{
$process = new Process($command);
$process->mustRun();
return $process->getOutput();
}
/**
* {@inheritdoc}
*/
public function upload($local, $remote)
{
copy($local, $remote);
}
/**
* {@inheritdoc}
*/
public function download($local, $remote)
{
copy($remote, $local);
}
}
| <?php
/* (c) Anton Medvedev <anton@elfet.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Deployer\Server;
use Symfony\Component\Process\Process;
class Local implements ServerInterface
{
/**
* {@inheritdoc}
*/
public function connect()
{
// We do not need to connect to local server.
}
/**
* {@inheritdoc}
*/
public function run($command)
{
$process = new Process($command);
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
return $process->getOutput();
}
/**
* {@inheritdoc}
*/
public function upload($local, $remote)
{
copy($local, $remote);
}
/**
* {@inheritdoc}
*/
public function download($local, $remote)
{
copy($remote, $local);
}
}
|
Make sure Windows modules are installed. | #!/usr/bin/env python
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
try:
from setuptools import setup, find_packages
except ImportError:
print "Ansible now needs setuptools in order to build. " \
"Install it using your package manager (usually python-setuptools) or via pip (pip install setuptools)."
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='michael@ansible.com',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-vault',
],
data_files=[],
)
| #!/usr/bin/env python
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
try:
from setuptools import setup, find_packages
except ImportError:
print "Ansible now needs setuptools in order to build. " \
"Install it using your package manager (usually python-setuptools) or via pip (pip install setuptools)."
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='michael@ansible.com',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-vault',
],
data_files=[],
)
|
Set "notify_email" in default scope only if settings allow it | """The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
| """The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
Add reference from Content to Resource table | export async function up(knex) {
await knex.schema.createTable('Resource', (table) => {
table.uuid('id').notNullable().primary()
table.string('name', 32).notNullable()
table.string('mime', 32)
table.string('md5')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
await knex.schema.createTable('Content', (table) => {
table.increments()
table.uuid('resourceId').notNullable().references('Resource.id')
table.string('name', 32)
table.string('title', 255)
table.text('description')
table.json('data')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
}
export async function down(knex) {
await knex.schema.dropTableIfExists('Content')
await knex.schema.dropTableIfExists('Resource')
}
| export async function up(knex) {
await knex.schema.createTable('Content', (table) => {
table.increments()
table.uuid('resourceId').notNullable()
table.string('name', 32)
table.string('title', 255)
table.text('description')
table.json('data')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
await knex.schema.createTable('Resource', (table) => {
table.uuid('id').notNullable().primary()
table.string('name', 32).notNullable()
table.string('mime', 32)
table.string('md5')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
}
export async function down(knex) {
await knex.schema.dropTableIfExists('Resource')
await knex.schema.dropTableIfExists('Content')
}
|
Correct value to match spec | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package COSE;
import com.upokecenter.cbor.CBORObject;
/**
*
* @author jimsch
*/
public enum HeaderKeys {
Algorithm(1),
CONTENT_TYPE(3),
KID(4),
IV(5),
CriticalHeaders(2),
CounterSignature(7),
PARTIAL_IV(6),
ECDH_EPK(-1),
ECDH_SPK(-2),
ECDH_SKID(-3),
HKDF_Salt(-20),
HKDF_Context_PartyU_ID(-21),
HKDF_Context_PartyU_nonce(-22),
HKDF_Context_PartyU_Other(-23),
HKDF_Context_PartyV_ID(-24),
HKDF_Context_PartyV_nonce(-25),
HKDF_Context_PartyV_Other(-26),
HKDF_SuppPub_Other(-999),
HKDF_SuppPriv_Other(-998)
;
private CBORObject value;
HeaderKeys(int val) {
this.value = CBORObject.FromObject(val);
}
public CBORObject AsCBOR() {
return value;
}
}
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package COSE;
import com.upokecenter.cbor.CBORObject;
/**
*
* @author jimsch
*/
public enum HeaderKeys {
Algorithm(1),
CONTENT_TYPE(3),
KID(2),
IV(5),
CriticalHeaders(2),
CounterSignature(7),
PARTIAL_IV(6),
ECDH_EPK(-1),
ECDH_SPK(-2),
ECDH_SKID(-3),
HKDF_Salt(-20),
HKDF_Context_PartyU_ID(-21),
HKDF_Context_PartyU_nonce(-22),
HKDF_Context_PartyU_Other(-23),
HKDF_Context_PartyV_ID(-24),
HKDF_Context_PartyV_nonce(-25),
HKDF_Context_PartyV_Other(-26),
HKDF_SuppPub_Other(-999),
HKDF_SuppPriv_Other(-998)
;
private CBORObject value;
HeaderKeys(int val) {
this.value = CBORObject.FromObject(val);
}
public CBORObject AsCBOR() {
return value;
}
}
|
Remove field that has now the same default implementation on it's super class. | # Copyright (c) 2009-2010 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.content.cp.browser.blocks.teaser
import zeit.content.cp.interfaces
import zeit.edit.browser.block
import zeit.edit.browser.view
import zope.formlib.form
class ViewletManager(zeit.edit.browser.block.BlockViewletManager):
@property
def css_class(self):
classes = super(ViewletManager, self).css_class
return ' '.join(['editable-area', classes])
class EditProperties(zeit.content.cp.browser.blocks.teaser.EditLayout):
interface = zeit.content.cp.interfaces.IArea
layout_prefix = 'teaserbar' # XXX should be area
layouts = ()
class EditCommon(zeit.edit.browser.view.EditBox):
form_fields = zope.formlib.form.Fields(
zeit.content.cp.interfaces.IArea).select(
'supertitle', 'teaserText', 'background_color')
form_fields['background_color'].custom_widget = (
zeit.cms.browser.widget.ColorpickerWidget)
| # Copyright (c) 2009-2010 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.content.cp.browser.blocks.teaser
import zeit.content.cp.interfaces
import zeit.edit.browser.block
import zeit.edit.browser.view
import zope.formlib.form
class ViewletManager(zeit.edit.browser.block.BlockViewletManager):
@property
def css_class(self):
classes = super(ViewletManager, self).css_class
return ' '.join(['editable-area', classes])
class EditProperties(zeit.content.cp.browser.blocks.teaser.EditLayout):
interface = zeit.content.cp.interfaces.IArea
layout_prefix = 'teaserbar' # XXX should be area
layouts = ()
form_fields = zope.formlib.form.Fields() # XXX implement me
class EditCommon(zeit.edit.browser.view.EditBox):
form_fields = zope.formlib.form.Fields(
zeit.content.cp.interfaces.IArea).select(
'supertitle', 'teaserText', 'background_color')
form_fields['background_color'].custom_widget = (
zeit.cms.browser.widget.ColorpickerWidget)
|
Fix parent position when walking child nodes
The child node needs to know its parent's absolute position in order to
determine its own absolute position. Previously, the parent's relative position
(in relation to its own parent) has been passed. This leads to wrong
positioning of nested nodes after several levels of recursion. I fixed this by
passing the current node's absolute position to the child nodes' layout
function. | 'use strict';
var computeLayout = require('./Layout');
/**
* This computes the CSS layout for a RenderLayer tree and mutates the frame
* objects at each node.
*
* @param {Renderlayer} root
* @return {Object}
*/
function layoutNode (root) {
var rootNode = createNode(root);
computeLayout(rootNode);
walkNode(rootNode);
return rootNode;
}
function createNode (layer) {
return {
layer: layer,
layout: {
width: undefined, // computeLayout will mutate
height: undefined, // computeLayout will mutate
top: 0,
left: 0,
},
style: layer._originalStyle || {},
children: (layer.children || []).map(createNode)
};
}
function walkNode (node, parentLeft, parentTop) {
node.layer.frame.x = node.layout.left + (parentLeft || 0);
node.layer.frame.y = node.layout.top + (parentTop || 0);
node.layer.frame.width = node.layout.width;
node.layer.frame.height = node.layout.height;
if (node.children && node.children.length > 0) {
node.children.forEach(function (child) {
walkNode(child, node.layer.frame.x, node.layer.frame.y);
});
}
}
module.exports = layoutNode;
| 'use strict';
var computeLayout = require('./Layout');
/**
* This computes the CSS layout for a RenderLayer tree and mutates the frame
* objects at each node.
*
* @param {Renderlayer} root
* @return {Object}
*/
function layoutNode (root) {
var rootNode = createNode(root);
computeLayout(rootNode);
walkNode(rootNode);
return rootNode;
}
function createNode (layer) {
return {
layer: layer,
layout: {
width: undefined, // computeLayout will mutate
height: undefined, // computeLayout will mutate
top: 0,
left: 0,
},
style: layer._originalStyle || {},
children: (layer.children || []).map(createNode)
};
}
function walkNode (node, parentLeft, parentTop) {
node.layer.frame.x = node.layout.left + (parentLeft || 0);
node.layer.frame.y = node.layout.top + (parentTop || 0);
node.layer.frame.width = node.layout.width;
node.layer.frame.height = node.layout.height;
if (node.children && node.children.length > 0) {
node.children.forEach(function (child) {
walkNode(child, node.layout.left, node.layout.top);
});
}
}
module.exports = layoutNode;
|
Add __str__ method for Chord class.
Signed-off-by: Charlotte Pierce <351429ca27f6e4bff2dbb77adb5046c88cd12fae@malformed-bits.com> | class Chord(object):
# TODO: doctring
def __init__(self, root_note):
# TODO: doctring
# TODO: validation
self.notes = [root_note]
def root(self):
# TODO: doctring
# TODO: tests
return self.notes[0]
def add_note(self, new_note):
# TODO: docstring
# TODO: tests
if new_note < self.root():
self.notes.insert(0, new_note)
return
for i in range(len(self.notes) - 1):
if (new_note >= self.notes[i]) and (new_note < self.notes[i + 1]):
self.notes.insert(i + 1, new_note)
return
self.notes.append(new_note)
def __str__(self):
# TODO: docstring
out = ''
for n in self.notes:
out += n.__str__() + '+'
out = out [:-1]
return out | class Chord(object):
# TODO: doctring
def __init__(self, root_note):
# TODO: doctring
# TODO: validation
self.notes = [root_note]
def root(self):
# TODO: doctring
# TODO: tests
return self.notes[0]
def add_note(self, new_note):
# TODO: docstring
# TODO: tests
if new_note < self.root():
self.notes.insert(0, new_note)
return
for i in range(len(self.notes) - 1):
if (new_note >= self.notes[i]) and (new_note < self.notes[i + 1]):
self.notes.insert(i + 1, new_note)
return
self.notes.append(new_note) |
Add footnotes extension to showdown
refs 1318
- based on Markdown Extra https://michelf.ca/projects/php-markdown/extra/
- allows [^n] for automatic numbering based on sequence | /* global Showdown, Handlebars, html_sanitize*/
import cajaSanitizers from 'ghost/utils/caja-sanitizers';
var showdown,
formatMarkdown;
showdown = new Showdown.converter({extensions: ['ghostimagepreview', 'ghostgfm', 'footnotes']});
formatMarkdown = Ember.Handlebars.makeBoundHelper(function (markdown) {
var escapedhtml = '';
// convert markdown to HTML
escapedhtml = showdown.makeHtml(markdown || '');
// replace script and iFrame
// jscs:disable
escapedhtml = escapedhtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
escapedhtml = escapedhtml.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// jscs:enable
// sanitize html
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
escapedhtml = html_sanitize(escapedhtml, cajaSanitizers.url, cajaSanitizers.id);
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
return new Handlebars.SafeString(escapedhtml);
});
export default formatMarkdown;
| /* global Showdown, Handlebars, html_sanitize*/
import cajaSanitizers from 'ghost/utils/caja-sanitizers';
var showdown,
formatMarkdown;
showdown = new Showdown.converter({extensions: ['ghostimagepreview', 'ghostgfm']});
formatMarkdown = Ember.Handlebars.makeBoundHelper(function (markdown) {
var escapedhtml = '';
// convert markdown to HTML
escapedhtml = showdown.makeHtml(markdown || '');
// replace script and iFrame
// jscs:disable
escapedhtml = escapedhtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
escapedhtml = escapedhtml.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// jscs:enable
// sanitize html
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
escapedhtml = html_sanitize(escapedhtml, cajaSanitizers.url, cajaSanitizers.id);
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
return new Handlebars.SafeString(escapedhtml);
});
export default formatMarkdown;
|
Make sprite unit tests more robust | 'use strict';
GJS.Sprite.gfxPath = '../examples/assets/gfx/';
describe('Sprite', function() {
it('maintains a counter of loaded objects', function() {
var s;
runs(function() {
s = new GJS.Sprite('carrot.png');
expect(GJS.Sprite.loadedFraction()).toBeLessThan(1);
});
waitsFor(function() { return s.loaded; });
runs(function() {
expect(GJS.Sprite.loadedFraction()).toBe(1);
});
});
it('can be used before it is loaded', function() {
var s = new GJS.Sprite('carrot.png');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
s.draw(ctx, 0, 0);
s.drawRotated(ctx, 0, 0, 0);
s.drawRotatedNonUniform(ctx, 0, 0, 0, 0, 0);
expect(s.loaded).toBe(false);
});
}); | 'use strict';
GJS.Sprite.gfxPath = '../examples/assets/gfx/';
describe('Sprite', function() {
it('can be used before it is loaded', function() {
var s = new GJS.Sprite('carrot.png');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
s.draw(ctx, 0, 0);
s.drawRotated(ctx, 0, 0, 0);
s.drawRotatedNonUniform(ctx, 0, 0, 0, 0, 0);
expect(s.loaded).toBe(false);
});
it('maintains a counter of loaded objects', function() {
var s;
runs(function() {
s = new GJS.Sprite('carrot.png');
expect(GJS.Sprite.loadedFraction()).toBe(0);
});
waitsFor(function() { return s.loaded; });
runs(function() {
expect(GJS.Sprite.loadedFraction()).toBe(1);
});
});
}); |
Throw error if APC extension is not loaded | <?php
namespace F3\AppNexusClient;
/**
* ApcTokenStorage
*
* @uses TokenStorage
* @package
* @version $id$
* @copyright Federico Nicolás Motta
* @author Federico Nicolás Motta <fedemotta@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
class ApcTokenStorage implements TokenStorage
{
private $prefix;
private $ttl;
public function __construct($prefix = '', $ttl = 0 )
{
if ( ! extension_loaded('apc')) {
throw new \RuntimeException('APC extension is not loaded');
}
$this->prefix = $prefix;
$this->ttl = $ttl;
}
/**
* set token
*
* @param string $username
* @param string $token
* @return bool
*/
public function set($username, $token)
{
return apc_store($this->prefix.$username, $token, $this->ttl);
}
/**
* get token
*
* @param string $username
* @return string|false
*/
public function get($username)
{
return apc_fetch($this->prefix.$username);
}
}
| <?php
namespace F3\AppNexusClient;
/**
* ApcTokenStorage
*
* @uses TokenStorage
* @package
* @version $id$
* @copyright Federico Nicolás Motta
* @author Federico Nicolás Motta <fedemotta@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
class ApcTokenStorage implements TokenStorage
{
private $prefix;
private $ttl;
public function __construct($prefix = '', $ttl = 0 )
{
$this->prefix = $prefix;
$this->ttl = $ttl;
}
/**
* set token
*
* @param string $username
* @param string $token
* @return bool
*/
public function set($username, $token)
{
return apc_store($this->prefix.$username, $token, $this->ttl);
}
/**
* get token
*
* @param string $username
* @return string|false
*/
public function get($username)
{
return apc_fetch($this->prefix.$username);
}
}
|
Make port dynamic for Heroku | var express = require('express'),
cons = require('consolidate'),
app = express(),
mustacheRender = require("./lib/mustacheRender").mustacheRender,
port = (process.env.PORT || 3000);
// Application settings
app.engine('html', cons.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk/public'));
// middleware to wrap mustache views in govuk template
app.use(mustacheRender);
//
var commonHead = '<link href="/public/stylesheets/application.css" rel="stylesheet" type="text/css" />';
// routes
app.get('/', function (req, res) {
var head = commonHead;
res.render('index',
{'pageTitle': 'index',
'head' : head });
});
app.get('/sample', function (req, res) {
var head = commonHead;
res.render('sample',
{'pageTitle': 'sample',
'head' : head });
});
// start the app
app.listen(port);
console.log('');
console.log('Listening on port ' + port);
console.log('');
| var express = require('express'),
cons = require('consolidate'),
app = express(),
mustacheRender = require("./lib/mustacheRender").mustacheRender;
// Application settings
app.engine('html', cons.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk/public'));
// middleware to wrap mustache views in govuk template
app.use(mustacheRender);
//
var commonHead = '<link href="/public/stylesheets/application.css" rel="stylesheet" type="text/css" />';
// routes
app.get('/', function (req, res) {
var head = commonHead;
res.render('index',
{'pageTitle': 'index',
'head' : head });
});
app.get('/sample', function (req, res) {
var head = commonHead;
res.render('sample',
{'pageTitle': 'sample',
'head' : head });
});
// start the app
app.listen(3000);
console.log('');
console.log('Listening on port 3000');
console.log('');
|
Upgrade libchromiumcontent to contain printing headers. | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '432720d4613e3aac939f127fe55b9d44fea349e5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
| #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'bb664e4665851fe923ce904e620ba43d8d010ba5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
|
Change the way to handle space followed by $inline$ | const latexExtension = (showdown) => {
const latexInlineRegex = /(\s)~D([^~D\n].*[^~D\n])~D/g
const latexDisplayRegex =/~D~D(.*)~D~D/g
showdown.extension('latex' , () => {
return [
{
type: "lang",
filter: (text, converter, options) => {
return text.replace(latexInlineRegex, (match, space, exp) => {
return `${space}<span class="latex">${exp}</span>`;
});
}
},
{
type: "lang",
filter: (text, converter, options) => {
return text.replace(latexDisplayRegex, (match, exp) => {
return `<div class="latex">${exp}</div>`;
});
}
}
];
});
}
export default latexExtension
| const latexExtension = (showdown) => {
const latexInlineRegex = /\s~D([^~D\n].*[^~D\n])~D/g
const latexDisplayRegex =/~D~D(.*)~D~D/g
showdown.extension('latex' , () => {
return [
{
type: "lang",
filter: (text, converter, options) => {
return text.replace(latexInlineRegex, (match, exp) => {
return `<span class="latex"> ${exp}</span>`;
});
}
},
{
type: "lang",
filter: (text, converter, options) => {
return text.replace(latexDisplayRegex, (match, exp) => {
return `<div class="latex">${exp}</div>`;
});
}
}
];
});
}
export default latexExtension
|
Mask Service is pending the completed object model
SVN-Revision: 7136 | package gov.nih.nci.calab.service.workflow;
/**
* Generalizes Mask functionality for masking Aliquot, File, etc.
* @author doswellj
* @param strType Type of Mask (e.g., aliquot, file, run, etc.)
* @param strId The id associated to the type
* @param strDescription The mask description associated to the mask type and Id.
*
*/
public class MaskService
{
//This functionality is pending the completed Object Model
public void setMask(String strType, String strId, String strDescription)
{
if (strType.equals("aliquot"))
{
//TODO Find Aliquot record based on the strID
//TODO Set File Status record to "Masked".
}
if (strType.equals("file"))
{
//TODO Find File record based on the its strID
//TODO Set File Status record to "Masked".
}
}
}
| package gov.nih.nci.calab.service.workflow;
/**
* Generalizes Mask functionality for masking Aliquot, File, etc.
* @author doswellj
* @param strType Type of Mask (e.g., aliquot, file, run, etc.)
* @param strId The id associated to the type
* @param strDescription The mask description associated to the mask type and Id.
*
*/
public class MaskService
{
public void setMask(String strType, String strId, String strDescription)
{
if (strType.equals("aliquot"))
{
//TODO Find Aliquot record based on the its id and set the status to "Masked" and its Description
}
if (strType.equals("file"))
{
//TODO Find File record based on the its id and set the status to "Masked" and its Description
}
}
}
|
Convert ES6 arrow syntax to ES5 for compatibility
This obviates the need to put Uglifier in harmony mode. | Spree.Views.Cart.EmptyCartButton = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'update', this.render);
this.render();
},
events: {
"click": "onClick"
},
onClick: function(e) {
e.preventDefault()
if (!confirm(Spree.translations.are_you_sure_delete)) {
return;
}
this.model.empty({
success: function () {
this.collection.reset()
this.collection.push({})
}.bind(this)
})
},
render: function() {
var isNew = function (item) { return item.isNew() };
this.$el.prop("disabled", !this.collection.length || this.collection.some(isNew));
}
});
| Spree.Views.Cart.EmptyCartButton = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'update', this.render);
this.render();
},
events: {
"click": "onClick"
},
onClick: function(e) {
e.preventDefault()
if (!confirm(Spree.translations.are_you_sure_delete)) {
return;
}
this.model.empty({
success: () => {
this.collection.reset()
this.collection.push({})
}
})
},
render: function() {
var isNew = function (item) { return item.isNew() };
this.$el.prop("disabled", !this.collection.length || this.collection.some(isNew));
}
});
|
Fix broken suffix on chapters with a dot. | 'use strict';
var affix = require('./affix');
/**
* Creates an alias for the chapter.
* @param {!{title: ?string}} series
* @param {!{number: number, volume: number}} chapter
* @param {string=} extension
* @return {?string}
*/
module.exports = function (series, chapter, extension) {
var name = invalidate(series.title);
if (!name) return undefined;
var number = '#' + affix(stripSuffix(chapter.number.toFixed(4)), 3);
var prefix = name + '/' + name + ' ';
var suffix = number + '.' + (extension || 'cbz');
if (isNaN(chapter.volume)) return prefix + suffix;
return prefix + 'V' + affix(String(chapter.volume), 2) + ' ' + suffix;
};
/**
* Invalidates the value.
* @param {string} value
* @return {string}
*/
function invalidate(value) {
return value.replace(/["<>\|:\*\?\\\/]/g, '');
}
/**
* Strips a suffix from the zero-padded value.
* @param {string} value
* @return {string}
*/
function stripSuffix(value) {
return value.replace(/0+$/g, '');
}
| 'use strict';
var affix = require('./affix');
/**
* Creates an alias for the chapter.
* @param {!{title: ?string}} series
* @param {!{number: number, volume: number}} chapter
* @param {string=} extension
* @return {?string}
*/
module.exports = function (series, chapter, extension) {
var name = invalidate(series.title);
if (!name) return undefined;
var number = '#' + affix(stripSuffix(chapter.number.toFixed(4)), 3);
var prefix = name + '/' + name + ' ';
var suffix = number + '.' + (extension || 'cbz');
if (isNaN(chapter.volume)) return prefix + suffix;
return prefix + 'V' + affix(String(chapter.volume), 2) + ' ' + suffix;
};
/**
* Invalidates the value.
* @param {string} value
* @return {string}
*/
function invalidate(value) {
return value.replace(/["<>\|:\*\?\\\/]/g, '');
}
/**
* Strips a suffix from the zero-padded value.
* @param {string} value
* @return {string}
*/
function stripSuffix(value) {
return value.replace(/\.0+$/g, '');
}
|
Revert "Revert "Another attempt to fix the RTD build.""
This reverts commit bb96586af0aa0fcf6ca5b1891740fbc02f3758c8. | from setuptools import setup, find_packages
VERSION = '1.1.4'
setup(
name="puresnmp",
version=VERSION,
description="Pure Python SNMP implementation",
long_description=open("README.rst").read(),
author="Michel Albert",
author_email="michel@albert.lu",
provides=['puresnmp'],
license="MIT",
include_package_data=True,
install_requires=[
'typing',
],
extras_require={
'dev': [],
'test': ['pytest-xdist', 'pytest', 'pytest-coverage']
},
packages=find_packages(exclude=["tests.*", "tests", "docs"]),
url="https://github.com/exhuma/puresnmp",
keywords="networking snmp",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Topic :: System :: Networking',
'Topic :: System :: Networking :: Monitoring',
'Topic :: System :: Systems Administration',
]
)
| from setuptools import setup, find_packages
from os.path import dirname, abspath
HERE = abspath(dirname(__file__))
VERSION = open(HERE + '/puresnmp/version.txt').read().strip()
setup(
name="puresnmp",
version=VERSION,
description="Pure Python SNMP implementation",
long_description=open(HERE + "/README.rst").read(),
author="Michel Albert",
author_email="michel@albert.lu",
provides=['puresnmp'],
license="MIT",
include_package_data=True,
install_requires=[
'typing',
],
extras_require={
'dev': [],
'test': ['pytest-xdist', 'pytest', 'pytest-coverage']
},
packages=find_packages(exclude=["tests.*", "tests", "docs"]),
url="https://github.com/exhuma/puresnmp",
keywords="networking snmp",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Topic :: System :: Networking',
'Topic :: System :: Networking :: Monitoring',
'Topic :: System :: Systems Administration',
]
)
|
Disable call to Analytics in the background_crash process | package com.ianhanniballake.contractiontimer;
import android.app.Application;
import com.google.firebase.FirebaseApp;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.ianhanniballake.contractiontimer.appwidget.AppWidgetUpdateHandler;
import com.ianhanniballake.contractiontimer.notification.NotificationUpdateService;
import com.ianhanniballake.contractiontimer.strictmode.StrictModeController;
/**
* Creates the Contraction Timer application, setting strict mode in debug mode
*/
public class ContractionTimerApplication extends Application {
/**
* Sets strict mode if we are in debug mode.
*
* @see android.app.Application#onCreate()
*/
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
StrictModeController.createInstance().setStrictMode();
}
if (!FirebaseApp.getApps(this).isEmpty()) {
FirebaseAnalytics.getInstance(this).setUserProperty("debug", Boolean.toString(BuildConfig.DEBUG));
}
super.onCreate();
AppWidgetUpdateHandler.createInstance().updateAllWidgets(this);
NotificationUpdateService.updateNotification(this);
}
} | package com.ianhanniballake.contractiontimer;
import android.app.Application;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.ianhanniballake.contractiontimer.appwidget.AppWidgetUpdateHandler;
import com.ianhanniballake.contractiontimer.notification.NotificationUpdateService;
import com.ianhanniballake.contractiontimer.strictmode.StrictModeController;
/**
* Creates the Contraction Timer application, setting strict mode in debug mode
*/
public class ContractionTimerApplication extends Application {
/**
* Sets strict mode if we are in debug mode.
*
* @see android.app.Application#onCreate()
*/
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
StrictModeController.createInstance().setStrictMode();
}
FirebaseAnalytics.getInstance(this).setUserProperty("debug", Boolean.toString(BuildConfig.DEBUG));
super.onCreate();
AppWidgetUpdateHandler.createInstance().updateAllWidgets(this);
NotificationUpdateService.updateNotification(this);
}
} |
Update initial migration to work on Python 3 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('key', models.CharField(primary_key=True, serialize=False, max_length=40)),
('created', models.DateTimeField(auto_now_add=True)),
('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')),
],
options={
},
bases=(models.Model,),
),
]
|
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('key', models.CharField(max_length=40, serialize=False, primary_key=True)),
('created', models.DateTimeField(auto_now_add=True)),
('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)),
],
options={
},
bases=(models.Model,),
),
]
|
Check if window.open succeed in DevToolsWindow | import React from 'react';
import { render } from 'react-dom';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
/**
* Puts Redux DevTools into a separate window.
* Based on https://gist.github.com/tlrobinson/1e63d15d3e5f33410ef7#gistcomment-1560218.
*/
export default function createDevToolsWindow(store) {
// Window name.
const name = 'Redux DevTools';
// Give it a name so it reuses the same window.
const win = window.open(
null,
name,
'menubar=no,location=no,resizable=yes,scrollbars=no,status=no'
);
// Pop-ups are blocked by default, so it may open async
if (!win) {
console.warn(
'Couldn\'t open the dev Tools, probably the popup window ' +
'was blocked, please enable the popup window for the current page.\n'
);
return;
}
// Reload in case it's reusing the same window with the old content.
win.location.reload();
// Set visible Window title.
win.document.title = name;
// Wait a little bit for it to reload, then render.
setTimeout(() => render(
<DebugPanel top right bottom left>
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>,
win.document.body.appendChild(document.createElement('div'))
), 10);
}
| import React from 'react';
import { render } from 'react-dom';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
/**
* Puts Redux DevTools into a separate window.
* Based on https://gist.github.com/tlrobinson/1e63d15d3e5f33410ef7#gistcomment-1560218.
*/
export default function createDevToolsWindow(store) {
// Window name.
const name = 'Redux DevTools';
// Give it a name so it reuses the same window.
const win = window.open(
null,
name,
'menubar=no,location=no,resizable=yes,scrollbars=no,status=no'
);
// Reload in case it's reusing the same window with the old content.
win.location.reload();
// Set visible Window title.
win.document.title = name;
// Wait a little bit for it to reload, then render.
setTimeout(() => render(
<DebugPanel top right bottom left>
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>,
win.document.body.appendChild(document.createElement('div'))
), 10);
}
|
Fix a packaging bug and make sure we also include templates directory. | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
package_data={
'st2api': ['templates/*.html']
},
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
| # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
|
Update Dotenv config to the new version | <?php
declare(strict_types=1);
/*
* This file is part of gpupo/submarino-sdk
* Created by Gilmar Pupo <contact@gpupo.com>
* For the information of copyright and license you should read the file
* LICENSE which is distributed with this source code.
* Para a informação dos direitos autorais e de licença você deve ler o arquivo
* LICENSE que é distribuído com este código-fonte.
* Para obtener la información de los derechos de autor y la licencia debe leer
* el archivo LICENSE que se distribuye con el código fuente.
* For more information, see <https://opensource.gpupo.com/>.
*
*/
use Symfony\Component\Dotenv\Dotenv;
if (!class_exists('\Gpupo\Common\Console\Application')) {
require __DIR__.'/../vendor/autoload.php';
}
if (!class_exists(Dotenv::class)) {
throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
// load all the .env files
(new Dotenv(true))->loadEnv(dirname(__DIR__).'/.env');
| <?php
declare(strict_types=1);
/*
* This file is part of gpupo/submarino-sdk
* Created by Gilmar Pupo <contact@gpupo.com>
* For the information of copyright and license you should read the file
* LICENSE which is distributed with this source code.
* Para a informação dos direitos autorais e de licença você deve ler o arquivo
* LICENSE que é distribuído com este código-fonte.
* Para obtener la información de los derechos de autor y la licencia debe leer
* el archivo LICENSE que se distribuye con el código fuente.
* For more information, see <https://opensource.gpupo.com/>.
*
*/
use Symfony\Component\Dotenv\Dotenv;
if (!class_exists('\Gpupo\Common\Console\Application')) {
require __DIR__.'/../vendor/autoload.php';
}
if (!class_exists(Dotenv::class)) {
throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
// load all the .env files
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
|
Fix validation messages in category | <?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Validator;
class Category extends Model {
protected $fillable = ['name'];
private static $messages = [
// name messages
'name.required' => 'El nombre es requerido',
'name.unique' => 'Ya existe una categoría con ese nombre',
'name.alpha' => 'El nombre no puede contener números ni símbolos',
'name.max' => 'El nombre debe tener menos de :max caracteres',
'name.min' => 'El nombre debe tener al menos :min caracteres',
];
private static $rulesForCreation = [
'name' => 'required|alpha|min:4|max:50|unique:categories,name'
];
public static function validate($all) {
$rules = self::$rulesForCreation;
$messages = self::$messages;
return Validator::make($all, $rules, $messages);
}
public static function validateUpdate($all) {
$rulestemp = self::$rulesForCreation;
$messages = self::$messages;
$rulestemp['name'] = $rulestemp['name'].','.$all['id'];
return Validator::make($all, $rulestemp, $messages);
}
//
public function articles() {
return $this->hasMany('App\Article');
}
}
| <?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Validator;
class Category extends Model {
protected $fillable = ['name'];
private static $messages = [
// name messages
'name.required' => 'El nombre es requerido',
'name.alpha' => 'El nombre no puede contener números ni símbolos',
'name.max' => 'El nombre debe tener menos de :max caracteres',
'name.min' => 'El nombre debe tener al menos :min caracteres',
];
private static $rulesForCreation = [
'name' => 'required|alpha|min:4|max:50|unique:categories,name'
];
public static function validate($all) {
$rules = self::$rulesForCreation;
$messages = self::$messages;
return Validator::make($all, $rules, $messages);
}
public static function validateUpdate($all) {
$rulestemp = self::$rulesForCreation;
$messages = self::$messages;
$rulestemp['name'] = 'required|alpha|min:4|max:50|unique:categories,name,'.$all['id'];
return Validator::make($all, $rulestemp, $messages);
}
//
public function articles() {
return $this->hasMany('App\Article');
}
}
|
Use fail signal in fail_archive_on_error decorator | import functools
from framework.exceptions import HTTPError
from website.project.decorators import _inject_nodes
from website.archiver import ARCHIVER_UNCAUGHT_ERROR
from website.archiver import signals
def fail_archive_on_error(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except HTTPError as e:
_inject_nodes(kwargs)
registration = kwargs['node']
signals.send.archive_fail(
registration,
ARCHIVER_UNCAUGHT_ERROR,
[str(e)]
)
return wrapped
| import functools
from framework.exceptions import HTTPError
from website.project.decorators import _inject_nodes
from website.archiver import ARCHIVER_UNCAUGHT_ERROR
from website.archiver import utils
def fail_archive_on_error(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except HTTPError as e:
_inject_nodes(kwargs)
registration = kwargs['node']
utils.handle_archive_fail(
ARCHIVER_UNCAUGHT_ERROR,
registration.registered_from,
registration,
registration.registered_user,
str(e)
)
return wrapped
|
Read Key from correct directory | const path = require('path')
const fs = require('fs')
const KEY = fs.readFileSync(path.join(__dirname, '.KEY'), 'utf-8')
/*
* Dota Discord Bot
*
* Commando Docs: https://discord.js.org/#/docs/commando/master/general/welcome
*/
const Commando = require('discord.js-commando')
const bot = new Commando.Client({
owner: '209050492330967040'
})
bot.registry
// Registers your custom command groups
.registerGroups([
['system', 'System Bot Commands'],
['dota', 'OpenDota Commands'],
['fun', 'Random Commands']
])
// Registers all built-in groups, commands, and argument types
.registerDefaults()
// Registers all of your commands in the ./commands/ directory
.registerCommandsIn(path.join(__dirname, 'commands'))
bot.on('disconnect', function (msg, code) {
if (code === 0) return console.error(msg)
bot.login(KEY)
})
bot.on('ready', () => {
bot.user.setPresence({ game: { name: 'DOTA 2', type: 0 } })
console.log(`Logged in as ${bot.user.tag}!`)
})
bot.login(KEY)
| const path = require('path')
const fs = require('fs')
const KEY = fs.readFileSync('./.KEY', 'utf-8')
/*
* Dota Discord Bot
*
* Commando Docs: https://discord.js.org/#/docs/commando/master/general/welcome
*/
const Commando = require('discord.js-commando')
const bot = new Commando.Client({
owner: '209050492330967040'
})
bot.registry
// Registers your custom command groups
.registerGroups([
['system', 'System Bot Commands'],
['dota', 'OpenDota Commands'],
['fun', 'Random Commands']
])
// Registers all built-in groups, commands, and argument types
.registerDefaults()
// Registers all of your commands in the ./commands/ directory
.registerCommandsIn(path.join(__dirname, 'commands'))
bot.on('disconnect', function (msg, code) {
if (code === 0) return console.error(msg)
bot.login(KEY)
})
bot.on('ready', () => {
bot.user.setPresence({ game: { name: 'DOTA 2', type: 0 } })
console.log(`Logged in as ${bot.user.tag}!`)
})
bot.login(KEY)
|
Fix callbacks not being a function | /**
* class Github
*
* A Node.JS module, which provides an object oriented wrapper for the GitHub v3 API.
*
* Copyright 2012 Cloud9 IDE, Inc.
*
* This product includes software developed by
* Cloud9 IDE, Inc (http://c9.io).
*
* Author: Mike de Boer <info@mikedeboer.nl>
**/
"use strict";
var Fs = require("fs");
var Util = require("./../../util");
var error = require("./../../error");
var GithubHandler = module.exports = function(client) {
this.client = client;
this.routes = JSON.parse(Fs.readFileSync(__dirname + "/routes.json", "utf8"));
};
var proto = {
sendError: function(err, block, msg, callback) {
if (this.client.debug)
Util.log(err, block, msg.user, "error");
if (typeof err == "string")
err = new error.InternalServerError(err);
if (callback && typeof(callback) === "function")
callback(err);
}
};
["gists", "gitdata", "issues", "authorization", "orgs", "statuses", "pullRequests", "repos", "user", "events", "releases", "search", "markdown", "gitignore", "misc"].forEach(function(api) {
Util.extend(proto, require("./" + api));
});
GithubHandler.prototype = proto;
| /**
* class Github
*
* A Node.JS module, which provides an object oriented wrapper for the GitHub v3 API.
*
* Copyright 2012 Cloud9 IDE, Inc.
*
* This product includes software developed by
* Cloud9 IDE, Inc (http://c9.io).
*
* Author: Mike de Boer <info@mikedeboer.nl>
**/
"use strict";
var Fs = require("fs");
var Util = require("./../../util");
var error = require("./../../error");
var GithubHandler = module.exports = function(client) {
this.client = client;
this.routes = JSON.parse(Fs.readFileSync(__dirname + "/routes.json", "utf8"));
};
var proto = {
sendError: function(err, block, msg, callback) {
if (this.client.debug)
Util.log(err, block, msg.user, "error");
if (typeof err == "string")
err = new error.InternalServerError(err);
if (callback)
callback(err);
}
};
["gists", "gitdata", "issues", "authorization", "orgs", "statuses", "pullRequests", "repos", "user", "events", "releases", "search", "markdown", "gitignore", "misc"].forEach(function(api) {
Util.extend(proto, require("./" + api));
});
GithubHandler.prototype = proto;
|
Add Route Model Binding for "logs" | <?php namespace ImguBox\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Routing\Router;
use ImguBox\Log;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'ImguBox\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
$router->model('logs', Log::class);
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
}
}
| <?php namespace ImguBox\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'ImguBox\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
//
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
}
}
|
Revert change to foreach order and use an isset() call instead. | <?php
namespace li3_fake_model\extensions\data\relationships;
class HasOne extends Relation {
public function appendData() {
$foreignField = current($this->meta['key']);
$currentField = key($this->meta['key']);
$fieldName = $this->meta['fieldName'];
foreach ($this->results() as $result) {
foreach ($this->data as $data) {
if (is_array($data->{$currentField}) && in_array($result->{$foreignField}, $data->{$currentField})) {
if (!isset($data->relData[$fieldName])) $data->relData[$fieldName] = $result;
} else if ($result->{$foreignField} == $data->{$currentField}) {
$data->relData[$fieldName] = $result;
}
}
}
return;
}
public function results() {
if (!empty($this->results)) {
return $this->results;
}
$class = $this->meta['to'];
return ($this->results = $class::all(
array(
current($this->meta['key']) => array(
'$in' => $this->retrieveFields(),
),
),
$this->options()
));
}
} | <?php
namespace li3_fake_model\extensions\data\relationships;
class HasOne extends Relation {
public function appendData() {
$foreignField = current($this->meta['key']);
$currentField = key($this->meta['key']);
$fieldName = $this->meta['fieldName'];
foreach ($this->data as $data) {
foreach ($this->results() as $result) {
if (is_array($data->{$currentField}) && in_array($result->{$foreignField}, $data->{$currentField})) {
$data->relData[$fieldName] = $result;
break;
} else if ($result->{$foreignField} == $data->{$currentField}) {
$data->relData[$fieldName] = $result;
}
}
}
return;
}
public function results() {
if (!empty($this->results)) {
return $this->results;
}
$class = $this->meta['to'];
return ($this->results = $class::all(
array(
current($this->meta['key']) => array(
'$in' => $this->retrieveFields(),
),
),
$this->options()
));
}
} |
Add export all components in src | import * as components from './components'
import config, { setOptions } from './utils/config'
import { use, registerComponentProgrammatic } from './utils/plugins'
const Buefy = {
install(Vue, options = {}) {
// Options
setOptions(Object.assign(config, options))
// Components
for (let componentKey in components) {
Vue.use(components[componentKey])
}
// Config component
const BuefyProgrammatic = {
setOptions(options) {
setOptions(Object.assign(config, options))
}
}
registerComponentProgrammatic(Vue, '$buefy', BuefyProgrammatic)
}
}
use(Buefy)
export default Buefy
export * from './components'
| import * as components from './components'
import config, { setOptions } from './utils/config'
import { use, registerComponentProgrammatic } from './utils/plugins'
const Buefy = {
install(Vue, options = {}) {
// Options
setOptions(Object.assign(config, options))
// Components
for (let componentKey in components) {
Vue.use(components[componentKey])
}
// Config component
const BuefyProgrammatic = {
setOptions(options) {
setOptions(Object.assign(config, options))
}
}
registerComponentProgrammatic(Vue, '$buefy', BuefyProgrammatic)
}
}
use(Buefy)
export default Buefy
|
examples: Add notice of openshift 2 shutdown
References:
* Issue: https://github.com/yagop/node-telegram-bot-api/issues/426 | /**
* This example demonstrates setting up webhook
* on the OpenShift platform.
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* NOTE:
*
* Openshift 2 has been shut down.
*
* This example is kept here for historical/educational purposes.
* No changes are expected to be made to the source code below.
*
* See https://github.com/yagop/node-telegram-bot-api/issues/426 for
* more information.
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('../..');
// See https://developers.openshift.com/en/node-js-environment-variables.html
const options = {
webHook: {
port: process.env.OPENSHIFT_NODEJS_PORT,
host: process.env.OPENSHIFT_NODEJS_IP,
// you do NOT need to set up certificates since OpenShift provides
// the SSL certs already (https://<app-name>.rhcloud.com)
},
};
// OpenShift routes from port :443 to OPENSHIFT_NODEJS_PORT
const domain = process.env.OPENSHIFT_APP_DNS;
const url = `${domain}:443`;
const bot = new TelegramBot(TOKEN, options);
// This informs the Telegram servers of the new webhook.
// Note: we do not need to pass in the cert, as it already provided
bot.setWebHook(`${url}/bot${TOKEN}`);
// Just to ping!
bot.on('message', function onMessage(msg) {
bot.sendMessage(msg.chat.id, 'I am alive on OpenShift!');
});
| /**
* This example demonstrates setting up webhook
* on the OpenShift platform.
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('../..');
// See https://developers.openshift.com/en/node-js-environment-variables.html
const options = {
webHook: {
port: process.env.OPENSHIFT_NODEJS_PORT,
host: process.env.OPENSHIFT_NODEJS_IP,
// you do NOT need to set up certificates since OpenShift provides
// the SSL certs already (https://<app-name>.rhcloud.com)
},
};
// OpenShift routes from port :443 to OPENSHIFT_NODEJS_PORT
const domain = process.env.OPENSHIFT_APP_DNS;
const url = `${domain}:443`;
const bot = new TelegramBot(TOKEN, options);
// This informs the Telegram servers of the new webhook.
// Note: we do not need to pass in the cert, as it already provided
bot.setWebHook(`${url}/bot${TOKEN}`);
// Just to ping!
bot.on('message', function onMessage(msg) {
bot.sendMessage(msg.chat.id, 'I am alive on OpenShift!');
});
|
Bump to get everything back where it should be | #!/usr/bin/env python
from setuptools import setup
import os
__version__ = '0.1.5'
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(name='ftpretty',
version=__version__,
description='Pretty FTP wrapper',
long_description=(read('README.rst') + '\n\n' +
read('HISTORY.rst') + '\n\n' +
read('AUTHORS.rst')),
license='MIT',
author='Rob Harrigan',
author_email='harrigan.rob@gmail.com',
url='https://github.com/codebynumbers/ftpretty/',
download_url='https://github.com/codebynumbers/ftpretty/tarball/%s' % __version__,
py_modules=['ftpretty'],
)
| #!/usr/bin/env python
from setuptools import setup
import os
__version__ = '0.1.4'
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(name='ftpretty',
version=__version__,
description='Pretty FTP wrapper',
long_description=(read('README.rst') + '\n\n' +
read('HISTORY.rst') + '\n\n' +
read('AUTHORS.rst')),
license='MIT',
author='Rob Harrigan',
author_email='harrigan.rob@gmail.com',
url='https://github.com/codebynumbers/ftpretty/',
download_url='https://github.com/codebynumbers/ftpretty/tarball/%s' % __version__,
py_modules=['ftpretty'],
)
|
Create a map of hosted files at client startup | import dir from 'node-dir';
import watch from 'watch';
import path from 'path';
import commandLineArgs from 'command-line-args';
const cli = commandLineArgs([
{
name: 'dir',
alias: 'd',
type: String
}
]);
const options = cli.parse();
const hostedFiles = {};
function processFile(file) {
const [artist, album, songFile] = path.relative(options.dir, file).split(path.sep);
hostedFiles[artist] = hostedFiles[artist] || {};
hostedFiles[artist][album] = hostedFiles[artist][album] || [];
hostedFiles[artist][album].push(songFile);
}
dir.files(options.dir, function(err, files) {
if (err) {
console.log(err);
return;
}
if (files) {
files.forEach((file) => {
processFile(file);
});
}
console.log(hostedFiles);
});
watch.createMonitor(options.dir, function(monitor) {
monitor.on('created', function(file) {
console.log('adding a new file:', file);
});
monitor.on('removed', function(file) {
console.log('removing file:', file);
});
});
| import dir from 'node-dir';
import watch from 'watch';
import path from 'path';
import commandLineArgs from 'command-line-args';
const cli = commandLineArgs([
{
name: 'dir',
alias: 'd',
type: String
}
]);
const options = cli.parse();
function processFile(file) {
console.log('file:', file);
const [artist, album, songFile] = path.relative(options.dir, file).split(path.sep);
console.log('artist:', artist);
console.log('album:', album);
console.log('song file:', songFile);
}
dir.files(options.dir, function(err, files) {
if (err) {
console.log(err);
return;
}
if (files) {
files.forEach((file) => {
processFile(file);
});
}
});
watch.createMonitor(options.dir, function(monitor) {
monitor.on('created', function(file) {
processFile(file);
});
monitor.on('removed', function(file) {
processFile(file);
});
});
|
Update saveStateIsNeeded parameters in viewDoneCommand | package seedu.taskitty.logic.commands;
import java.util.Set;
/**
* Finds and lists all tasks in task manager whose name contains any of the argument keywords.
* Keyword matching is case sensitive.
*/
public class ViewDoneCommand extends Command {
public static final String COMMAND_WORD = "viewdone";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": view all previously marked as done tasks. "
+ "Example: " + COMMAND_WORD;
public ViewDoneCommand() {
}
@Override
public CommandResult execute() {
model.updateFilteredDoneList();
return new CommandResult(getMessageForTaskListShownSummary(model.getTaskList().size()));
}
@Override
public void saveStateIfNeeded(String commandText) {
model.saveState(commandText);
}
}
| package seedu.taskitty.logic.commands;
import java.util.Set;
/**
* Finds and lists all tasks in task manager whose name contains any of the argument keywords.
* Keyword matching is case sensitive.
*/
public class ViewDoneCommand extends Command {
public static final String COMMAND_WORD = "viewdone";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": view all previously marked as done tasks. "
+ "Example: " + COMMAND_WORD;
public ViewDoneCommand() {
}
@Override
public CommandResult execute() {
model.updateFilteredDoneList();
return new CommandResult(getMessageForTaskListShownSummary(model.getTaskList().size()));
}
@Override
public void saveStateIfNeeded() {
model.saveState();
}
}
|
Use the old values for resource names
The logic here is that anything below v3 will use the old resources, after 3.0, the resources will carry a version number in their name. | 'use strict';
const fsx = require('./fs-additions');
const path = require('path');
const root = require('find-root');
const _ = require('lodash');
// Information about LT itself
const pkg = require('../../package.json');
const majorVersion = pkg.version ? pkg.version.split('.')[0] : 'unknown';
/**
* Helper for loading config file of a project
*/
// Load configuration file from disk (if one exists)
// Default values
let result = {
project: {},
lambda: {
runtime: 'nodejs'
},
aws: {
region: 'us-east-1',
stage: 'dev'
},
tools: {
name: pkg.name,
version: pkg.version,
majorVersion: majorVersion,
resources: {
iamRole: 'lambda-tools-helper',
apiGateway: 'lambda-tools-api-gateway-resource'
}
}
};
// Config file is assumed to be at "package root"
try {
const rootPath = root(process.cwd());
const configPath = path.resolve(rootPath, '.lambda-tools-rc.json');
if (fsx.fileExists(configPath)) {
result = _.merge(result, fsx.readJSONFileSync(configPath));
}
} catch (err) {
// Ignore
}
module.exports = result;
| 'use strict';
const fsx = require('./fs-additions');
const path = require('path');
const root = require('find-root');
const _ = require('lodash');
// Information about LT itself
const pkg = require('../../package.json');
const majorVersion = pkg.version ? pkg.version.split('.')[0] : 'unknown';
const resourcePrefix = _.compact([pkg.name, majorVersion]).join('-');
/**
* Helper for loading config file of a project
*/
// Load configuration file from disk (if one exists)
// Default values
let result = {
project: {},
lambda: {
runtime: 'nodejs'
},
aws: {
region: 'us-east-1',
stage: 'dev'
},
tools: {
name: pkg.name,
version: pkg.version,
majorVersion: majorVersion,
resources: {
iamRole: [resourcePrefix, 'resource'].join('-'),
apiGateway: [resourcePrefix, 'api-gateway'].join('-')
}
}
};
// Config file is assumed to be at "package root"
try {
const rootPath = root(process.cwd());
const configPath = path.resolve(rootPath, '.lambda-tools-rc.json');
if (fsx.fileExists(configPath)) {
result = _.merge(result, fsx.readJSONFileSync(configPath));
}
} catch (err) {
// Ignore
}
module.exports = result;
|
Implement of Cantor Paring Function | # -*- coding:utf-8 -*-
"""
Floyd's cycle-finding algorithm
http://en.wikipedia.org/wiki/Cycle_detection
http://www.siafoo.net/algorithm/10
"""
def floyd(top):
"""
>>> floyd([1,2,3,4])
False
>>> floyd([1,2,1,2,1])
True
>>> floyd([1,2,3,1,2,3,1])
True
>>> floyd([1,2,3,1,2,3,1,2,3,1])
True
>>> floyd(["A","B","A","B","A"])
True
"""
tortoise = top
hare = top
while True:
# Is Hare at End?
if not hare[1:]:
return False # NO LOOP
hare = hare[1:] # Increment hare
# Is Hare at End?
if not hare[1:]:
return False # NO LOOP
hare = hare[1:] # Increment Hare Again
tortoise = tortoise[1:]
# Did Hare Meet Tortoise?
if hare[0] == tortoise[0]:
return True # LOOP!
if __name__ == "__main__":
import doctest
doctest.testmod()
| #!-*- coding:utf-8 -*-
"""
Floyd's cycle-finding algorithm
http://en.wikipedia.org/wiki/Cycle_detection
http://www.siafoo.net/algorithm/10
"""
def floyd(top):
"""
>>> floyd([1,2,3,4])
False
>>> floyd([1,2,1,2,1])
True
>>> floyd([1,2,3,1,2,3,1])
True
>>> floyd([1,2,3,1,2,3,1,2,3,1])
True
>>> floyd(["A","B","A","B","A"])
True
"""
tortoise = top
hare = top
while True:
# Is Hare at End?
if not hare[1:]:
return False # NO LOOP
hare = hare[1:] # Increment hare
# Is Hare at End?
if not hare[1:]:
return False # NO LOOP
hare = hare[1:] # Increment Hare Again
tortoise = tortoise[1:]
# Did Hare Meet Tortoise?
if hare[0] == tortoise[0]:
return True # LOOP!
if __name__ == "__main__":
import doctest
doctest.testmod()
|
Fix notify2 being imported with the module | """Contains code related to notifications."""
from .constants import (DEFAULT_ICON_PATH,
DEFAULT_TIMEOUT,
ICONS_BY_STATUS)
from .formatters import format_notification_message
def send_notification(arguments, information):
"""Send the notification to the OS with a Python library.
:param arguments: The parsed arguments
:param information: The various song informations
"""
import notify2
notify2.init(arguments['application_name'])
title, text = format_notification_message(information,
title=arguments['title'],
body=arguments['body'])
notification = notify2.Notification(
title,
text,
ICONS_BY_STATUS.get('icon_path', DEFAULT_ICON_PATH)
)
notification.set_urgency(arguments.get('urgency', notify2.URGENCY_LOW))
notification.timeout = arguments.get('timeout', DEFAULT_TIMEOUT)
notification.show()
| """Contains code related to notifications."""
import notify2
from .constants import (DEFAULT_ICON_PATH,
DEFAULT_TIMEOUT,
ICONS_BY_STATUS)
from .formatters import format_notification_message
def send_notification(arguments, information):
"""Send the notification to the OS with a Python library.
:param arguments: The parsed arguments
:param information: The various song informations
"""
notify2.init(arguments['application_name'])
title, text = format_notification_message(information,
title=arguments['title'],
body=arguments['body'])
notification = notify2.Notification(
title,
text,
ICONS_BY_STATUS.get('icon_path', DEFAULT_ICON_PATH)
)
notification.set_urgency(arguments.get('urgency', notify2.URGENCY_LOW))
notification.timeout = arguments.get('timeout', DEFAULT_TIMEOUT)
notification.show()
|
Add support for reading *.tar.zst package files | // Copyright (c) 2015, Ben Morgan. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package alpm works with parts of Arch Linux packages.
package alpm
import "strings"
// PackageGlob is a glob that should only find packages.
const PackageGlob = "-*.pkg.tar*"
// HasDatabaseFormat returns true if the filename matches a pacman package
// format that we can do anything with.
//
// Currently, only the following formats are supported:
// .db.tar.gz
//
func HasDatabaseFormat(filename string) bool {
return strings.HasSuffix(filename, ".db.tar.gz")
}
// HasPackageFormat returns true if the filename matches a pacman package
// format that we can do anything with.
//
// Currently, only the following formats are supported:
// .pkg.tar
// .pkg.tar.xz
// .pkg.tar.gz
// .pkg.tar.bz2
// .pkg.tar.zst
//
func HasPackageFormat(filename string) bool {
for _, ext := range []string{".pkg.tar", ".pkg.tar.xz", ".pkg.tar.gz", ".pkg.tar.bz2", ".pkg.tar.zst"} {
if strings.HasSuffix(filename, ext) {
return true
}
}
return false
}
| // Copyright (c) 2015, Ben Morgan. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package alpm works with parts of Arch Linux packages.
package alpm
import "strings"
// PackageGlob is a glob that should only find packages.
const PackageGlob = "-*.pkg.tar*"
// HasDatabaseFormat returns true if the filename matches a pacman package
// format that we can do anything with.
//
// Currently, only the following formats are supported:
// .db.tar.gz
//
func HasDatabaseFormat(filename string) bool {
return strings.HasSuffix(filename, ".db.tar.gz")
}
// HasPackageFormat returns true if the filename matches a pacman package
// format that we can do anything with.
//
// Currently, only the following formats are supported:
// .pkg.tar
// .pkg.tar.xz
// .pkg.tar.gz
// .pkg.tar.bz2
//
func HasPackageFormat(filename string) bool {
for _, ext := range []string{".pkg.tar", ".pkg.tar.xz", ".pkg.tar.gz", ".pkg.tar.bz2"} {
if strings.HasSuffix(filename, ext) {
return true
}
}
return false
}
|
Add same check for Interrupt that exists for Kill
[#91746998] | package ginkgomon
import (
"fmt"
"os"
"github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/tedsuo/ifrit"
)
func Invoke(runner ifrit.Runner) ifrit.Process {
process := ifrit.Background(runner)
select {
case <-process.Ready():
case err := <-process.Wait():
ginkgo.Fail(fmt.Sprintf("process failed to start: %s", err))
}
return process
}
func Interrupt(process ifrit.Process, intervals ...interface{}) {
if process != nil {
process.Signal(os.Interrupt)
Eventually(process.Wait(), intervals...).Should(Receive(), "interrupted ginkgomon process failed to exit in time")
}
}
func Kill(process ifrit.Process, intervals ...interface{}) {
if process != nil {
process.Signal(os.Kill)
Eventually(process.Wait(), intervals...).Should(Receive(), "killed ginkgomon process failed to exit in time")
}
}
| package ginkgomon
import (
"fmt"
"os"
"github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/tedsuo/ifrit"
)
func Invoke(runner ifrit.Runner) ifrit.Process {
process := ifrit.Background(runner)
select {
case <-process.Ready():
case err := <-process.Wait():
ginkgo.Fail(fmt.Sprintf("process failed to start: %s", err))
}
return process
}
func Interrupt(process ifrit.Process, intervals ...interface{}) {
process.Signal(os.Interrupt)
Eventually(process.Wait(), intervals...).Should(Receive(), "interrupted ginkgomon process failed to exit in time")
}
func Kill(process ifrit.Process, intervals ...interface{}) {
if process != nil {
process.Signal(os.Kill)
Eventually(process.Wait(), intervals...).Should(Receive(), "killed ginkgomon process failed to exit in time")
}
}
|
Use collectStyles function for server-side rendering of styles | import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
export default function HTML (props) {
const head = Helmet.rewind()
const sheet = new ServerStyleSheet()
const main = sheet.collectStyles(
<div id='react-mount' dangerouslySetInnerHTML={{ __html: props.body }} />
)
const css = sheet.getStyleElement()
return (
<html lang='en'>
<head>
<meta charSet='utf-8' />
{ props.headComponents }
{ head.title.toComponent() }
{ head.meta.toComponent() }
{ head.link.toComponent() }
<meta httpEquiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<link rel='icon' href='/favicon.ico' type='image/x-icon' />
<link rel='apple-touch-icon' sizes='600x600' href='/icon.png' type='image/x-icon' />
{ process.env.NODE_ENV === 'production' && css }
</head>
<body>
{ main }
{ props.postBodyComponents }
</body>
</html>
)
}
| import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
export default function HTML (props) {
const head = Helmet.rewind()
const sheet = new ServerStyleSheet()
const css = sheet.getStyleElement()
return (
<StyleSheetManager sheet={sheet.instance}>
<html lang='en'>
<head>
<meta charSet='utf-8' />
{ props.headComponents }
{ head.title.toComponent() }
{ head.meta.toComponent() }
{ head.link.toComponent() }
<meta httpEquiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<link rel='icon' href='/favicon.ico' type='image/x-icon' />
<link rel='apple-touch-icon' sizes='600x600' href='/icon.png' type='image/x-icon' />
{ process.env.NODE_ENV === 'production' && css }
</head>
<body>
<div id='react-mount' dangerouslySetInnerHTML={{ __html: props.body }} />
{ props.postBodyComponents }
</body>
</html>
</StyleSheetManager>
)
}
|
Enable development assets to aid debugging | var path = require('path');
var landRegistryElements = require('land-registry-elements');
/**
* Call the land registry elements pattern library to grab our assets
*/
landRegistryElements({
'mode': ((process.env.mode === 'PRODUCTION') ? 'production' : 'dev'),
'includePath': __dirname,
'destination': path.join(__dirname, 'app/assets/.land-registry-elements'),
'assetPath': '/public',
'components': [
'pages/find-property-information/landing-form',
'pages/find-property-information/search-form',
'pages/find-property-information/search-results',
'pages/find-property-information/order-confirmation',
'pages/find-property-information/summary',
'pages/find-property-information/cookies',
'pages/land-registry/error-page'
]
})
.then(function(dest) {
console.log('Assets built to', dest);
})
.catch(function(e) {
console.error(e);
});
| var path = require('path');
var landRegistryElements = require('land-registry-elements');
/**
* Call the land registry elements pattern library to grab our assets
*/
landRegistryElements({
'includePath': __dirname,
'destination': path.join(__dirname, 'app/assets/.land-registry-elements'),
'assetPath': '/public',
'components': [
'pages/find-property-information/landing-form',
'pages/find-property-information/search-form',
'pages/find-property-information/search-results',
'pages/find-property-information/order-confirmation',
'pages/find-property-information/summary',
'pages/find-property-information/cookies',
'pages/land-registry/error-page'
]
})
.then(function(dest) {
console.log('Assets built to', dest);
})
.catch(function(e) {
console.error(e);
});
|
Fix update_wordpress_user for missing email | import random
import string
from django.conf import settings
from .tasks import (
update_wordpress_user as update_wordpress_user_task,
update_wordpress_role as update_wordpress_role_task
)
def update_wordpress_user(user):
if user.email:
email = user.email
else:
random_string = ''.join(random.choice(string.ascii_lowercase) for _ in range(8))
email = random_string + '@example.com'
if not settings.ASYNC:
update_wordpress_user_task.apply((user.username, email, user.first_name, user.last_name), throw=True)
else:
update_wordpress_user_task.apply_async((user.username, email, user.first_name, user.last_name))
def update_wordpress_role(user):
if user.is_superuser:
wordpress_role = 'administrator'
elif user.groups.filter(name='wordpress_admin').exists():
wordpress_role = 'administrator'
elif user.groups.filter(name='wordpress_editor').exists():
wordpress_role = 'editor'
else:
wordpress_role = 'subscriber'
if not settings.ASYNC:
update_wordpress_role_task.apply((user.username, wordpress_role), throw=True)
else:
update_wordpress_role_task.apply_async((user.username, wordpress_role))
| from django.conf import settings
from .tasks import (
update_wordpress_user as update_wordpress_user_task,
update_wordpress_role as update_wordpress_role_task
)
def update_wordpress_user(user):
if not settings.ASYNC:
update_wordpress_user_task.apply((user.username, user.email, user.first_name, user.last_name), throw=True)
else:
update_wordpress_user_task.apply_async((user.username, user.email, user.first_name, user.last_name))
def update_wordpress_role(user):
if user.is_superuser:
wordpress_role = 'administrator'
elif user.groups.filter(name='wordpress_admin').exists():
wordpress_role = 'administrator'
elif user.groups.filter(name='wordpress_editor').exists():
wordpress_role = 'editor'
else:
wordpress_role = 'subscriber'
if not settings.ASYNC:
update_wordpress_role_task.apply((user.username, wordpress_role), throw=True)
else:
update_wordpress_role_task.apply_async((user.username, wordpress_role))
|
Handle OPTION requests for generate
Just return nothing. Chrome seems to be happy with that response. | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
print("Generating id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
|
Use sourceIds instead of hardcoded attribute name
The source_id attr just happened to work, use the sourceIds method
instead | var template = require('./default-layer-analysis-view.tpl');
/**
* View for an analysis node with a single input
*
* this.model is expected to be a analysis-definition-node-nodel
*/
module.exports = cdb.core.View.extend({
initialize: function (opts) {
if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
if (!opts.layerAnalysisViewFactory) throw new Error('layerAnalysisViewFactory is required');
this._layerDefinitionModel = opts.layerDefinitionModel;
this._layerAnalysisViewFactory = opts.layerAnalysisViewFactory;
this.model.on('change', this.render, this);
},
render: function () {
this.clearSubViews();
this.$el.html(template({
id: this.model.id,
title: this.model.get('type')
}));
var view = this._layerAnalysisViewFactory.createView(this.model.sourceIds()[0], this._layerDefinitionModel);
this.addView(view);
this.$el.append(view.render().el);
return this;
}
});
| var template = require('./default-layer-analysis-view.tpl');
/**
* View for an analysis node with a single input
*
* this.model is expected to be a analysis-definition-node-nodel
*/
module.exports = cdb.core.View.extend({
initialize: function (opts) {
if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
if (!opts.layerAnalysisViewFactory) throw new Error('layerAnalysisViewFactory is required');
this._layerDefinitionModel = opts.layerDefinitionModel;
this._layerAnalysisViewFactory = opts.layerAnalysisViewFactory;
this.model.on('change', this.render, this);
},
render: function () {
this.clearSubViews();
this.$el.html(template({
id: this.model.id,
title: this.model.get('type')
}));
var view = this._layerAnalysisViewFactory.createView(this.model.get('source_id'), this._layerDefinitionModel);
this.addView(view);
this.$el.append(view.render().el);
return this;
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.