text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Replace newlines with spaces for readability
|
import logging
from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput
@command
def fortune(user, channel, text):
"""Show a random, hopefully interesting, adage"""
_call_fortune(user, channel)
@command
def ofortune(user, channel, text):
"""Show a random, hopefully interesting, offensive adage"""
_call_fortune(user, channel, ["-o"])
def _call_fortune(user, channel, args=[]):
"""Call the ``fortune`` executable with ``args`` (a sequence of strings).
"""
callback = partial(_send_output_to_channel, user, channel)
errback = partial(_send_error_to_channel, user, channel)
deferred = getProcessOutput("fortune", args)
deferred.addCallback(callback)
deferred.addErrback(errback)
deferred.addErrback(logging.error)
def _send_output_to_channel(user, channel, text):
msg(channel, "%s: %s" %(user, text.replace("\n"," ")))
def _send_error_to_channel(user, channel, exception):
msg(channel, "%s: Sorry, no fortune for you today! Details are in the log." % user)
return exception
|
import logging
from functools import partial
from lala.util import command, msg
from twisted.internet.utils import getProcessOutput
@command
def fortune(user, channel, text):
"""Show a random, hopefully interesting, adage"""
_call_fortune(user, channel)
@command
def ofortune(user, channel, text):
"""Show a random, hopefully interesting, offensive adage"""
_call_fortune(user, channel, ["-o"])
def _call_fortune(user, channel, args=[]):
"""Call the ``fortune`` executable with ``args`` (a sequence of strings).
"""
callback = partial(_send_output_to_channel, user, channel)
errback = partial(_send_error_to_channel, user, channel)
deferred = getProcessOutput("fortune", args)
deferred.addCallback(callback)
deferred.addErrback(errback)
deferred.addErrback(logging.error)
def _send_output_to_channel(user, channel, text):
msg(channel, "%s: %s" %(user, text.replace("\n","")))
def _send_error_to_channel(user, channel, exception):
msg(channel, "%s: Sorry, no fortune for you today! Details are in the log." % user)
return exception
|
Improve mapUrl filter. Replace whitespace with %20C.
|
'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}])
.filter('mapUrl', function() {
return function(e) {
var str = "";
for (var i=0;i<e.length;i++) {
str += typeof e[i].name === 'undefined' ||
e[i].name.localeCompare('') === 0 ?
e[i].latitude + ',' + e[i].longitude + '%7C' :
e[i].name + '%7C';
}
str = str.replace(/ /g, '%20C');
console.log(str);
return str.replace(/%7C$/, '');
};
});
|
'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}])
.filter('mapUrl', function() {
return function(e) {
var str = "";
for (var i=0;i<e.length;i++) {
str += typeof e[i].name === 'undefined' ||
e[i].name.localeCompare('') === 0 ?
e[i].latitude + ',' + e[i].longitude + '%7C' :
e[i].name + '%7C';
}
return str;
};
});
|
Use IRC style symbols instead of weird mix of IRC symbols and shell symbols.
|
<?php
function ircReport($stuff)
{
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port"));
socket_write($sock, $stuff."\n");
socket_close($sock);
}
function ircUserColor($name, $gender, $power) {
$gColors = array(0 => 12, 1 => 13, 2 => '02');
$pChars = array(1 => "%", 2 => "@", 3 => "&", 4 => "~", 5 => "+");
$color = $gColors[$gender];
if ($power > 0)
$powerChar = $pChars[$power];
else
$powerChar = "";
if ($power === -1)
$color = 14;
else if ($power === 5)
$color = 4;
return "\x0314" . $powerChar . "\x03" . $color . $name;
}
function ircColor($c)
{
return sprintf('%02d', $c);
}
|
<?php
function ircReport($stuff)
{
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port"));
socket_write($sock, $stuff."\n");
socket_close($sock);
}
function ircUserColor($name, $gender, $power) {
$gColors = array(0 => 12, 1 => 13, 2 => '02');
$pChars = array(1 => "+", 2 => "%", 3 => "$", 4 => "#", 5 => ">");
$color = $gColors[$gender];
if ($power > 0)
$powerChar = $pChars[$power];
else
$powerChar = "";
if ($power === -1)
$color = 14;
else if ($power === 5)
$color = 4;
return "\x0314" . $powerChar . "\x03" . $color . $name;
}
function ircColor($c)
{
return sprintf('%02d', $c);
}
|
Complete alias list test case
|
package seedu.todo.guitests;
import static org.junit.Assert.*;
import org.junit.Test;
import seedu.todo.guitests.guihandles.AliasItemHandle;
import seedu.todo.models.Task;
// @@author A0139812A
public class AliasCommandTest extends GuiTest {
@Test
public void alias_view_success() {
console.runCommand("alias");
assertTrue(aliasView.hasLoaded());
}
@Test
public void alias_toList_success() {
console.runCommand("alias list ls");
assertAliasItemVisible("list", "ls");
console.runCommand("add Buy milk");
Task testTask = new Task();
testTask.setName("Buy milk");
assertTaskVisibleAfterCmd("ls", testTask);
}
/**
* Helper function to assert that AliasItem is visible.
*/
private void assertAliasItemVisible(String aliasKey, String aliasValue) {
// Make sure we can see the Alias View.
assertTrue(aliasView.hasLoaded());
// Gets the matching AliasItem. Since it matches, if it's not null -> it definitely exists.
AliasItemHandle aliasItem = aliasView.getAliasItem(aliasKey, aliasValue);
assertNotNull(aliasItem);
}
}
|
package seedu.todo.guitests;
import static org.junit.Assert.*;
import org.junit.Test;
import seedu.todo.guitests.guihandles.AliasItemHandle;
// @@author A0139812A
public class AliasCommandTest extends GuiTest {
@Test
public void alias_view_success() {
console.runCommand("alias");
assertTrue(aliasView.hasLoaded());
}
@Test
public void alias_toList_success() {
console.runCommand("alias list ls");
System.out.println("hello");
assertAliasItemVisible("list", "ls");
}
/**
* Helper function to assert that AliasItem is visible.
*/
private void assertAliasItemVisible(String aliasKey, String aliasValue) {
// Make sure we can see the Alias View.
assertTrue(aliasView.hasLoaded());
// Gets the matching AliasItem. Since it matches, if it's not null -> it definitely exists.
AliasItemHandle aliasItem = aliasView.getAliasItem(aliasKey, aliasValue);
assertNotNull(aliasItem);
}
}
|
Change hashing for ParticleFilter python class
|
import hoomd._hoomd as _hoomd
import numpy as np
class ParticleFilter:
def __init__(self, *args, **kwargs):
args_str = ''.join([repr(arg) if not isinstance(arg, np.ndarray)
else repr(list(arg)) for arg in args])
kwargs_str = ''.join([repr(value) if not isinstance(value, np.ndarray)
else repr(list(value))
for value in kwargs.values()])
self.args_str = args_str
self.kwargs_str = kwargs_str
_id = hash(self.__class__.__name__ + args_str + kwargs_str)
self._id = _id
def __hash__(self):
return self._id
def __eq__(self, other):
return self._id == other._id
class All(ParticleFilterID, _hoomd.ParticleFilterAll):
def __init__(self):
ParticleFilterID.__init__(self)
_hoomd.ParticleFilterAll(self)
|
import hoomd._hoomd as _hoomd
class ParticleFilterID:
def __init__(self, *args, **kwargs):
args_str = ''.join([str(arg) for arg in args])
kwargs_str = ''.join([str(value)for value in kwargs.values()])
self.args_str = args_str
self.kwargs_str = kwargs_str
_id = hash(self.__class__.__name__ + args_str + kwargs_str)
self._id = _id
def __hash__(self):
return self._id
def __eq__(self, other):
return self._id == other._id
class All(ParticleFilterID, _hoomd.ParticleFilterAll):
def __init__(self):
ParticleFilterID.__init__(self)
_hoomd.ParticleFilterAll(self)
|
Add link to Firefox’s I2P
|
/**
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Name: Threads
// Proposal: https://github.com/webassembly/threads
import inlineModule from "wat2wasm:--enable-threads:./module.wat";
import { testCompile } from "../../helpers.js";
export default async function() {
try {
// Test for availability of shared Wasm memory
new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
// Test for transferability of SABs (needed for Firefox)
// https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ
await new Promise(resolve => {
const sab = new SharedArrayBuffer(1);
const { port1, port2 } = new MessageChannel();
port2.onmessage = resolve;
port1.postMessage(sab);
});
// Test for atomics
await testCompile(inlineModule);
return true;
} catch (e) {
return false;
}
}
|
/**
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Name: Threads
// Proposal: https://github.com/webassembly/threads
import inlineModule from "wat2wasm:--enable-threads:./module.wat";
import { testCompile } from "../../helpers.js";
export default async function() {
try {
// Test for availability of shared Wasm memory
new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
// Test for transferability of SABs (needed for Firefox)
await new Promise(resolve => {
const sab = new SharedArrayBuffer(1);
const { port1, port2 } = new MessageChannel();
port2.onmessage = resolve;
port1.postMessage(sab);
});
// Test for atomics
await testCompile(inlineModule);
return true;
} catch (e) {
return false;
}
}
|
Change the name of the endpoint
|
/**
* Created by Neil on 29/09/13.
*/
function signin(mode, callback, clientID) { // clientID filled in by template, immediate = true because we should not need to ask permission again
gapi.auth.authorize({client_id: clientID,
scope: ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"], immediate: true,
response_type: 'token'}, // Can't use id tokens as we can't get the user if from an id token
callback);
}
function userAuthed() {
var request =
gapi.client.oauth2.userinfo.get().execute(function (resp) { // Check the token by calling userinfo, if it's ok call our end point
if (!resp.code) {
var token = gapi.auth.getToken();
gapi.client.mylatitude.locations.latest().execute(function (resp) { // this does not do anything yet it's just a test.
// console.log(resp);
});
}
});
}
|
/**
* Created by Neil on 29/09/13.
*/
function signin(mode, callback, clientID) { // clientID filled in by template, immediate = true because we should not need to ask permission again
gapi.auth.authorize({client_id: clientID,
scope: ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"], immediate: true,
response_type: 'token'}, // Can't use id tokens as we can't get the user if from an id token
callback);
}
function userAuthed() {
var request =
gapi.client.oauth2.userinfo.get().execute(function (resp) { // Check the token by calling userinfo, if it's ok call our end point
if (!resp.code) {
var token = gapi.auth.getToken();
gapi.client.mylatitude.location.last().execute(function (resp) { // this does not do anything yet it's just a test.
// console.log(resp);
});
}
});
}
|
Change 'Address App' to Task Manager'
|
package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.task.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Task Manager\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/taskmanager.xml\n" +
"TaskManager name : MyTaskManager";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.task.commons.core.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Address App\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/taskmanager.xml\n" +
"TaskManager name : MyTaskManager";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
Add call to random.seed() and change print statement to print function.
|
# -*- coding: utf-8 -*-
import random
import webbrowser
from pythonkc_meetups import PythonKCMeetups
from optparse import OptionParser
def raffle_time(api_key=None, event_id=None):
client = PythonKCMeetups(api_key=api_key)
attendees = client.get_event_attendees(event_id)
random.seed()
random.shuffle(attendees)
winner = random.choice(attendees)
if winner.photo:
webbrowser.open_new(winner.photo.url)
print("\n\nAnd the winner is, %s \n\n" % winner.name)
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-k", "--key", help="api key for meetup.com", dest="api_key", type="string")
parser.add_option("-e", "--event_id", help="event id from meetup.com", dest="event_id",
type="int")
options, args = parser.parse_args()
raffle_time(api_key=options.api_key, event_id=options.event_id)
|
# -*- coding: utf-8 -*-
import random
import webbrowser
from pythonkc_meetups import PythonKCMeetups
from optparse import OptionParser
def raffle_time(api_key=None, event_id=None):
client = PythonKCMeetups(api_key=api_key)
attendees = client.get_event_attendees(event_id)
random.shuffle(attendees)
winner = random.choice(attendees)
if winner.photo:
webbrowser.open_new(winner.photo.url)
print "\n\nAnd the winner is, %s \n\n" % winner.name
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-k", "--key", help="api key for meetup.com", dest="api_key", type="string")
parser.add_option("-e", "--event_id", help="event id from meetup.com", dest="event_id",
type="int")
options, args = parser.parse_args()
raffle_time(api_key=options.api_key, event_id=options.event_id)
|
Change navbar to be static at top of app.
|
import React from 'react';
import { Link } from 'react-router-dom';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
const Navigation = (props) => {
return (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">
Recipeas
</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem>
<a href="https://github.com/phuchle/recipeas">
Source Code
</a>
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
export default Navigation;
|
import React from 'react';
import { Link } from 'react-router-dom';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
const Navigation = (props) => {
return (
<Navbar fixedTop={true}>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">
Recipeas
</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem>
<a href="https://github.com/phuchle/recipeas">
Source Code
</a>
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
export default Navigation;
|
Add methods for converting resolution independent pixels (dp) to real pixels and the other way round.
|
/*
* *
* * LayoutUtil.java
* * as part of mkcommons-android
* *
* * Created by michaelkuck, last updated on 7/25/14 1:00 PM
* * Unless otherwise stated in a separate LICENSE file for this project
* * or agreed via contract, all rights reserved by the author.
*
*/
package com.michael_kuck.android.mkcommons;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.TypedValue;
/**
* Created by michaelkuck on 7/25/14.
*/
public class LayoutUtil {
public static float pixelFromDp(final float dpPixel) {
final Resources resources = Android.getApplication().getResources();
final float pixel = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpPixel, resources.getDisplayMetrics());
return pixel;
}
public static int pixelFromDp(final int dpPixel) {
return (int) pixelFromDp((float)dpPixel);
}
public static PointF pixelsFromDpPoint(final PointF dpPixels) {
final PointF pixels = new PointF(pixelFromDp(dpPixels.x), pixelFromDp(dpPixels.y));
return pixels;
}
public static Point pixelsFromDpPoint(final Point dpPixels) {
final Point pixels = new Point(pixelFromDp(dpPixels.x), pixelFromDp(dpPixels.y));
return pixels;
}
}
|
/*
* *
* * LayoutUtil.java
* * as part of mkcommons-android
* *
* * Created by michaelkuck, last updated on 7/25/14 1:00 PM
* * Unless otherwise stated in a separate LICENSE file for this project
* * or agreed via contract, all rights reserved by the author.
*
*/
package com.michael_kuck.android.mkcommons;
import android.content.Context;
import android.graphics.Point;
import android.util.TypedValue;
/**
* Created by michaelkuck on 7/25/14.
*/
public class LayoutUtil {
public static Point dpToP(final Context context, final Point point) {
int x = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, point.x, context.getResources().getDisplayMetrics());
int y = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, point.y, context.getResources().getDisplayMetrics());
return new Point(x, y);
}
public static int dpToP(final Context context, final int pixel) {
return (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pixel, context.getResources().getDisplayMetrics());
}
}
|
Improve notifications around the remove package command
|
'use babel';
import DependenciesView from '../views/DependenciesView';
import getDependencies from '../yarn/get-dependencies';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
import addProgressNotification from '../add-progress-notification';
import path from 'path';
export default async function(projectFolderPath) {
const dependencies = await getDependencies(projectFolderPath);
const view = new DependenciesView(dependencies, selected => {
const projectFolder = path.basename(projectFolderPath);
let progress;
const options = {
onStart: () => {
progress = addProgressNotification(
`Removing ${selected} package from ${projectFolder}...`
);
}
};
yarnExec(projectFolderPath, 'remove', [selected], options)
.then(success => {
progress.dismiss();
if (!success) {
atom.notifications.addError(
`An error occurred removing the ${selected} package. See output for more information.`
);
return;
}
atom.notifications.addSuccess(
`Removed ${selected} package from ${projectFolder}`
);
})
.catch(reportError);
});
view.show();
}
|
'use babel';
import DependenciesView from '../views/DependenciesView';
import getDependencies from '../yarn/get-dependencies';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
export default async function(projectFolder) {
const dependencies = await getDependencies(projectFolder);
const view = new DependenciesView(dependencies, selected => {
const options = {
onStart: () =>
atom.notifications.addInfo(`Removing '${selected}' package...`)
};
yarnExec(projectFolder, 'remove', [selected], options)
.then(success => {
if (!success) {
atom.notifications.addError(
`An error occurred removing the '${selected}' package. See output for more information.`
);
return;
}
atom.notifications.addSuccess(
`Removed '${selected}' from package.json`
);
})
.catch(reportError);
});
view.show();
}
|
Change page target to unprotected sandbox
|
var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
fs = require( 'fs' ),
c = require( 'ansicolors' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'scribunto-console',
title: 'Module:Sandbox/CLI',
clear: true
};
function call( err, info, next, data ) {
if ( err ) {
console.error( err );
} else if ( data.type === 'error' ) {
console.error( data.message );
} else {
console.log( data.print );
}
}
function cli( input ) {
params.question = input;
client.api.call( params, call );
}
function session( err, data ) {
params.content = data;
console.log( c.green( '* The module exports are available as the variable "p", including unsaved modifications.' ) );
console.log( c.green( '* Precede a line with "=" to evaluate it as an expression, or use print().' ) );
console.log( c.green( '* Use mw.log() in module code to send messages to this console.' ) );
rl.on( 'line', cli );
}
fs.readFile( 'helloworld.lua', session );
|
var Bot = require( 'nodemw' ),
readline = require( 'readline' ),
fs = require( 'fs' ),
c = require( 'ansicolors' ),
rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} ),
client = new Bot( {
protocol: 'https',
server: 'dev.fandom.com',
path: ''
} ),
params = {
action: 'scribunto-console',
title: 'Module:Sandbox',
clear: true
};
function call( err, info, next, data ) {
if ( err ) {
console.error( err );
} else if ( data.type === 'error' ) {
console.error( data.message );
} else {
console.log( data.print );
}
}
function cli( input ) {
params.question = input;
client.api.call( params, call );
}
function session( err, data ) {
params.content = data;
console.log( c.green( '* The module exports are available as the variable "p", including unsaved modifications.' ) );
console.log( c.green( '* Precede a line with "=" to evaluate it as an expression, or use print().' ) );
console.log( c.green( '* Use mw.log() in module code to send messages to this console.' ) );
rl.on( 'line', cli );
}
fs.readFile( 'helloworld.lua', session );
|
Remove unneccessary attack action 'toggleFavorite'
|
import * as types from './types';
export const showAttack = (attackId) => {
return {
type: types.SHOW_ATTACK,
attackId
};
}
export const setAttacks = (attacks) => {
return {
type: types.SET_ATTACKS,
attacks
};
}
export const setPendingAttackEdits = (attack) => {
return {
type: types.SET_PENDING_ATTACK_EDITS,
attack
};
}
export const toggleActiveAttack = (attack) => {
return {
type: types.TOGGLE_ACTIVE_ATTACK,
attack
};
}
export const toggleEditAttack = (attack) => {
return {
type: types.TOGGLE_EDIT_ATTACK,
attack
};
}
export const updateActiveAttackInput = (input) => {
return {
type: types.UPDATE_ACTIVE_ATTACK_INPUT,
input
};
}
|
import * as types from './types';
export const favoriteAttack = (attack) => {
return {
type: types.TOGGLE_FAVORITE,
attack
};
}
export const showAttack = (attackId) => {
return {
type: types.SHOW_ATTACK,
attackId
};
}
export const setAttacks = (attacks) => {
return {
type: types.SET_ATTACKS,
attacks
};
}
export const setPendingAttackEdits = (attack) => {
return {
type: types.SET_PENDING_ATTACK_EDITS,
attack
};
}
export const toggleActiveAttack = (attack) => {
return {
type: types.TOGGLE_ACTIVE_ATTACK,
attack
};
}
export const toggleEditAttack = (attack) => {
return {
type: types.TOGGLE_EDIT_ATTACK,
attack
};
}
export const updateActiveAttackInput = (input) => {
return {
type: types.UPDATE_ACTIVE_ATTACK_INPUT,
input
};
}
|
Revert "Changing this to a release candidate."
This reverts commit a9f8afbc1c5a40d0a35e3a9757f8c96da494d35a.
|
from setuptools import setup, find_packages
GITHUB_ALERT = """**NOTE**: These are the docs for the version of envbuilder in git. For
documentation on the last release, see the `pypi_page <http://pypi.python.org/pypi/envbuilder/>`_."""
readme = open('README.rst', 'r')
unsplit_readme_text = readme.read()
split_text = [x for x in unsplit_readme_text.split('.. split here')
if x]
README_TEXT = split_text[-1]
readme.close()
setup(
name='envbuilder',
author='Jason Baker',
author_email='amnorvend@gmail.com',
version='0.2.0b2',
packages=find_packages(),
setup_requires=['nose'],
install_requires=['ConfigObj>=4.7.0', 'argparse', 'pip', 'virtualenv'],
zip_safe=False,
include_package_data=True,
entry_points = {
'console_scripts' : [
'envb = envbuilder.run:main',
'envbuilder = envbuilder.run:main'
]
},
description = "A package for automatic generation of virtualenvs",
long_description = README_TEXT,
url='http://github.com/jasonbaker/envbuilder',
)
|
from setuptools import setup, find_packages
GITHUB_ALERT = """**NOTE**: These are the docs for the version of envbuilder in git. For
documentation on the last release, see the `pypi_page <http://pypi.python.org/pypi/envbuilder/>`_."""
readme = open('README.rst', 'r')
unsplit_readme_text = readme.read()
split_text = [x for x in unsplit_readme_text.split('.. split here')
if x]
README_TEXT = split_text[-1]
readme.close()
setup(
name='envbuilder',
author='Jason Baker',
author_email='amnorvend@gmail.com',
version='0.2.0rc',
packages=find_packages(),
setup_requires=['nose'],
install_requires=['ConfigObj>=4.7.0', 'argparse', 'pip', 'virtualenv'],
zip_safe=False,
include_package_data=True,
entry_points = {
'console_scripts' : [
'envb = envbuilder.run:main',
'envbuilder = envbuilder.run:main'
]
},
description = "A package for automatic generation of virtualenvs",
long_description = README_TEXT,
url='http://github.com/jasonbaker/envbuilder',
)
|
Add coverage to some of log.py
|
import json
import logging
from unittest.mock import Mock, patch
from jsonrpcclient.log import _trim_string, _trim_values, _trim_message
def test_trim_string():
message = _trim_string("foo" * 100)
assert "..." in message
def test_trim_values():
message = _trim_values({"list": [0] * 100})
assert "..." in message["list"]
def test_trim_values_nested():
message = _trim_values({"obj": {"obj2": {"string2": "foo" * 100}}})
assert "..." in message["obj"]["obj2"]["string2"]
def test_trim_values_batch():
message = _trim_values([{"list": [0] * 100}])
assert "..." in message[0]["list"]
def test_trim_message():
message = _trim_message("foo" * 100)
assert "..." in message
|
import json
import logging
from unittest.mock import Mock, patch
from jsonrpcclient.log import _trim_string, _trim_values
def test_trim_string():
message = _trim_string("foo" * 100)
assert "..." in message
def test_trim_values():
message = _trim_values({"list": [0] * 100})
assert "..." in message["list"]
def test_trim_values_nested():
message = _trim_values({"obj": {"obj2": {"string2": "foo" * 100}}})
assert "..." in message["obj"]["obj2"]["string2"]
def test_trim_values_batch():
message = _trim_values([{"list": [0] * 100}])
assert "..." in message[0]["list"]
def test_trim_message():
message = _trim_values([{"list": [0] * 100}])
assert "..." in message[0]["list"]
|
Use [] notation in wrapper module for task management
|
from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
self.task[flow.name] = NestedWorkflow(flow)
nested = self.task[flow.name]
for port in flow.input:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
self.input[port.name] = type
self.input[port.name] >> nested.input[port.name]
for port in flow.output:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
self.output[port.name] = type
nested.output[port.name] >> self.output[port.name]
|
from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
setattr(self.task, flow.name, NestedWorkflow(flow))
nested = getattr(self.task, flow.name)
for port in flow.input:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
self.input[port.name] = type
self.input[port.name] >> nested.input[port.name]
for port in flow.output:
# Set type to same depth, but basetype of String
depth = port.type.getDepth()
if depth == 0:
type = String
else:
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
self.output[port.name] = type
nested.output[port.name] >> self.output[port.name]
|
Remove debug print in test.
|
package scraper
import (
"os"
"os/exec"
"testing"
"time"
"github.com/pachyderm/pachyderm/src/client/pkg/require"
)
func TestScraper(t *testing.T) {
require.NoError(t, exec.Command("pachctl", "create-repo", "urls").Run())
require.NoError(t, exec.Command("pachctl", "start-commit", "urls", "master").Run())
putFileCmd := exec.Command("pachctl", "put-file", "urls", "master", "urls")
urls, err := os.Open("urls")
require.NoError(t, err)
putFileCmd.Stdin = urls
require.NoError(t, putFileCmd.Run())
require.NoError(t, exec.Command("pachctl", "finish-commit", "urls", "master").Run())
require.NoError(t, exec.Command("pachctl", "create-pipeline", "-f", "scraper.json").Run())
time.Sleep(5 * time.Second)
require.NoError(t, exec.Command("pachctl", "flush-commit", "urls/master").Run())
}
|
package scraper
import (
"fmt"
"os"
"os/exec"
"testing"
"time"
"github.com/pachyderm/pachyderm/src/client/pkg/require"
)
func TestScraper(t *testing.T) {
wd, err := os.Getwd()
require.NoError(t, err)
fmt.Printf("wd: %s", wd)
require.NoError(t, exec.Command("pachctl", "create-repo", "urls").Run())
require.NoError(t, exec.Command("pachctl", "start-commit", "urls", "master").Run())
putFileCmd := exec.Command("pachctl", "put-file", "urls", "master", "urls")
urls, err := os.Open("urls")
require.NoError(t, err)
putFileCmd.Stdin = urls
require.NoError(t, putFileCmd.Run())
require.NoError(t, exec.Command("pachctl", "finish-commit", "urls", "master").Run())
require.NoError(t, exec.Command("pachctl", "create-pipeline", "-f", "scraper.json").Run())
time.Sleep(5 * time.Second)
require.NoError(t, exec.Command("pachctl", "flush-commit", "urls/master").Run())
}
|
Print player emails in migration script.
|
import store
rstore = store.RedisStore()
def populate_terminations():
for game in rstore.all_games():
rstore.set_game(game["game_id"], game["game"])
def populate_game_ids():
keys = rstore.rconn.keys("chess:games:*:game")
game_ids = [k.split(":")[-2] for k in keys]
rstore.rconn.sadd("chess:game_ids", *game_ids)
def populate_players():
keys = rstore.rconn.keys("chess:games:*:*:email")
players = set()
for k in keys:
val = rstore.rconn.get(k)
if val:
players.add(val)
print players
rstore.rconn.sadd("chess:players", *players)
|
import store
rstore = store.RedisStore()
def populate_terminations():
for game in rstore.all_games():
rstore.set_game(game["game_id"], game["game"])
def populate_game_ids():
keys = rstore.rconn.keys("chess:games:*:game")
game_ids = [k.split(":")[-2] for k in keys]
rstore.rconn.sadd("chess:game_ids", *game_ids)
def populate_players():
keys = rstore.rconn.keys("chess:games:*:*:email")
players = set()
for k in keys:
val = rstore.rconn.get(k)
if val:
players.add(k)
rstore.rconn.sadd("chess:players", *players)
|
Use string resource instead of hardcoded string
|
package fr.free.nrw.commons.nearby;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.ViewHolder;
import fr.free.nrw.commons.utils.ResourceUtils;
public class NearbyViewHolder implements ViewHolder<Place> {
@BindView(R.id.tvName) TextView tvName;
@BindView(R.id.tvDesc) TextView tvDesc;
@BindView(R.id.distance) TextView distance;
@BindView(R.id.icon) ImageView icon;
public NearbyViewHolder(View view) {
ButterKnife.bind(this, view);
}
@Override
public void bindModel(Context context, Place place) {
// Populate the data into the template view using the data object
tvName.setText(place.name);
String description = place.description;
if ( description == null || description.isEmpty() || description.equals("?")) {
description = context.getString(R.string.no_description_found);
}
tvDesc.setText(description);
distance.setText(place.distance);
icon.setImageResource(ResourceUtils.getDescriptionIcon(place.description));
}
}
|
package fr.free.nrw.commons.nearby;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.ViewHolder;
import fr.free.nrw.commons.utils.ResourceUtils;
public class NearbyViewHolder implements ViewHolder<Place> {
@BindView(R.id.tvName) TextView tvName;
@BindView(R.id.tvDesc) TextView tvDesc;
@BindView(R.id.distance) TextView distance;
@BindView(R.id.icon) ImageView icon;
public NearbyViewHolder(View view) {
ButterKnife.bind(this, view);
}
@Override
public void bindModel(Context context, Place place) {
// Populate the data into the template view using the data object
tvName.setText(place.name);
String description = place.description;
if ( description == null || description.isEmpty() || description.equals("?")) {
description = "No Description Found";
}
tvDesc.setText(description);
distance.setText(place.distance);
icon.setImageResource(ResourceUtils.getDescriptionIcon(place.description));
}
}
|
Add cors whitelist configuration to api
|
const express = require('express');
const morganLogger = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const RateLimit = require('express-rate-limit');
const cors = require('cors');
const log = require('./config/logger');
const { blogPostRoute, healthCheckRoute } = require('./routes');
const {
NODE_ENV,
PORT = 3000,
MONGODB_URI = 'mongodb://localhost:27017/blogapp',
} = process.env;
mongoose.Promise = Promise;
mongoose
.connect(MONGODB_URI)
.catch(err => log('error', err));
const app = express();
if (NODE_ENV === 'dev') app.use(morganLogger('dev'));
app.use(new RateLimit({
windowMs: 900000,
max: 100,
delayMs: 0,
}));
app.use(bodyParser.json());
const whitelist = 'https://jonnys-blog-react-front-end.herokuapp.com';
const corsOptions = {
origin(origin, callback) {
if (whitelist === origin) {
return callback(null, true);
}
return callback(new Error('Not allowed by CORS'));
},
};
app.use(cors(corsOptions));
app.use('/api', blogPostRoute);
app.use('/private', healthCheckRoute);
app.listen(PORT, () => {
log('info', `App listening on port: ${PORT}`);
});
module.exports = app;
|
const express = require('express');
const morganLogger = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const RateLimit = require('express-rate-limit');
const cors = require('cors');
const log = require('./config/logger');
const { blogPostRoute, healthCheckRoute } = require('./routes');
const {
NODE_ENV,
PORT = 3000,
MONGODB_URI = 'mongodb://localhost:27017/blogapp',
} = process.env;
mongoose.Promise = Promise;
mongoose
.connect(MONGODB_URI)
.catch(err => log('error', err));
const app = express();
if (NODE_ENV === 'dev') app.use(morganLogger('dev'));
app.use(new RateLimit({
windowMs: 900000,
max: 100,
delayMs: 0,
}));
app.use(bodyParser.json());
app.use(cors());
app.use('/api', blogPostRoute);
app.use('/private', healthCheckRoute);
app.listen(PORT, () => {
log('info', `App listening on port: ${PORT}`);
});
module.exports = app;
|
Change iOS back button color to white
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
NavigatorIOS,
StyleSheet
} from 'react-native';
import ContestListScreen from './ContestListScreen';
import { PRIMARY_COLOR } from './Constants';
import moment from 'moment-timezone'
import deLocale from 'moment/locale/de'
moment.updateLocale('de', deLocale);
class JumuNordost extends Component {
render() {
return (
<NavigatorIOS
barTintColor={PRIMARY_COLOR}
tintColor='#FFFFFF'
titleTextColor='#FFFFFF'
style={styles.nav}
translucent={false}
initialRoute={initialRoute}
/>
)
}
}
const initialRoute = {
title: 'Wettbewerbe',
component: ContestListScreen,
backButtonTitle: " "
}
const styles = StyleSheet.create({
nav: {
flex: 1
}
});
AppRegistry.registerComponent('JumuNordost', () => JumuNordost);
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
NavigatorIOS,
StyleSheet
} from 'react-native';
import ContestListScreen from './ContestListScreen';
import { PRIMARY_COLOR } from './Constants';
import moment from 'moment-timezone'
import deLocale from 'moment/locale/de'
moment.updateLocale('de', deLocale);
class JumuNordost extends Component {
render() {
return (
<NavigatorIOS
barTintColor={PRIMARY_COLOR}
titleTextColor='#FFFFFF'
style={styles.nav}
translucent={false}
initialRoute={initialRoute}
/>
)
}
}
const initialRoute = {
title: 'Wettbewerbe',
component: ContestListScreen,
backButtonTitle: " "
}
const styles = StyleSheet.create({
nav: {
flex: 1
}
});
AppRegistry.registerComponent('JumuNordost', () => JumuNordost);
|
Make test runner work with blank mysql password
|
import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"]
os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql")
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini")
|
import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql")
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini")
|
Make `initial` argument to `accumulate` optional
|
from functools import partial
from itertools import accumulate as accumulate_, chain, tee
MYPY = False
if MYPY:
from typing import Callable, Iterable, Iterator, Optional, Tuple, TypeVar
T = TypeVar('T')
filter_ = partial(filter, None) # type: Callable[[Iterator[Optional[T]]], Iterator[T]]
flatten = chain.from_iterable
def accumulate(iterable, initial=None):
# type: (Iterable[int], int) -> Iterable[int]
if initial is None:
return accumulate_(iterable)
else:
return accumulate_(chain([initial], iterable))
def pairwise(iterable):
# type: (Iterable[T]) -> Iterable[Tuple[T, T]]
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
|
from functools import partial
from itertools import accumulate as accumulate_, chain, tee
MYPY = False
if MYPY:
from typing import Callable, Iterable, Iterator, Optional, Tuple, TypeVar
T = TypeVar('T')
filter_ = partial(filter, None) # type: Callable[[Iterator[Optional[T]]], Iterator[T]]
flatten = chain.from_iterable
def accumulate(iterable, initial):
# type: (Iterable[int], int) -> Iterable[int]
if initial is None:
return accumulate_(iterable)
else:
return accumulate_(chain([initial], iterable))
def pairwise(iterable):
# type: (Iterable[T]) -> Iterable[Tuple[T, T]]
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
|
Disable random test for Jenkins
|
/*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. 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
*
* This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the
* License.
*/
package com.cloudera.oryx.common.random;
import org.apache.commons.math3.random.RandomGenerator;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.cloudera.oryx.common.OryxTest;
public final class RandomManagerRandomTest extends OryxTest {
@Override
@Before
public void initRandom() {
// specifically don't init random
}
// Not clear why this only fails on JenkinsDisable
@Ignore
@Test
public void testRandomState() {
RandomGenerator generator = RandomManager.getRandom();
double unseededValue = generator.nextDouble();
RandomManager.useTestSeed();
double seededValue = generator.nextDouble();
assertNotEquals(unseededValue, seededValue);
assertEquals(seededValue, RandomManager.getRandom().nextDouble());
}
}
|
/*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. 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
*
* This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the
* License.
*/
package com.cloudera.oryx.common.random;
import org.apache.commons.math3.random.RandomGenerator;
import org.junit.Before;
import org.junit.Test;
import com.cloudera.oryx.common.OryxTest;
public final class RandomManagerRandomTest extends OryxTest {
@Override
@Before
public void initRandom() {
// specifically don't init random
}
@Test
public void testRandomState() {
RandomGenerator generator = RandomManager.getRandom();
double unseededValue = generator.nextDouble();
RandomManager.useTestSeed();
double seededValue = generator.nextDouble();
assertNotEquals(unseededValue, seededValue);
assertEquals(seededValue, RandomManager.getRandom().nextDouble());
}
}
|
Modify parseErrorResponse to return JSON API compatible array
|
import Ember from 'ember';
import DS from 'ember-data';
const VALIDATION_ERROR_STATUSES = [400, 422];
export default DS.RESTAdapter.extend({
namespace: 'api',
isInvalid: function(status) {
return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0;
},
// Override the parseErrorResponse method from RESTAdapter
// so that we can munge the modelState into an errors collection.
// The source of the original method can be found at:
// https://github.com/emberjs/data/blob/v2.1.0/packages/ember-data/lib/adapters/rest-adapter.js#L899
parseErrorResponse: function(responseText) {
let json = this._super(responseText),
strippedErrors = {},
jsonIsObject = json && (typeof json === 'object');
if (jsonIsObject && json.message) {
delete json.message;
}
if (jsonIsObject && json.modelState) {
Object.keys(json.modelState).forEach(key => {
let newKey = Ember.String.camelize(key.substring(key.indexOf('.') + 1));
strippedErrors[newKey] = json.modelState[key];
});
json.errors = DS.errorsHashToArray(strippedErrors);
delete json.modelState;
}
return json;
}
});
|
import DS from 'ember-data';
const VALIDATION_ERROR_STATUSES = [400, 422];
export default DS.RESTAdapter.extend({
namespace: 'api',
isInvalid: function(status) {
return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0;
},
// Override the parseErrorResponse method from RESTAdapter
// so that we can munge the modelState into an errors collection.
// The source of the original method can be found at:
// https://github.com/emberjs/data/blob/v2.1.0/packages/ember-data/lib/adapters/rest-adapter.js#L899
parseErrorResponse: function(responseText) {
let json = this._super(responseText),
strippedErrors = {},
jsonIsObject = json && (typeof json === 'object');
if (jsonIsObject && json.message) {
delete json.message;
}
if (jsonIsObject && json.modelState) {
Object.keys(json.modelState).forEach(key => {
let newKey = key.substring(key.indexOf('.') + 1).camelize();
strippedErrors[newKey] = json.modelState[key];
});
json.errors = strippedErrors;
delete json.modelState;
}
return json;
}
});
|
Allow Fake Backend to take an image as the screen
|
import numpy as np
from ..core import Location
class GeistFakeBackend(object):
def __init__(self, image=None, w=800, h=600):
if image is None:
self.image = np.zeros((h, w, 3))
self.locations = [Location(0, 0, w=w, h=h, image=self.image)]
else:
if isinstance(image, basestring):
image = np.load(image)
self.image = image
h, w, _ = image.shape
self.locations = [Location(0, 0, w=w, h=h, image=self.image)]
def create_process(self, command):
pass
def actions_transaction(self):
pass
def capture_locations(self):
for loc in self.locations:
yield loc
def key_down(self, name):
pass
def key_up(self, name):
pass
def button_down(self, button_num):
pass
def button_up(self, button_num):
pass
def move(self, point):
pass
def close(self):
pass
|
import numpy as np
from ..core import Location
class GeistFakeBackend(object):
def __init__(self, w=800, h=600):
self.image = np.zeros((h, w, 3))
self.locations = [Location(0, 0, w=w, h=h, image=self.image)]
def create_process(self, command):
pass
def actions_transaction(self):
pass
def capture_locations(self):
for loc in self.locations:
yield loc
def key_down(self, name):
pass
def key_up(self, name):
pass
def button_down(self, button_num):
pass
def button_up(self, button_num):
pass
def move(self, point):
pass
def close(self):
pass
|
Improve module definition generation script
The script no longer produces unnecessary module declarations.
|
'use strict';
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var banner = require('./banner');
var dest = path.resolve(__dirname, '../dist/event-station.d.ts');
var dist = path.resolve(__dirname, '../dist');
var src = path.resolve(__dirname, '../build/dts/main.d.ts');
mkdirp(dist, function () {
fs.readFile(src, function (err, buf) {
if (err) throw err;
var declaration = '\ndeclare module "event-station" {';
var definition = buf.toString()
.replace(/(}\n)?declare module "([^"]*)" {/g, '')
.replace(/\n\s+import ([^"]+) from "([^"]+)";/g, '');
var output = banner + declaration + definition;
fs.writeFile(dest, output, function (err) {
if (err) throw err;
});
});
});
|
'use strict';
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var banner = require('./banner');
var dest = path.resolve(__dirname, '../dist/event-station.d.ts');
var dist = path.resolve(__dirname, '../dist');
var src = path.resolve(__dirname, '../build/dts/main.d.ts');
mkdirp(dist, function () {
fs.readFile(src, function (err, buf) {
if (err) throw err;
var output = banner + '\n' + buf.toString()
.replace(/declare module "/g, 'declare module "__event-station#')
.replace(/from "/g, 'from "__event-station#')
.replace(/"__event-station#main"/g, '"event-station"');
fs.writeFile(dest, output, function (err) {
if (err) throw err;
});
});
});
|
Use only android and ios browser for autoprefixer
|
var ExtractText = require('extract-text-webpack-plugin');
var LessClean = require('less-plugin-clean-css');
var HtmlFile = require('html-webpack-plugin');
var webpack = require('webpack');
var config = {
cache: true,
entry: {
android: './src/android/main.less',
ios: './src/ios/main.less'
},
output: {
path: 'build',
filename: '[name].js',
pathinfo: false
},
module: {
loaders: [
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url?limit=8192&name=asset/[name].[ext]'
}, {
test: /\.less$/,
loader: ExtractText.extract(
'css!autoprefixer?browsers=Android >= 4 iOS >= 7' +
'!less?config=lessLoaderCustom'
)
}
]
},
lessLoader: {
lessPlugins: [
new LessClean({advanced: true})
]
},
plugins: [
new ExtractText('[name].css')
]
};
var k;
for (k in config.entry) {
config.plugins.push(
new HtmlFile({
filename: k + '.html',
template: 'index.html',
hash: true,
inject: 'head',
chunks: [k]
})
);
}
module.exports = config;
|
var ExtractText = require('extract-text-webpack-plugin');
var LessClean = require('less-plugin-clean-css');
var HtmlFile = require('html-webpack-plugin');
var webpack = require('webpack');
var config = {
cache: true,
entry: {
android: './src/android/main.less',
ios: './src/ios/main.less'
},
output: {
path: 'build',
filename: '[name].js',
pathinfo: false
},
module: {
loaders: [
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url?limit=8192&name=asset/[name].[ext]'
}, {
test: /\.less$/,
loader: ExtractText.extract(
'css!autoprefixer?browsers=last 5 version' +
'!less?config=lessLoaderCustom'
)
}
]
},
lessLoader: {
lessPlugins: [
new LessClean({advanced: true})
]
},
plugins: [
new ExtractText('[name].css')
]
};
var k;
for (k in config.entry) {
config.plugins.push(
new HtmlFile({
filename: k + '.html',
template: 'index.html',
hash: true,
inject: 'head',
chunks: [k]
})
);
}
module.exports = config;
|
Add some output to let users know what is about to be scraped.
|
package main
import (
"flag"
"fmt"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
)
type user struct {
name string
email string
url string
username string
}
func main() {
url := flag.String("github_url", "", "github url you want to scrape")
flag.Parse()
githubURL := *url
doc, err := goquery.NewDocument(githubURL)
if err != nil {
log.Fatal(err)
}
if strings.Contains(githubURL, "/orgs/") {
fmt.Println("Organization URL. Beginning to scrape.")
scrapeOrganization(doc, githubURL)
} else if strings.Contains(githubURL, "/search?") {
fmt.Println("Search URL. Beginning to scrape.")
scrapeSearch(doc, githubURL)
} else if strings.Contains(githubURL, "/stargazers") {
fmt.Println("Stargazer URL. Beginning to scrape.")
scrapeStarGazers(doc, githubURL)
} else {
fmt.Println("Single profile URL. Beginning to scrape.")
scrapeProfile(doc)
}
}
|
package main
import (
"flag"
"fmt"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
)
type user struct {
name string
email string
url string
username string
}
func main() {
url := flag.String("github_url", "", "github url you want to scrape")
flag.Parse()
githubURL := *url
doc, err := goquery.NewDocument(githubURL)
if err != nil {
log.Fatal(err)
}
if strings.Contains(githubURL, "/orgs/") {
scrapeOrganization(doc, githubURL)
} else if strings.Contains(githubURL, "/search?") {
scrapeSearch(doc, githubURL)
} else if strings.Contains(githubURL, "/stargazers") {
fmt.Println("Stargazer URL. Beginning to scrape.")
scrapeStarGazers(doc, githubURL)
} else {
scrapeProfile(doc)
}
}
|
Fix implied_group, it still refers to the old module name
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm, fields
class AccountConfigSettings(orm.TransientModel):
_inherit = 'account.config.settings'
_columns = {
'group_use_product_description_per_inv_line': fields.boolean(
"""Allow using only the product description on the
invoice order lines""",
implied_group="account_invoice_line_description."
"group_use_product_description_per_inv_line",
help="""Allows you to use only product description on the
invoice order lines."""
),
}
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm, fields
class AccountConfigSettings(orm.TransientModel):
_inherit = 'account.config.settings'
_columns = {
'group_use_product_description_per_inv_line': fields.boolean(
"""Allow using only the product description on the
invoice order lines""",
implied_group="invoice_line_description."
"group_use_product_description_per_inv_line",
help="""Allows you to use only product description on the
invoice order lines."""
),
}
|
Change a bracelet to new line
|
<?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Http\Kernel;
class CharacterSolverServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @param \Illuminate\Contracts\Http\Kernel $kernel
* @return void
*/
public function boot(Kernel $kernel)
{
// Global middleware
// Add a new middleware to end of the stack if it does not already exist.
// https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/Http/Kernel.php#L205
$kernel->pushMiddleware(Middleware\CharacterSolver::class);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
|
<?php
namespace Juy\CharacterSolver;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Http\Kernel;
class CharacterSolverServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @param \Illuminate\Contracts\Http\Kernel $kernel
* @return void
*/
public function boot(Kernel $kernel) {
// Global middleware
// Add a new middleware to end of the stack if it does not already exist.
// https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/Http/Kernel.php#L205
$kernel->pushMiddleware(Middleware\CharacterSolver::class);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
|
Fix compatibility with Phalcon 2
|
<?php
/**
* @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
*/
namespace User;
use Phalcon\DiInterface;
class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
public function registerAutoloaders(DiInterface $dependencyInjector = null)
{
$loader = new \Phalcon\Loader();
$loader->registerNamespaces(array(
'User\Controller' => APPLICATION_PATH . '/modules/user/controllers/',
'User\Model' => APPLICATION_PATH . '/modules/user/models/',
));
$loader->register();
}
public function registerServices(DiInterface $dependencyInjector)
{
$dispatcher = $dependencyInjector->get('dispatcher');
$dispatcher->setDefaultNamespace('User\Controller');
/**
* @var $view \Phalcon\Mvc\View
*/
$view = $dependencyInjector->get('view');
$view->setLayout('index');
$view->setViewsDir(APPLICATION_PATH . '/modules/user/views/');
$view->setLayoutsDir('../../common/layouts/');
$view->setPartialsDir('../../common/partials/');
$dependencyInjector->set('view', $view);
}
}
|
<?php
/**
* @author Patsura Dmitry https://github.com/ovr <talk@dmtry.me>
*/
namespace User;
class Module implements \Phalcon\Mvc\ModuleDefinitionInterface
{
public function registerAutoloaders()
{
$loader = new \Phalcon\Loader();
$loader->registerNamespaces(array(
'User\Controller' => APPLICATION_PATH . '/modules/user/controllers/',
'User\Model' => APPLICATION_PATH . '/modules/user/models/',
));
$loader->register();
}
public function registerServices($di)
{
$dispatcher = $di->get('dispatcher');
$dispatcher->setDefaultNamespace('User\Controller');
/**
* @var $view \Phalcon\Mvc\View
*/
$view = $di->get('view');
$view->setLayout('index');
$view->setViewsDir(APPLICATION_PATH . '/modules/user/views/');
$view->setLayoutsDir('../../common/layouts/');
$view->setPartialsDir('../../common/partials/');
$di->set('view', $view);
}
}
|
Add project to hook table so it's a little more clear what it's a global one.
|
import django_tables2 as tables
from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable
from fabric_bolt.web_hooks import models
class HookTable(PaginateTable):
"""Table used to show the configurations
Also provides actions to edit and delete"""
actions = ActionsColumn([
{'title': '<i class="glyphicon glyphicon-pencil"></i>', 'url': 'hooks_hook_update', 'args': [tables.A('pk')],
'attrs':{'data-toggle': 'tooltip', 'title': 'Edit Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}},
{'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'hooks_hook_delete', 'args': [tables.A('pk')],
'attrs':{'data-toggle': 'tooltip', 'title': 'Delete Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}},
], delimiter='   ')
class Meta:
model = models.Hook
attrs = {"class": "table table-striped"}
sequence = fields = (
'project',
'url',
)
|
import django_tables2 as tables
from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable
from fabric_bolt.web_hooks import models
class HookTable(PaginateTable):
"""Table used to show the configurations
Also provides actions to edit and delete"""
actions = ActionsColumn([
{'title': '<i class="glyphicon glyphicon-pencil"></i>', 'url': 'hooks_hook_update', 'args': [tables.A('pk')],
'attrs':{'data-toggle': 'tooltip', 'title': 'Edit Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}},
{'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'hooks_hook_delete', 'args': [tables.A('pk')],
'attrs':{'data-toggle': 'tooltip', 'title': 'Delete Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}},
], delimiter='   ')
class Meta:
model = models.Hook
attrs = {"class": "table table-striped"}
sequence = fields = (
'url',
)
|
Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals.
|
def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise ImproperlyConfigured("No defaults were supplied to set_defaults.")
app_label = app.__name__.split('.')[-2]
def install_settings(app, created_models, verbosity=2, **kwargs):
printed = False
for class_name, attribute_name, value in defaults:
if not get_setting_storage(app.__name__, class_name, attribute_name):
if verbosity >= 2 and not printed:
# Print this message only once, and only if applicable
print "Installing default settings for %s" % app_label
printed = True
try:
set_setting_value(app.__name__, class_name, attribute_name, value)
except:
raise ImproperlyConfigured("%s requires dbsettings." % app_label)
signals.post_syncdb.connect(install_settings, sender=app, weak=False)
|
def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise ImproperlyConfigured("No defaults were supplied to set_defaults.")
app_label = app.__name__.split('.')[-2]
def install_settings(app, created_models, verbosity=2, **kwargs):
printed = False
for class_name, attribute_name, value in defaults:
if not get_setting_storage(app.__name__, class_name, attribute_name):
if verbosity >= 2 and not printed:
# Print this message only once, and only if applicable
print "Installing default settings for %s" % app_label
printed = True
try:
set_setting_value(app.__name__, class_name, attribute_name, value)
except:
raise ImproperlyConfigured("%s requires dbsettings." % app_label)
signals.post_syncdb.connect(install_settings, sender=app)
|
Fix range error in randomColor test
|
var lodash = require('lodash');
var expect = require('chai').expect;
var testPath = require('path').join(__dirname, '../../src/colors/randomColor');
var _ = require(testPath)(lodash);
module.exports = function() {
describe('randomColor', function() {
it('exists', function() {
expect(_.randomColor).to.be.a('function');
});
it('generates a color', function() {
var color = _.randomColor();
expect(color.r).to.be.a('number');
expect(color.g).to.be.a('number');
expect(color.b).to.be.a('number');
expect(color.r).to.be.below(256);
expect(color.g).to.be.below(256);
expect(color.b).to.be.below(256);
expect(color.r).to.be.above(-1);
expect(color.g).to.be.above(-1);
expect(color.b).to.be.above(-1);
});
});
};
|
var lodash = require('lodash');
var expect = require('chai').expect;
var testPath = require('path').join(__dirname, '../../src/colors/randomColor');
var _ = require(testPath)(lodash);
module.exports = function() {
describe('randomColor', function() {
it('exists', function() {
expect(_.randomColor).to.be.a('function');
});
it('generates a color', function() {
var color = _.randomColor();
expect(color.r).to.be.a('number');
expect(color.g).to.be.a('number');
expect(color.b).to.be.a('number');
expect(color.r).to.be.below(256);
expect(color.g).to.be.below(256);
expect(color.b).to.be.below(256);
expect(color.r).to.be.above(0);
expect(color.g).to.be.above(0);
expect(color.b).to.be.above(0);
});
});
};
|
Split out the dependencies of client and server.
|
from setuptools import setup
setup(
name="rotterdam",
version="0.3.2",
description=(
"Simple asynchronous job queue via redis."
),
author="William Glass",
author_email="william.glass@gmail.com",
url="http://github.com/wglass/rotterdam",
packages=["rotterdam"],
include_package_data=True,
package_data={
'rotterdam': ['lua/*.lua']
},
scripts=[
"bin/rotterdam",
"bin/rotterdamctl"
],
install_requires=[
"python-dateutil",
"pytz"
],
extras_require={
"server": [
"setproctitle",
"redis"
]
},
tests_require=[
"mock",
"nose"
]
)
|
from setuptools import setup
setup(
name="rotterdam",
version="0.3.2",
description=(
"Simple distributed job queue via redis."
),
author="William Glass",
author_email="william.glass@gmail.com",
url="http://github.com/wglass/rotterdam",
packages=["rotterdam"],
include_package_data=True,
package_data={
'rotterdam': ['lua/*.lua']
},
scripts=[
"bin/rotterdam",
"bin/rotterdamctl"
],
install_requires=[
"setproctitle",
"redis",
"python-dateutil",
"pytz"
],
dependency_links=[
"http://github.com/surfly/gevent/tarball/1.0rc3#egg=gevent-1.0dev"
],
tests_require=[
"mock",
"nose"
]
)
|
Use simple name iso full class name to choose a port
|
package be.bagofwords.web;
import be.bagofwords.application.MainClass;
import be.bagofwords.application.annotations.BowConfiguration;
import be.bagofwords.util.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@BowConfiguration
public class WebContainerConfiguration {
@Bean
@Autowired
public WebContainer createWebContainer(MainClass mainClass) {
long hashCode = HashUtils.hashCode(mainClass.getClass().getSimpleName());
if (hashCode < 0) {
hashCode = -hashCode;
}
int randomPortForApplication = (int) (1023 + (hashCode % (65535 - 1023)));
return new WebContainer(randomPortForApplication);
}
}
|
package be.bagofwords.web;
import be.bagofwords.application.MainClass;
import be.bagofwords.application.annotations.BowConfiguration;
import be.bagofwords.util.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@BowConfiguration
public class WebContainerConfiguration {
@Bean
@Autowired
public WebContainer createWebContainer(MainClass mainClass) {
long hashCode = HashUtils.hashCode(mainClass.getClass().getName());
if (hashCode < 0) {
hashCode = -hashCode;
}
int randomPortForApplication = (int) (1023 + (hashCode % (65535 - 1023)));
return new WebContainer(randomPortForApplication);
}
}
|
Tweak formatting of argparse section to minimize lines extending past 80 chars.
|
#!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status pages.')
parser.add_argument('-f',
'--format',
choices=['ascii', 'json', 'pprint'],
default='ascii', dest='output_format',
help='output format')
parser.add_argument('-u',
'--url',
default=default_url,
help='url of modem status page')
args = parser.parse_args()
if args.output_format == 'ascii':
print("ASCII output not yet implemented")
elif args.output_format == 'json':
result = arris_scraper.get_status(args.url)
print(json.dumps(result))
elif args.output_format == 'pprint':
result = arris_scraper.get_status(args.url)
pprint.pprint(result)
else:
print("How in the world did you get here?")
|
#!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status pages.')
parser.add_argument('-f', '--format', choices=['ascii', 'json', 'pprint'], default='ascii', dest='output_format', help='output format')
parser.add_argument('-u', '--url', default=default_url, help='url of modem status page')
args = parser.parse_args()
if args.output_format == 'ascii':
print("ASCII output not yet implemented")
elif args.output_format == 'json':
result = arris_scraper.get_status(args.url)
print(json.dumps(result))
elif args.output_format == 'pprint':
result = arris_scraper.get_status(args.url)
pprint.pprint(result)
else:
print("How in the world did you get here?")
|
Add workaround for atomic writes in watch mode
|
let chokidar = require('chokidar');
class Task {
/**
* Create a new task instance.
*
* @param {Object} data
*/
constructor(data) {
this.data = data;
this.assets = [];
this.isBeingWatched = false;
}
/**
* Watch all relevant files for changes.
*
* @param {boolean} usePolling
*/
watch(usePolling = false) {
if (this.isBeingWatched) return;
const files = this.files.get()
const watcher = chokidar.watch(files, { usePolling, persistent: true})
.on('change', this.onChange.bind(this));
// workaround for issue with atomic writes (See https://github.com/paulmillr/chokidar/issues/591)
if (!usePolling) {
watcher.on('raw', (event, path, {watchedPath}) => {
if (event === 'rename') {
watcher.unwatch(files);
watcher.add(files);
}
})
}
this.isBeingWatched = true;
}
}
module.exports = Task;
|
let chokidar = require('chokidar');
class Task {
/**
* Create a new task instance.
*
* @param {Object} data
*/
constructor(data) {
this.data = data;
this.assets = [];
this.isBeingWatched = false;
}
/**
* Watch all relevant files for changes.
*
* @param {boolean} usePolling
*/
watch(usePolling = false) {
if (this.isBeingWatched) return;
const files = this.files.get()
const watcher = chokidar.watch(files, { usePolling, persistent: true})
.on('change', this.onChange.bind(this));
this.isBeingWatched = true;
}
}
module.exports = Task;
|
Fix bug where homepage only displayed once.
Resolves #383
|
//
// Gistbook
// A model representing a new Gistbook
//
import * as _ from 'underscore';
import { BaseModel, BaseCollection } from 'base/entities';
export default BaseModel.extend({
initialize() {
this._dirty = false;
this.on('change', this._markDirty, this);
this.listenTo(this.get('pages'), 'change', this._markDirty);
},
// Create a deeply nested model structure
// Gistbooks have a collection of pages
// Pages have a collection of sections
parse(data) {
data = _.clone(data);
// Create our nested pages
data.pages = new BaseCollection(data.pages);
// Loop through each page...
data.pages.each(page => {
// ...to create our nested sections
page.set({
sections: new BaseCollection(page.get('sections'))
}, {silent: true});
// And forward all events from our sections to our pages
page.listenTo(page.get('sections'), 'all', function() {
page.trigger.apply(page, arguments);
});
});
return data;
},
isDirty() {
return !!this._dirty;
},
_markDirty() {
this._dirty = true;
},
});
|
//
// Gistbook
// A model representing a new Gistbook
//
import { BaseModel, BaseCollection } from 'base/entities';
export default BaseModel.extend({
initialize() {
this._dirty = false;
this.on('change', this._markDirty, this);
this.listenTo(this.get('pages'), 'change', this._markDirty);
},
// Create a deeply nested model structure
// Gistbooks have a collection of pages
// Pages have a collection of sections
parse(data) {
// Create our nested pages
data.pages = new BaseCollection(data.pages);
// Loop through each page...
data.pages.each(page => {
// ...to create our nested sections
page.set({
sections: new BaseCollection(page.get('sections'))
}, {silent: true});
// And forward all events from our sections to our pages
page.listenTo(page.get('sections'), 'all', function() {
page.trigger.apply(page, arguments);
});
});
return data;
},
isDirty() {
return !!this._dirty;
},
_markDirty() {
this._dirty = true;
},
});
|
:key: Change dir to serve resources from public dir
|
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
realpath(base_path('public/')),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => realpath(storage_path('framework/views')),
];
|
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
realpath(base_path('resources/views')),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => realpath(storage_path('framework/views')),
];
|
Change fixture upload task to json serializer
|
from __future__ import absolute_import, unicode_literals
from celery.task import task
from soil import DownloadBase
from corehq.apps.fixtures.upload import upload_fixture_file
@task
def fixture_upload_async(domain, download_id, replace):
task = fixture_upload_async
DownloadBase.set_progress(task, 0, 100)
download_ref = DownloadBase.get(download_id)
result = upload_fixture_file(domain, download_ref.get_filename(), replace, task)
DownloadBase.set_progress(task, 100, 100)
return {
'messages': {
'success': result.success,
'messages': result.messages,
'errors': result.errors,
'number_of_fixtures': result.number_of_fixtures,
},
}
@task(serializer='pickle')
def fixture_download_async(prepare_download, *args, **kw):
task = fixture_download_async
DownloadBase.set_progress(task, 0, 100)
prepare_download(task=task, *args, **kw)
DownloadBase.set_progress(task, 100, 100)
|
from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.apps.fixtures.upload import upload_fixture_file
from soil import DownloadBase
from celery.task import task
@task(serializer='pickle')
def fixture_upload_async(domain, download_id, replace):
task = fixture_upload_async
DownloadBase.set_progress(task, 0, 100)
download_ref = DownloadBase.get(download_id)
result = upload_fixture_file(domain, download_ref.get_filename(), replace, task)
DownloadBase.set_progress(task, 100, 100)
return {
'messages': {
'success': result.success,
'messages': result.messages,
'errors': result.errors,
'number_of_fixtures': result.number_of_fixtures,
},
}
@task(serializer='pickle')
def fixture_download_async(prepare_download, *args, **kw):
task = fixture_download_async
DownloadBase.set_progress(task, 0, 100)
prepare_download(task=task, *args, **kw)
DownloadBase.set_progress(task, 100, 100)
|
Fix typo in latest change for Base Controller Autoload.
|
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Authenticated Controller
*
* Provides a base class for all controllers that must check user login
* status.
*
* @package Bonfire\Core\Controllers
* @category Controllers
* @author Bonfire Dev Team
* @link http://guides.cibonfire.com/helpers/file_helpers.html
*
*/
class Authenticated_Controller extends Base_Controller
{
protected $require_authentication = true;
//--------------------------------------------------------------------
/**
* Class constructor setup login restriction and load various libraries
*
*/
public function __construct()
{
$this->autoload['helpers'][] = 'form';
$this->autoload['libraries'][] = 'Template';
$this->autoload['libraries'][] = 'Assets';
$this->autoload['libraries'][] = 'form_validation';
parent::__construct();
$this->form_validation->set_error_delimiters('', '');
}//end construct()
//--------------------------------------------------------------------
}
/* End of file Authenticated_Controller.php */
/* Location: ./application/core/Authenticated_Controller.php */
|
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Authenticated Controller
*
* Provides a base class for all controllers that must check user login
* status.
*
* @package Bonfire\Core\Controllers
* @category Controllers
* @author Bonfire Dev Team
* @link http://guides.cibonfire.com/helpers/file_helpers.html
*
*/
class Authenticated_Controller extends Base_Controller
{
protected $require_authentication = true;
//--------------------------------------------------------------------
/**
* Class constructor setup login restriction and load various libraries
*
*/
public function __construct()
{
$this->autoload['helpers'] = 'form';
$this->autoload['libraries'][] = 'Template';
$this->autoload['libraries'][] = 'Assets';
$this->autoload['libraries'][] = 'form_validation';
parent::__construct();
$this->form_validation->set_error_delimiters('', '');
}//end construct()
//--------------------------------------------------------------------
}
/* End of file Authenticated_Controller.php */
/* Location: ./application/core/Authenticated_Controller.php */
|
Add wait before switching iframe. This will stablize the e2e tests.
|
/**
* Copyright 2019 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.command = function(iframeSrcString, iframeMsg, callback) {
return this.element('css selector', `iframe${iframeSrcString}`, frame => {
this.pause(2000);
this.frame({ELEMENT: frame.value.ELEMENT}, () => {
this.log(`Switching to ${iframeMsg}`);
callback && callback();
});
});
};
|
/**
* Copyright 2019 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.command = function(iframeSrcString, iframeMsg, callback) {
return this.element('css selector', `iframe${iframeSrcString}`, frame => {
this.frame({ELEMENT: frame.value.ELEMENT}, () => {
this.log(`Switching to ${iframeMsg}`);
callback && callback();
});
});
};
|
Upgrade to Keras 2 API
|
from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(n1, f1, kernel_initializer='he_normal',
activation='relu', input_shape=input_shape))
model.add(Conv2D(n2, f2, kernel_initializer='he_normal',
activation='relu'))
model.add(Conv2D(c, f3, kernel_initializer='he_normal'))
model.compile(optimizer='adam', loss='mse', metrics=[psnr])
return model
|
from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(nb_filter=n1, nb_row=f1, nb_col=f1, init='he_normal',
activation='relu', input_shape=input_shape))
model.add(Conv2D(nb_filter=n2, nb_row=f2, nb_col=f2, init='he_normal',
activation='relu'))
model.add(Conv2D(nb_filter=c, nb_row=f3, nb_col=f3, init='he_normal'))
model.compile(optimizer='adam', loss='mse', metrics=[psnr])
return model
|
Make sure __setitem__ is available for site.register()
|
from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class HatbandAndDjangoRegistry(object):
def __init__(self, site, default_site=None):
if default_site is None:
default_site = django_site
super(HatbandAndDjangoRegistry, self).__init__()
self._site = site
self._registry = {}
self.dicts = [self._registry, default_site._registry]
def items(self):
for d in self.dicts:
for item in d.items():
yield item
def iteritems(self):
return iter(self.items())
def __contains__(self, k):
for d in self.dicts:
if k in d:
return True
return False
def __setitem__(self, k, v):
self._registry[k] = v
class AdminSite(DjangoAdminSite):
def get_urls(self):
from django.conf.urls.defaults import patterns, url
return patterns('',
# Custom hatband Views here
) + super(AdminSite, self).get_urls()
site = AdminSite()
site._registry = HatbandAndDjangoRegistry(site, default_site=django_site)
|
from django.contrib.admin.sites import AdminSite as DjangoAdminSite
from django.contrib.admin.sites import site as django_site
class HatbandAndDjangoRegistry(object):
def __init__(self, site, default_site=None):
if default_site is None:
default_site = django_site
super(HatbandAndDjangoRegistry, self).__init__()
self._site = site
self._registry = {}
self.dicts = [self._registry, default_site._registry]
def items(self):
for d in self.dicts:
for item in d.items():
yield item
def iteritems(self):
return iter(self.items())
def __contains__(self, k):
for d in self.dicts:
if k in d:
return True
return False
class AdminSite(DjangoAdminSite):
def get_urls(self):
from django.conf.urls.defaults import patterns, url
return patterns('',
# Custom hatband Views here
) + super(AdminSite, self).get_urls()
site = AdminSite()
site._registry = HatbandAndDjangoRegistry(site, default_site=django_site)
|
Rename prop for image source to imageSource instead of text
|
import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
// import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class ClickableImage extends Component {
static propTypes = {
onPress: PropTypes.func,
onLongPress: PropTypes.func,
imageSource: PropTypes.object,
children: PropTypes.object,
navigation: PropTypes.object,
imageStyle: Image.propTypes.style,
touchStyle: View.propTypes.style
}
_onLongPress() {
}
render() {
return (
<View>
<FadeInView>
<TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress} onLongPress={this.props.onLongPress}>
<Image style={this.props.imageStyle} source={this.props.imageSource} />
</TouchableOpacity>
</FadeInView>
</View>
)
}
}
|
import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
// import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class ClickableImage extends Component {
static propTypes = {
onPress: PropTypes.func,
onLongPress: PropTypes.func,
text: PropTypes.object,
children: PropTypes.object,
navigation: PropTypes.object,
imageStyle: Image.propTypes.style,
touchStyle: View.propTypes.style
}
_onLongPress() {
}
render() {
return (
<View>
<FadeInView>
<TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress} onLongPress={this.props.onLongPress}>
<Image style={this.props.imageStyle} source={this.props.text} />
</TouchableOpacity>
</FadeInView>
</View>
)
}
}
|
Revert "util: make DeflateRaw Checksum hook into _transform so that it mimicks the norms."
This reverts commit cf22d920b48c3c320b0a7a75577b082901db07a6.
|
var zlib = require('zlib');
var inherits = require('util').inherits;
var util = require('./');
function DeflateRawChecksum(options) {
zlib.DeflateRaw.call(this, options);
this.checksum = util.crc32.createCRC32();
this.digest = null;
this.rawSize = 0;
this.compressedSize = 0;
this.on('data', function(chunk) {
this.compressedSize += chunk.length;
});
this.on('end', function() {
this.digest = this.checksum.digest();
});
}
inherits(DeflateRawChecksum, zlib.DeflateRaw);
DeflateRawChecksum.prototype.write = function(chunk, cb) {
if (chunk) {
this.checksum.update(chunk);
this.rawSize += chunk.length;
}
return zlib.DeflateRaw.prototype.write.call(this, chunk, cb);
};
module.exports = DeflateRawChecksum;
|
var zlib = require('zlib');
var inherits = require('util').inherits;
var util = require('./');
function DeflateRawChecksum(options) {
zlib.DeflateRaw.call(this, options);
this.checksum = util.crc32.createCRC32();
this.digest = null;
this.rawSize = 0;
this.compressedSize = 0;
this.on('data', function(chunk) {
this.compressedSize += chunk.length;
});
this.on('end', function() {
this.digest = this.checksum.digest();
});
}
inherits(DeflateRawChecksum, zlib.DeflateRaw);
DeflateRawChecksum.prototype._transform = function(chunk, encoding, callback) {
if (chunk) {
this.checksum.update(chunk);
this.rawSize += chunk.length;
}
return zlib.DeflateRaw.prototype._transform.call(this, chunk, encoding, callback);
};
module.exports = DeflateRawChecksum;
|
Test line end carriages redo.
|
import moment from 'moment';
import { Paginator } from '../../../utils';
import template from './outdated-queries.html';
function OutdatedQueriesCtrl($scope, Events, $http, $timeout) {
Events.record('view', 'page', 'admin/outdated_queries');
$scope.autoUpdate = true;
this.queries = new Paginator([], { itemsPerPage: 50 });
const refresh = () => {
if ($scope.autoUpdate) {
$scope.refresh_time = moment().add(1, 'minutes');
$http.get('/api/admin/queries/outdated').success((data) => {
this.queries.updateRows(data.queries);
$scope.updatedAt = data.updated_at * 1000.0;
});
}
const timer = $timeout(refresh, 59 * 1000);
$scope.$on('$destroy', () => {
if (timer) {
$timeout.cancel(timer);
}
});
};
refresh();
}
export default function (ngModule) {
ngModule.component('outdatedQueriesPage', {
template,
controller: OutdatedQueriesCtrl,
});
return {
'/admin/queries/outdated': {
template: '<outdated-queries-page></outdated-queries-page>',
title: 'Outdated Queries',
},
};
}
|
import moment from 'moment';
import { Paginator } from '../../../utils';
import template from './outdated-queries.html';
function OutdatedQueriesCtrl($scope, Events, $http, $timeout) {
Events.record('view', 'page', 'admin/outdated_queries');
$scope.autoUpdate = true;
this.queries = new Paginator([], { itemsPerPage: 50 });
const refresh = () => {
if ($scope.autoUpdate) {
$scope.refresh_time = moment().add(1, 'minutes');
$http.get('/api/admin/queries/outdated').success((data) => {
this.queries.updateRows(data.queries);
$scope.updatedAt = data.updated_at * 1000.0;
});
}
const timer = $timeout(refresh, 59 * 1000);
$scope.$on('$destroy', () => {
if (timer) {
$timeout.cancel(timer);
}
});
};
refresh();
}
export default function (ngModule) {
ngModule.component('outdatedQueriesPage', {
template,
controller: OutdatedQueriesCtrl,
});
return {
'/admin/queries/outdated': {
template: '<outdated-queries-page></outdated-queries-page>',
title: 'Outdated Queries',
},
};
}
|
Allow for root-level domains like localhost
|
/**
* Expose `sni`.
* @type Function
*/
module.exports = sni;
/**
* RegEx for finding a domain name.
* @type {RegExp}
*/
var regex = /^(?:[a-z0-9-]+\.)*[a-z]+$/i;
/**
* Extract the SNI from a Buffer.
* @param {Buffer} buf
* @return {String|null}
*/
function sni(buf) {
var sni = null;
for(var b = 0, prev, start, end, str; b < buf.length; b++) {
if(prev === 0 && buf[b] === 0) {
start = b + 2;
end = start + buf[b + 1];
if(start < end && end < buf.length) {
str = buf.toString("utf8", start, end);
if(regex.test(str)) {
sni = str;
continue;
}
}
}
prev = buf[b];
}
return sni;
}
|
/**
* Expose `sni`.
* @type Function
*/
module.exports = sni;
/**
* RegEx for finding a domain name.
* @type {RegExp}
*/
var regex = /^(?:[a-z0-9-]+\.)+[a-z]+$/i;
/**
* Extract the SNI from a Buffer.
* @param {Buffer} buf
* @return {String|null}
*/
function sni(buf) {
var sni = null;
for(var b = 0, prev, start, end, str; b < buf.length; b++) {
if(prev === 0 && buf[b] === 0) {
start = b + 2;
end = start + buf[b + 1];
if(start < end && end < buf.length) {
str = buf.toString("utf8", start, end);
if(regex.test(str)) {
sni = str;
continue;
}
}
}
prev = buf[b];
}
return sni;
}
|
[SYN5-294] Hide the user_profile data class
|
export default {
list() {
this.NewLibConnection
.Class
.please()
.list()
.ordering('desc')
.then((classes) => {
const classesList = classes.filter((item) => item.name !== 'user_profile');
this.completed(classesList);
})
.catch(this.failure);
},
get(name) {
this.NewLibConnection
.Class
.please()
.get({ name })
.then(this.completed)
.catch(this.failure);
},
create(payload) {
this.NewLibConnection
.Class
.please()
.create(payload)
.then(this.completed)
.catch(this.failure);
},
update(name, payload) {
this.NewLibConnection
.Class
.please()
.update({ name }, payload)
.then(this.completed)
.catch(this.failure);
},
remove(classes) {
const promises = classes.map((item) => this.NewLibConnection.Class.please().delete({ name: item.name }));
this.Promise.all(promises)
.then(this.completed)
.catch(this.failure);
}
};
|
export default {
list() {
this.NewLibConnection
.Class
.please()
.list()
.ordering('desc')
.then(this.completed)
.catch(this.failure);
},
get(name) {
this.NewLibConnection
.Class
.please()
.get({ name })
.then(this.completed)
.catch(this.failure);
},
create(payload) {
this.NewLibConnection
.Class
.please()
.create(payload)
.then(this.completed)
.catch(this.failure);
},
update(name, payload) {
this.NewLibConnection
.Class
.please()
.update({ name }, payload)
.then(this.completed)
.catch(this.failure);
},
remove(classes) {
const promises = classes.map((item) => this.NewLibConnection.Class.please().delete({ name: item.name }));
this.Promise.all(promises)
.then(this.completed)
.catch(this.failure);
}
};
|
Fix bug where page stops updating by forcing it to reload after a minute
of no activity
|
#!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_id('email').send_keys(input('Email: '))
driver.find_element_by_id('pass').send_keys(getpass())
driver.find_element_by_id('loginbutton').click()
driver.get('https://facebook.com/pokes/')
assert "Forgot password?" not in driver.page_source
c = 0
c2 = 0
while True:
try:
for i in driver.find_elements_by_link_text("Poke Back"):
i.click()
c += 1
c2 = 0
print("Clicked so far: " + str(c))
except StaleElementReferenceException:
print("Found exception, reloading page")
driver.get('https://facebook.com/pokes/')
c2 += 1
if c2 % 121 == 0:
print("No pokes in last minute. Reloading")
driver.get('https://facebook.com/pokes/')
sleep(0.5)
|
#!/bin/env python
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from time import sleep
from getpass import getpass
if __name__ == '__main__':
driver = webdriver.phantomjs.webdriver.WebDriver()
driver.get('https://facebook.com')
driver.find_element_by_id('email').send_keys(input('Email: '))
driver.find_element_by_id('pass').send_keys(getpass())
driver.find_element_by_id('loginbutton').click()
driver.get('https://facebook.com/pokes/')
assert "Forgot password?" not in driver.page_source
c = 0
while True:
try:
for i in driver.find_elements_by_link_text("Poke Back"):
i.click()
c += 1
print("Clicked so far: " + str(c))
except StaleElementReferenceException:
print("Found exception, reloading page")
driver.get('https://facebook.com/pokes/')
sleep(0.5)
|
Include only fields that a component needs
|
var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates, streaming) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
var _source = !streaming ? `${fieldName}` : null;
return ({
type: config.appbase.type,
body: {
"size": 100,
"_source": [_source],
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
geo_bounding_box
}
}
}
}
});
},
getAppbaseRef: function (config) {
return (
new Appbase({
url: 'https://scalr.api.appbase.io',
appname: config.appbase.appname,
username: config.appbase.username,
password: config.appbase.password
})
);
}
};
|
var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
return ({
type: config.appbase.type,
body: {
"size": 1000,
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
geo_bounding_box
}
}
}
}
});
},
getAppbaseRef: function (config) {
return (
new Appbase({
url: 'https://scalr.api.appbase.io',
appname: config.appbase.appname,
username: config.appbase.username,
password: config.appbase.password
})
);
}
};
|
Add dollar sign to fares, sort by fare type
|
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def get_location(self, key):
return Location.from_location(
self.get_argument(key)
)
def fares_to_table(fares):
keys, values = zip(*fares.items())
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
for key in sorted(values[0].keys()):
table_rows.append([key.title()])
table_rows[-1].extend(
'${}'.format(ticket_type[key])
for ticket_type in values
)
table = ipy_table.make_table(table_rows)
table.apply_theme('basic')
return table
|
import tornado.web
import ipy_table
from transperth.location import Location
class BaseRequestHandler(tornado.web.RequestHandler):
@property
def args(self):
args = self.request.arguments
return {
k: [sv.decode() for sv in v]
for k, v in args.items()
}
def get_location(self, key):
return Location.from_location(
self.get_argument(key)
)
def fares_to_table(fares):
keys, values = zip(*fares.items())
table_rows = [['Fare Type']]
table_rows[-1].extend(key.title() for key in keys)
for key in values[0].keys():
table_rows.append([key.title()])
table_rows[-1].extend(
ticket_type[key]
for ticket_type in values
)
table = ipy_table.make_table(table_rows)
table.apply_theme('basic')
return table
|
Fix SoundCloud embed width/height replacement.
SoundCloud embeds aren't always 500x500.
Also, don't set the "width" embed dict key to '100%':
"width"/"height" keys expect integers only.
|
from urllib.parse import urlparse
from django.conf import settings
from wagtail.wagtailembeds.finders.embedly import embedly
from wagtail.wagtailembeds.finders.oembed import oembed
def get_default_finder():
if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
return embedly
return oembed
def finder(url, max_width=None):
domain = urlparse(url).netloc
# work around Embedly missing embedding HTML for Twitter and Instagram URLs
if domain.endswith((
'instagram.com',
'twitter.com',
)):
return oembed(url, max_width)
embed_dict = get_default_finder()(url, max_width)
if domain.endswith('soundcloud.com'):
embed_dict['html'] = (
embed_dict['html']
.replace('visual%3Dtrue', 'visual%3Dfalse')
.replace('width="%s"' % embed_dict['width'], 'width="100%"')
.replace('height="%s"' % embed_dict['height'], 'height="166"')
)
embed_dict['width'] = None
embed_dict['height'] = 166
return embed_dict
|
from urllib.parse import urlparse
from django.conf import settings
from wagtail.wagtailembeds.finders.embedly import embedly
from wagtail.wagtailembeds.finders.oembed import oembed
def get_default_finder():
if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
return embedly
return oembed
def finder(url, max_width=None):
domain = urlparse(url).netloc
# work around Embedly missing embedding HTML for Twitter and Instagram URLs
if domain.endswith((
'instagram.com',
'twitter.com',
)):
return oembed(url, max_width)
embed_dict = get_default_finder()(url, max_width)
if domain.endswith('soundcloud.com'):
embed_dict['html'] = (
embed_dict['html']
.replace('visual%3Dtrue', 'visual%3Dfalse')
.replace('width="500"', 'width="100%"')
.replace('height="500"', 'height="166"')
)
embed_dict['width'] = '100%'
embed_dict['height'] = '166'
return embed_dict
|
Update bootstrapped package.json to use Webpack and Karma CLIs
|
import { join } from 'path'
import json from '../util/json'
const saguiScripts = {
'start': 'npm run develop',
'test': 'NODE_ENV=test karma start',
'test:watch': 'npm test -- --no-single-run --auto-watch',
'develop': 'webpack-dev-server --port 3000 --host 0.0.0.0',
'build': 'webpack',
'dist': 'NODE_ENV=production webpack -p'
}
export default function (projectPath) {
const packagePath = join(projectPath, 'package.json')
const packageJSON = json.read(packagePath)
json.write(packagePath, {
...packageJSON,
scripts: {
...saguiScripts,
...withoutDefaults(packageJSON.scripts)
}
})
}
/**
* Remove default configurations generated by NPM that can be overwriten
* We don't want to overwrite any user configured scripts
*/
function withoutDefaults (scripts) {
const defaultScripts = {
'test': 'echo \"Error: no test specified\" && exit 1'
}
return Object.keys(scripts)
.filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key])
.reduce((filtered, key) => {
return {
...filtered,
[key]: scripts[key]
}
}, {})
}
|
import { join } from 'path'
import json from '../util/json'
const saguiScripts = {
'start': 'npm run develop',
'test': 'NODE_ENV=test sagui test',
'test-watch': 'NODE_ENV=test sagui test --watch',
'develop': 'sagui develop',
'build': 'sagui build',
'dist': 'NODE_ENV=production sagui dist'
}
export default function (projectPath) {
const packagePath = join(projectPath, 'package.json')
const packageJSON = json.read(packagePath)
json.write(packagePath, {
...packageJSON,
scripts: {
...saguiScripts,
...withoutDefaults(packageJSON.scripts)
}
})
}
/**
* Remove default configurations generated by NPM that can be overwriten
* We don't want to overwrite any user configured scripts
*/
function withoutDefaults (scripts) {
const defaultScripts = {
'test': 'echo \"Error: no test specified\" && exit 1'
}
return Object.keys(scripts)
.filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key])
.reduce((filtered, key) => {
return {
...filtered,
[key]: scripts[key]
}
}, {})
}
|
Use ugettext_lazy instead of ugettext to support Django 1.7 migrations
|
from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
class Feedback(models.Model):
site = models.ForeignKey(Site, verbose_name=_('site'))
url = models.CharField(max_length=255, verbose_name=_('url'))
urlhash = models.TextField(verbose_name=_('urlhash'), default="", null=True, blank=True)
useragent = models.TextField(verbose_name=_('useragent'), default="", null=True, blank=True)
subject = models.CharField(max_length=255, blank=True, null=True,
verbose_name=_('subject'))
email = models.EmailField(blank=True, null=True, verbose_name=_('email'))
text = models.TextField(verbose_name=_('text'))
created = models.DateTimeField(auto_now_add=True, null=True)
def __unicode__(self):
return u'{url}: {subject}'.format(url=self.url, subject=self.subject)
|
from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext as _
class Feedback(models.Model):
site = models.ForeignKey(Site, verbose_name=_('site'))
url = models.CharField(max_length=255, verbose_name=_('url'))
urlhash = models.TextField(verbose_name=_('urlhash'), default="", null=True, blank=True)
useragent = models.TextField(verbose_name=_('useragent'), default="", null=True, blank=True)
subject = models.CharField(max_length=255, blank=True, null=True,
verbose_name=_('subject'))
email = models.EmailField(blank=True, null=True, verbose_name=_('email'))
text = models.TextField(verbose_name=_('text'))
created = models.DateTimeField(auto_now_add=True, null=True)
def __unicode__(self):
return u'{url}: {subject}'.format(url=self.url, subject=self.subject)
|
Split replacement pattern over multiple lines
This makes it a little more readable and maintainable.
|
/*
* Pattern matching the prefix of at least one stripped query string
* parameter. We'll search the query string portion of the URL for this
* pattern to determine if there's any stripping work to do.
*/
var searchPattern = new RegExp('utm_|clid|mkt_tok', 'i');
/*
* Pattern matching the query string parameters (key=value) that will be
* stripped from the final URL.
*/
var replacePattern = new RegExp(
'([?&]' +
'(mkt_tok|(g|fb)clid|utm_(source|medium|term|campaign|content|cid|reader|referrer|name))' +
'=[^&#]*)',
'ig');
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var url = details.url;
var queryStringIndex = url.indexOf('?');
if (url.search(searchPattern) > queryStringIndex) {
var stripped = url.replace(replacePattern, '');
if (stripped.charAt(queryStringIndex) === '&') {
stripped = stripped.substr(0, queryStringIndex) + '?' +
stripped.substr(queryStringIndex + 1)
}
if (stripped != url) {
return {redirectUrl: stripped};
}
}
},
{urls: ['https://*/*?*', 'http://*/*?*'], types: ['main_frame']}, ['blocking']);
|
/*
* Pattern matching the prefix of at least one stripped query string
* parameter. We'll search the query string portion of the URL for this
* pattern to determine if there's any stripping work to do.
*/
var searchPattern = new RegExp('utm_|clid|mkt_tok', 'i');
/*
* Pattern matching the query string parameters (key=value) that will be
* stripped from the final URL.
*/
var replacePattern = new RegExp('([?&](mkt_tok|(g|fb)clid|utm_(source|medium|term|campaign|content|cid|reader|referrer|name))=[^&#]*)', 'ig');
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var url = details.url;
var queryStringIndex = url.indexOf('?');
if (url.search(searchPattern) > queryStringIndex) {
var stripped = url.replace(replacePattern, '');
if (stripped.charAt(queryStringIndex) === '&') {
stripped = stripped.substr(0, queryStringIndex) + '?' +
stripped.substr(queryStringIndex + 1)
}
if (stripped != url) {
return {redirectUrl: stripped};
}
}
},
{urls: ['https://*/*?*', 'http://*/*?*'], types: ['main_frame']}, ['blocking']);
|
Hide dirs on Windows only
|
import Promise from 'bluebird'
import childProcess from 'child_process'
import logger from '../logger'
Promise.promisifyAll(childProcess)
const log = logger({
component: 'FS'
})
// Hides a directory on Windows.
// Errors are logged, not thrown.
export async function hideOnWindows (path: string): Promise<void> {
if (process.platform !== 'win32') return
try {
await childProcess.execAsync(`attrib +h "${path}"`)
} catch (err) {
log.error(err)
}
}
const ILLEGAL_CHARACTERS = '/?<>\\:*|"'
const ILLEGAL_CHARACTERS_REGEXP = new RegExp(`[${ILLEGAL_CHARACTERS}]`, 'g')
const REPLACEMENT_CHARACTER = '_'
// Return a new name compatible with target filesystems by replacing invalid
// characters from the given file/dir name.
export function validName (name: string) {
return name.replace(ILLEGAL_CHARACTERS_REGEXP, REPLACEMENT_CHARACTER)
}
|
import Promise from 'bluebird'
import childProcess from 'child_process'
import logger from '../logger'
Promise.promisifyAll(childProcess)
const log = logger({
component: 'FS'
})
// Hides a directory on Windows.
// Errors are logged, not thrown.
export async function hideOnWindows (path: string): Promise<void> {
try {
await childProcess.execAsync(`attrib +h "${path}"`)
} catch (err) {
log.error(err)
}
}
const ILLEGAL_CHARACTERS = '/?<>\\:*|"'
const ILLEGAL_CHARACTERS_REGEXP = new RegExp(`[${ILLEGAL_CHARACTERS}]`, 'g')
const REPLACEMENT_CHARACTER = '_'
// Return a new name compatible with target filesystems by replacing invalid
// characters from the given file/dir name.
export function validName (name: string) {
return name.replace(ILLEGAL_CHARACTERS_REGEXP, REPLACEMENT_CHARACTER)
}
|
Introduce a `render` method that generates content without beeing forced to put the result in a file.
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\GeneratorBundle\Generator;
/**
* Generator is the base class for all generators.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Generator
{
protected function render($skeletonDir, $template, $parameters)
{
$twig = new \Twig_Environment(new \Twig_Loader_Filesystem($skeletonDir), array(
'debug' => true,
'cache' => false,
'strict_variables' => true,
'autoescape' => false,
));
return $twig->render($template, $parameters);
}
protected function renderFile($skeletonDir, $template, $target, $parameters)
{
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
return file_put_contents($target, $this->render($skeletonDir, $template, $parameters));
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\GeneratorBundle\Generator;
/**
* Generator is the base class for all generators.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Generator
{
protected function renderFile($skeletonDir, $template, $target, $parameters)
{
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
$twig = new \Twig_Environment(new \Twig_Loader_Filesystem($skeletonDir), array(
'debug' => true,
'cache' => false,
'strict_variables' => true,
'autoescape' => false,
));
file_put_contents($target, $twig->render($template, $parameters));
}
}
|
Order and comment
Organizar y comentar
|
angular.module('wi.bar.mainGridBar', [])
/**
* Grid Bar Ctrlr | Controlador de la Barra del Grid
*/
.controller('GridBarCtrl', ['$scope',
function ($scope) {
// *** CREATE | CREAR ***
// Create button click event | Evento clic en el botón Crear
$scope.createClk = function() {
console.log('Create Click');
$scope.$emit('gridBar.create');
};
// *** DELETE | BORRAR ***
// Delete button click event | Evento clic en el botón Borrar
$scope.deleteClk = function() {
console.log('Delete Click');
$scope.$emit('gridBar.delete');
};
// *** SEARCH | BUSCAR ***
// Search String | String de búsqueda
$scope.searchString = '';
// Search button click event | Evento clic en el botón Búsqueda
$scope.searchClk = function() {
$scope.$emit('gridBar.search', $scope.searchString);
};
// Search input Intro key event | Evento tecla en el campo de búsqueda
$scope.searchKey = function(keyEvent) {
// Only search on intro key |
// Solo buscar con enter
if (keyEvent.which === 13) {
$scope.$emit('gridBar.search', $scope.searchString);
}
}
}]) // GridBarCtrl
;
|
angular.module('wi.bar.mainGridBar', [])
/**
* Grid Bar Ctrlr | Controlador de la Barra del Grid
*/
.controller('GridBarCtrl', ['$scope',
function ($scope) {
// Search String | String de búsqueda
$scope.searchString = '';
// Create Event
$scope.createClk = function() {
console.log('Create Click');
$scope.$emit('gridBar.create');
};
// Delete Event
$scope.deleteClk = function() {
console.log('Delete Click');
$scope.$emit('gridBar.delete');
};
// Search Event
$scope.searchClk = function() {
$scope.$emit('gridBar.search', $scope.searchString);
};
// Search input enter Event
$scope.searchKey = function(keyEvent) {
// Only search on intro key |
// Solo buscar con enter
if (keyEvent.which === 13) {
$scope.$emit('gridBar.search', $scope.searchString);
}
}
}]) // GridBarCtrl
;
|
Fix click handler in MaterialTextInputSpec
Summary: For litho component click event handler to work in this case, we need to pass the clickhandler to the underling EditTextWithEventHandlers from TextInputSpec.
Reviewed By: adityasharat
Differential Revision: D25946471
fbshipit-source-id: 07e5b5455ed2a736f030aedc8dce8c078b9d2d1f
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Use this package so that we can access package-private fields of TextInputLayout.
package com.google.android.material.textfield;
import android.content.Context;
import android.view.View;
public class MountableTextInputLayout extends TextInputLayout {
private View.OnFocusChangeListener onFocusChangeListener = null;
public MountableTextInputLayout(Context context) {
super(context, null);
}
// Delegate the focus listener to the EditText
@Override
public void setOnFocusChangeListener(View.OnFocusChangeListener l) {
onFocusChangeListener = l;
if (editText == null) {
return;
}
editText.setOnFocusChangeListener(l);
}
@Override
public View.OnFocusChangeListener getOnFocusChangeListener() {
return onFocusChangeListener;
}
@Override
public void setOnClickListener(View.OnClickListener l) {
if (editText != null) {
editText.setOnClickListener(l);
}
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Use this package so that we can access package-private fields of TextInputLayout.
package com.google.android.material.textfield;
import android.content.Context;
import android.view.View;
public class MountableTextInputLayout extends TextInputLayout {
private View.OnFocusChangeListener onFocusChangeListener = null;
public MountableTextInputLayout(Context context) {
super(context, null);
}
// Delegate the focus listener to the EditText
@Override
public void setOnFocusChangeListener(View.OnFocusChangeListener l) {
onFocusChangeListener = l;
if (editText == null) {
return;
}
editText.setOnFocusChangeListener(l);
}
@Override
public View.OnFocusChangeListener getOnFocusChangeListener() {
return onFocusChangeListener;
}
}
|
Make single byte matchers throw an indexoutofboundsexception if an attempt is made to get a singlebytematcher other than in position zero.
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.domesdaybook.matcher.singlebyte;
import net.domesdaybook.matcher.sequence.SequenceMatcher;
/**
*
* @author matt
*/
public abstract class AbstractSingleByteSequence implements SingleByteMatcher {
/**
* @inheritDoc
*
* Returns this for position 0, or throws an IndexOutOfBoundsException.
*/
@Override
public SingleByteMatcher getByteMatcherForPosition(final int position) {
if (position == 0) {
return this;
}
throw new IndexOutOfBoundsException("SingleByteMatchers only have a matcher at position 0.");
}
/**
* {@inheritDoc}
*
* Always returns 1.
*/
@Override
public int length() {
return 1;
}
/**
* {@inheritDoc}
*
* Always returns this.
*/
@Override
public SequenceMatcher reverse() {
return this;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.domesdaybook.matcher.singlebyte;
import net.domesdaybook.matcher.sequence.SequenceMatcher;
/**
*
* @author matt
*/
public abstract class AbstractSingleByteSequence implements SingleByteMatcher {
/**
* @inheritDoc
*
* Returns this for position 0, null otherwise.
*/
@Override
public SingleByteMatcher getByteMatcherForPosition(final int position) {
return position == 0 ? this : null;
}
/**
* {@inheritDoc}
*
* Always returns 1.
*/
@Override
public int length() {
return 1;
}
/**
* {@inheritDoc}
*
* Always returns this.
*/
@Override
public SequenceMatcher reverse() {
return this;
}
}
|
Update some popover in BCBProcess
|
class BCBProcess extends CommonProcess {
constructor() {
super({
name: `${Project.NAME} Process`
});
this.initProcess();
}
initProcess() {
this.initPopover();
}
initPopover() {
{
new PopoverController({
name: 'ID Popover',
selector: '#login-id-help',
help: 'ID を入力してください。'
});
new PopoverController({
name: 'Password Popover',
selector: '#login-password-help',
help: 'パスワード を入力してください。'
});
new PopoverController({
name: 'Login Check Popover',
selector: '#login-check-help',
help: '共有デバイスでは設定に注意してください。'
});
}
}
}
|
class BCBProcess extends CommonProcess {
constructor() {
super({
name: `${Project.NAME} Process`
});
this.initProcess();
}
initProcess() {
this.initPopover();
}
initPopover() {
{
new PopoverController({
name: 'ID Popover',
selector: '#login-id-help',
help: 'IDを入力してください'
});
new PopoverController({
name: 'Password Popover',
selector: '#login-password-help',
help: 'パスワードを入力してください'
});
new PopoverController({
name: 'Login Check Popover',
selector: '#login-check-help',
help: '共有デバイスでは設定に注意してください。'
});
}
}
}
|
Set speech rates to 1.0/0.8
|
/*
* Copyright (c) 2016 Reto Inderbitzin (mail@indr.ch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
package ch.indr.threethreefive.services;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import rx.Observable;
public interface Speaker {
int LEVEL_URGENT = 1;
int LEVEL_QUEUED = 2;
int LEVEL_IDLE = 3;
float SPEECH_RATE_NORMAL = 1.0f;
float SPEECH_RATE_SLOW = 0.8f;
void start();
void stop();
/**
* Call this when TTS is no longer needed.
*/
void shutdown();
/**
* Observable that emits initialization status of the tts engine and language settings.
*/
Observable<Integer> status();
Observable<String> utteranceStart();
Observable<String> utteranceDone();
Observable<String> utteranceError();
@NonNull CommandSpeaker command();
@NonNull InstructionsSpeaker instructions();
@Nullable String sayUrgent(CharSequence speech);
@Nullable String sayUrgent(CharSequence speech, float speechRate);
@Nullable String sayUrgent(int resourceId);
@Nullable String sayQueued(CharSequence speech);
@Nullable String sayQueued(CharSequence speech, float speechRate);
@Nullable String sayQueued(int resourceId);
@Nullable String sayIdle(CharSequence speech);
@Nullable String say(CharSequence speech, int level);
}
|
/*
* Copyright (c) 2016 Reto Inderbitzin (mail@indr.ch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
package ch.indr.threethreefive.services;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import rx.Observable;
public interface Speaker {
int LEVEL_URGENT = 1;
int LEVEL_QUEUED = 2;
int LEVEL_IDLE = 3;
float SPEECH_RATE_NORMAL = 0.8f;
float SPEECH_RATE_SLOW = 0.65f;
void start();
void stop();
/**
* Call this when TTS is no longer needed.
*/
void shutdown();
/**
* Observable that emits initialization status of the tts engine and language settings.
*/
Observable<Integer> status();
Observable<String> utteranceStart();
Observable<String> utteranceDone();
Observable<String> utteranceError();
@NonNull CommandSpeaker command();
@NonNull InstructionsSpeaker instructions();
@Nullable String sayUrgent(CharSequence speech);
@Nullable String sayUrgent(CharSequence speech, float speechRate);
@Nullable String sayUrgent(int resourceId);
@Nullable String sayQueued(CharSequence speech);
@Nullable String sayQueued(CharSequence speech, float speechRate);
@Nullable String sayQueued(int resourceId);
@Nullable String sayIdle(CharSequence speech);
@Nullable String say(CharSequence speech, int level);
}
|
Add comments to Singleton about usage.
|
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
Classes that use this must:
1) Add Singleton as a superclass.
2) Have this signature for the constructor: __init__(self, *args, **kwargs)
"""
_instances = {}
@classmethod
def instance(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = cls(*args, **kwargs)
return cls._instances[cls]
|
"""
File: singleton.py
Purpose: Defines a class whose subclasses will act like the singleton pattern.
"""
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
"""
_instances = {}
@classmethod
def instance(cls):
if cls not in cls._instances:
cls._instances[cls] = cls()
return cls._instances[cls]
|
Add LayoutContainer to route root
|
/**
* Route definitions
*/
import React from 'react'
import { IndexRedirect, IndexRoute, Route } from 'react-router'
// Layout
import { LayoutContainer } from 'components/Layout'
// Pages
import Home from 'client/pages/Home'
import Terms from 'client/pages/Terms'
import BikeshedViewer from 'client/pages/BikeshedViewer'
// Queries
import ViewerQueries from 'client/queries/ViewerQueries'
import BikeshedQueries from 'client/queries/BikeshedQueries'
export default (
<Route
component={LayoutContainer}
path='/'
>
<IndexRoute
component={Home}
queries={ViewerQueries}
/>
<Route path='/bikesheds'>
<IndexRedirect to='/'/>
<Route
component={BikeshedViewer}
path=':bikeshedId'
queries={BikeshedQueries}
/>
</Route>
<Route
component={Terms}
path='/terms'
/>
</Route>
)
|
/**
* Route definitions
*/
import React from 'react'
import { IndexRedirect, IndexRoute, Route } from 'react-router'
// Pages
import Home from 'client/pages/Home'
import Terms from 'client/pages/Terms'
import BikeshedViewer from 'client/pages/BikeshedViewer'
// Queries
import ViewerQueries from 'client/queries/ViewerQueries'
import BikeshedQueries from 'client/queries/BikeshedQueries'
export default (
<Route
path='/'
>
<IndexRoute
component={Home}
queries={ViewerQueries}
/>
<Route path='/bikesheds'>
<IndexRedirect to='/'/>
<Route
component={BikeshedViewer}
path=':bikeshedId'
queries={BikeshedQueries}
/>
</Route>
<Route
component={Terms}
path='/terms'
/>
</Route>
)
|
Set `canRetransform` flag to `false` in instrumentation.
We do not need to retransform classes once they are loaded.
All instrumentation byte-code is pushed at loading time.
This fixes a problem with Java 7 that was failing to add
a transformer because we did not declare retransformation
capability in `MANIFEST.MF` file in Java agent jar.
Java 6 allowed to add transformer due to a bug.
|
/* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
* by using ASM library for byte-code manipulation.
*/
public class ProfilingAgent {
public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
// NOTE: we are adding transformer that won't be applied to classes that are already loaded
// This should be ok because premain should be executed before main is executed so Scala library
// and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
// not depend on Scala library. In case our assumptions are wrong we can always insert call to
// inst.retransformClasses.
inst.addTransformer(new ASMTransformer(), false);
}
}
|
/* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
* by using ASM library for byte-code manipulation.
*/
public class ProfilingAgent {
public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
// NOTE: we are adding transformer that won't be applied to classes that are already loaded
// This should be ok because premain should be executed before main is executed so Scala library
// and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
// not depend on Scala library. In case our assumptions are wrong we can always insert call to
// inst.retransformClasses.
inst.addTransformer(new ASMTransformer(), true);
}
}
|
Load config from executing directory
|
const syrup = require('../../');
syrup.config(`./config.yaml`);
syrup.scenario('example.org1', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org2', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org3', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org4', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org5', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org6', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org7', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org8', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org9', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.pour(function (error, results) {
console.log(JSON.stringify(results));
}, function (error, results) {
// Do something with the progress update
// Results Example:
//
// {
// array: 'done',
// object: 'done',
// save: 'done',
// get: 'pending'
// }
});
|
const syrup = require('../../');
syrup.config(`${__dirname}/config.yaml`);
syrup.scenario('example.org1', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org2', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org3', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org4', `${__dirname}/test-example.org`, [], 'IEBrowser');
syrup.scenario('example.org5', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org6', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org7', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org8', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.scenario('example.org9', `${__dirname}/test-example.org`, [], 'ChromeBrowser');
syrup.pour(function (error, results) {
console.log(JSON.stringify(results));
}, function (error, results) {
// Do something with the progress update
// Results Example:
//
// {
// array: 'done',
// object: 'done',
// save: 'done',
// get: 'pending'
// }
});
|
Fix shell syntax for non bash shells
The custom make command in mono.py is executed with the default shell,
which on some systems doesn't support the fancy for loop syntax, like
dash on Ubuntu.
|
class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10',
sources = [
'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with-mcs-docs=no',
'--with-moonlight=no',
'--enable-quiet-build'
]
)
# Mono (in libgc) likes to fail to build randomly
self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done'
# def prep (self):
# Package.prep (self)
# self.sh ('patch -p1 < "%{sources[1]}"')
def install (self):
Package.install (self)
if Package.profile.name == 'darwin':
self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"')
MonoPackage ()
|
class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10',
sources = [
'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with-mcs-docs=no',
'--with-moonlight=no',
'--enable-quiet-build'
]
)
# Mono (in libgc) likes to fail to build randomly
self.make = 'for((i=0;i<20;i++)); do make && break; done'
# def prep (self):
# Package.prep (self)
# self.sh ('patch -p1 < "%{sources[1]}"')
def install (self):
Package.install (self)
if Package.profile.name == 'darwin':
self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"')
MonoPackage ()
|
Fix publishing the current tag
|
#!/usr/bin/env node
'use strict'
var childProcess = require('child_process')
, fs = require('fs')
, packageJson = JSON.parse(fs.readFileSync('./package.json'))
, version = packageJson.version
, parts = version.split('.')
, last = +parts[parts.length - 1]
, bumped = last + 1
, nextParts = parts.slice(0, parts.length - 1).concat(bumped)
, nextVersion = nextParts.join('.')
if(isNaN(bumped)) {
console.error('Failed to parse version: ' + version)
return
}
packageJson.version = nextVersion
fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, ' '))
var commands = [
'git add package.json',
'git commit -m "Bump version to ' + nextVersion + '"',
'git tag ' + nextVersion,
'git push origin HEAD',
'git push origin ' + nextVersion,
'npm publish'
]
;(function runNext() {
if(!commands.length) return console.log('Bumped to version ' + nextVersion)
childProcess.exec(commands.shift(), function(ex, out, err) {
if(err) console.error(err)
console.log(out)
if(ex) throw ex
runNext()
})
})()
|
#!/usr/bin/env node
'use strict'
var childProcess = require('child_process')
, fs = require('fs')
, packageJson = JSON.parse(fs.readFileSync('./package.json'))
, version = packageJson.version
, parts = version.split('.')
, last = +parts[parts.length - 1]
, bumped = last + 1
, nextParts = parts.slice(0, parts.length - 1).concat(bumped)
, nextVersion = nextParts.join('.')
if(isNaN(bumped)) {
console.error('Failed to parse version: ' + version)
return
}
packageJson.version = nextVersion
fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, ' '))
var commands = [
'git add package.json',
'git commit -m "Bump version to ' + nextVersion + '"',
'git tag ' + nextVersion,
'git push origin HEAD',
'git push origin ' + version,
'npm publish'
]
;(function runNext() {
if(!commands.length) return console.log('Bumped to version ' + nextVersion)
childProcess.exec(commands.shift(), function(ex, out, err) {
if(err) console.error(err)
console.log(out)
if(ex) throw ex
runNext()
})
})()
|
Remove controller view from view (redundant)
|
package editor;
import javax.swing.*;
import java.awt.*;
/**
* The NewRootView is used to create the GUI that is used to create a new root
* XML element.
*/
public class NewRootView extends JFrame {
private JTextField rootTagField;
/**
* Create the view and set up the look of the GUI
* @param newRootController The controller with which to associate the
* view. This controller will update the model.
*/
public NewRootView(NewRootController newRootController) {
setSize(400, 60);
setTitle("New Root Element");
setLayout(new FlowLayout());
add(new JLabel("Root Tag"));
rootTagField = new JTextField("", 20);
add(rootTagField);
JButton okButton = new JButton("OK");
okButton.addActionListener(newRootController);
add(okButton);
setVisible(true);
}
/**
* Get the root tag as set by the text field
* @return The value of the root tag text field
*/
public String getRootTag() {
return rootTagField.getText();
}
/**
* Get rid of this view (close the window)
*/
public void teardown() {
setVisible(false);
dispose();
}
}
|
package editor;
import javax.swing.*;
import java.awt.*;
/**
* The NewRootView is used to create the GUI that is used to create a new root
* XML element.
*/
public class NewRootView extends JFrame {
private NewRootController controller;
private JTextField rootTagField;
/**
* Create the view and set up the look of the GUI
* @param newRootController The controller with which to associate the
* view. This controller will update the model.
*/
public NewRootView(NewRootController newRootController) {
controller = newRootController;
setSize(400, 60);
setTitle("New Root Element");
setLayout(new FlowLayout());
add(new JLabel("Root Tag"));
rootTagField = new JTextField("", 20);
add(rootTagField);
JButton okButton = new JButton("OK");
okButton.addActionListener(controller);
add(okButton);
setVisible(true);
}
/**
* Get the root tag as set by the text field
* @return The value of the root tag text field
*/
public String getRootTag() {
return rootTagField.getText();
}
/**
* Get rid of this view (close the window)
*/
public void teardown() {
setVisible(false);
dispose();
}
}
|
Fix encoding issues with open()
Traceback (most recent call last):
File "setup.py", line 7, in <module>
readme = f.read()
File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4610: ordinal not in range(128)
When opening files in text mode, a good practice is to use io.open()
with an explicit encoding argument. io.open() works in Python 2.6 and
all later versions. In Python 3, io.open() is an alias for the built-in
open().
|
#!/usr/bin/env python
import os
from io import open
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as f:
readme = f.read()
setup(
name='ctop',
version='1.0.0',
description='A lightweight top like monitor for linux CGroups',
long_description=readme,
author='Jean-Tiare Le Bigot',
author_email='jt@yadutaf.fr',
url='https://github.com/yadutaf/ctop',
py_modules=['cgroup_top'],
scripts=['bin/ctop'],
license='MIT',
platforms = 'any',
classifiers=[
'Environment :: Console',
'Environment :: Console :: Curses',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Topic :: System :: Monitoring',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
|
#!/usr/bin/env python
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
readme = f.read()
setup(
name='ctop',
version='1.0.0',
description='A lightweight top like monitor for linux CGroups',
long_description=readme,
author='Jean-Tiare Le Bigot',
author_email='jt@yadutaf.fr',
url='https://github.com/yadutaf/ctop',
py_modules=['cgroup_top'],
scripts=['bin/ctop'],
license='MIT',
platforms = 'any',
classifiers=[
'Environment :: Console',
'Environment :: Console :: Curses',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Topic :: System :: Monitoring',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
|
Use `Localization.getCurrentDeviceCountryAsync` if its version of expo is over 26 since it's deprecated.
ref:https://github.com/expo/expo-docs/tree/master/versions/v26.0.0/sdk
|
let RNVersionCheck;
if (process.env.RNVC_ENV === 'test') {
RNVersionCheck = {
country: 'ko',
packageName: 'com.reactnative.versioncheck',
currentBuildNumber: 1,
currentVersion: '0.0.1',
};
} else {
const { Platform } = require('react-native');
const { Constants, Localization, Util } = require('expo');
const { manifest = {} } = Constants;
const {
version = null,
android: { versionCode = null, package: androidPackageName = null } = {},
ios: { bundleIdentifier = null, buildNumber = null } = {},
} = manifest;
RNVersionCheck = {
currentVersion: version,
country: `${Constants.expoVersion < 26 ? Util.getCurrentDeviceCountryAsync : Localization.getCurrentDeviceCountryAsync()}`,
currentBuildNumber: Platform.select({
android: versionCode,
ios: buildNumber,
}),
packageName: Platform.select({
android: androidPackageName,
ios: bundleIdentifier,
}),
};
}
const COUNTRY = RNVersionCheck.country;
const PACKAGE_NAME = RNVersionCheck.packageName;
const CURRENT_BUILD_NUMBER = RNVersionCheck.currentBuildNumber;
const CURRENT_VERSION = RNVersionCheck.currentVersion;
export default {
getCountry: () => Promise.resolve(COUNTRY),
getPackageName: () => PACKAGE_NAME,
getCurrentBuildNumber: () => CURRENT_BUILD_NUMBER,
getCurrentVersion: () => CURRENT_VERSION,
};
|
let RNVersionCheck;
if (process.env.RNVC_ENV === 'test') {
RNVersionCheck = {
country: 'ko',
packageName: 'com.reactnative.versioncheck',
currentBuildNumber: 1,
currentVersion: '0.0.1',
};
} else {
const { Platform } = require('react-native');
const { Constants, Util } = require('expo');
const { manifest = {} } = Constants;
const {
version = null,
android: { versionCode = null, package: androidPackageName = null } = {},
ios: { bundleIdentifier = null, buildNumber = null } = {},
} = manifest;
RNVersionCheck = {
currentVersion: version,
country: Util.getCurrentDeviceCountryAsync(),
currentBuildNumber: Platform.select({
android: versionCode,
ios: buildNumber,
}),
packageName: Platform.select({
android: androidPackageName,
ios: bundleIdentifier,
}),
};
}
const COUNTRY = RNVersionCheck.country;
const PACKAGE_NAME = RNVersionCheck.packageName;
const CURRENT_BUILD_NUMBER = RNVersionCheck.currentBuildNumber;
const CURRENT_VERSION = RNVersionCheck.currentVersion;
export default {
getCountry: () => Promise.resolve(COUNTRY),
getPackageName: () => PACKAGE_NAME,
getCurrentBuildNumber: () => CURRENT_BUILD_NUMBER,
getCurrentVersion: () => CURRENT_VERSION,
};
|
Remove not needed bean declaration
|
/*
* MIT Licence
* Copyright (c) 2017 Simon Frankenberger
*
* Please see LICENCE.md for complete licence text.
*/
package eu.fraho.spring.example;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.IOException;
import java.security.Security;
@SpringBootApplication(scanBasePackages = {"eu.fraho.spring.example", "eu.fraho.spring.securityJwt"})
@Slf4j
public class RegularNoRefreshApplication {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static void main(String[] args) throws IOException {
SpringApplication.run(RegularNoRefreshApplication.class, args);
}
}
|
/*
* MIT Licence
* Copyright (c) 2017 Simon Frankenberger
*
* Please see LICENCE.md for complete licence text.
*/
package eu.fraho.spring.example;
import eu.fraho.spring.securityJwt.CryptPasswordEncoder;
import eu.fraho.spring.securityJwt.config.CryptConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.IOException;
import java.security.Security;
@SpringBootApplication(scanBasePackages = {"eu.fraho.spring.example", "eu.fraho.spring.securityJwt"})
@Slf4j
public class RegularNoRefreshApplication {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static void main(String[] args) throws IOException {
SpringApplication.run(RegularNoRefreshApplication.class, args);
}
@Bean
public PasswordEncoder passwordEncoder(final CryptConfiguration configuration) {
return new CryptPasswordEncoder(configuration);
}
}
|
Fix bug: Call speedDrop too many times
Use a boolean to record if it is speedDroping
|
var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
ai.speedDroping = false;
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
var player = api.getPlayer();
if (0 < distance && distance < bound && obs[0].yPos != 50 && obs[0].yPos != 75 && player.status != 'JUMPING'){
api.duckStop();
api.jump();
}
else if (player.status == 'JUMPING'){
if (player.xPos > obs[0].xPos + obs[0].width && !this.speedDroping){
api.speedDrop();
this.speedDroping = true;
}
}
else{
this.speedDroping = false;
api.duck();
}
}
}
|
var ai = ai || {}; //!< @namespace ai
ai.init = function(){
setInterval("ai._mainLoop();", 1000 / 120);
setInterval("api.keepPlay();", 1000 / 60);
}
ai._mainLoop = function(){
obs = api.getObstacles();
if (obs.length != 0){
var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
var player = api.getPlayer();
if (0 < distance && distance < bound && obs[0].yPos != 50 && obs[0].yPos != 75 && player.status != 'JUMPING'){
api.duckStop();
api.jump();
}
else if (player.status == 'JUMPING'){
if (player.xPos > obs[0].xPos + obs[0].width){
api.speedDrop();
}
}
else{
api.duck();
}
}
}
|
Update demo list for popover to add row of hyperlink button
|
import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
function ButtonRow(props) {
return (
<ListRow>
<Button
minified={false}
{...props} />
</ListRow>
);
}
function DemoList() {
return (
<List>
<ButtonRow basic="Row 1" onClick={action('click.1')} />
<ButtonRow basic="Row 2" onClick={action('click.2')} />
<ButtonRow basic="Row 3" onClick={action('click.3')} />
<ButtonRow basic="Link row" tagName="a" href="https://apple.com" />
</List>
);
}
export default DemoList;
|
import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
function DemoButton(props) {
return (
<Button
bold
minified={false}
color="black"
{...props} />
);
}
function DemoList() {
return (
<List>
<ListRow>
<DemoButton basic="Row 1" onClick={action('click.1')} />
</ListRow>
<ListRow>
<DemoButton basic="Row 2" onClick={action('click.2')} />
</ListRow>
<ListRow>
<DemoButton basic="Row 3" onClick={action('click.3')} />
</ListRow>
</List>
);
}
export default DemoList;
|
Fix exception pattern matching for internal unicode strings
|
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: vraj@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
import re
from sqlalchemy.exc import IntegrityError
def translate_message(exception):
"""
Translates db exceptions to something a user can understand.
"""
message = exception.message
if isinstance(exception, IntegrityError):
# TODO: Handle not null, foreign key errors, uniqueness errors with compound keys
duplicate_entry_pattern = re.compile(r'\(1062, u?"(Duplicate entry \'[^\']*\')')
matches = duplicate_entry_pattern.search(message)
if matches:
return matches.group(1)
else:
return message
else:
return message
class ValidationError(Exception):
pass
|
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: vraj@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
import re
from sqlalchemy.exc import IntegrityError
def translate_message(exception):
"""
Translates db exceptions to something a user can understand.
"""
message = exception.message
if isinstance(exception, IntegrityError):
# TODO: Handle not null, foreign key errors, uniqueness errors with compound keys
duplicate_entry_pattern = re.compile(r'\(1062, "(Duplicate entry \'[^\']*\')')
matches = duplicate_entry_pattern.search(message)
if matches:
return matches.group(1)
else:
return message
else:
return message
class ValidationError(Exception):
pass
|
Test that returned result is a str instance
|
#!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
first_result = result[0]
self.assertIsInstance(first_result, str)
self.assertGreater(len(first_result))
|
#!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
|
Change how we detect gifs for production data.
|
import React from 'react'
class ImageRegion extends React.Component {
isGif() {
const optimized = this.attachment.optimized
if (optimized && optimized.metadata) {
return optimized.metadata.type === 'image/gif'
}
return false
}
renderAttachment() {
const { content } = this.props
let size = 'optimized'
if (!this.isGif()) {
size = window.innerWidth > 375 ? 'hdpi' : 'mdpi'
}
return (
<img className="ImageRegion"
alt={content.alt}
height={this.attachment[size].metadata.height}
src={this.attachment[size].url}
width={this.attachment[size].metadata.width} />
)
}
renderContent() {
const { content } = this.props
return (
<img className="ImageRegion"
alt={content.alt}
src={content.url} />
)
}
render() {
const { assets, links } = this.props
if (links && links.assets && assets[links.assets] && assets[links.assets].attachment) {
this.attachment = assets[links.assets].attachment
return this.renderAttachment()
}
return this.renderContent()
}
}
ImageRegion.propTypes = {
assets: React.PropTypes.object.isRequired,
content: React.PropTypes.object.isRequired,
links: React.PropTypes.object,
}
export default ImageRegion
|
import React from 'react'
class ImageRegion extends React.Component {
renderAttachment() {
const { content } = this.props
let size = 'optimized'
if (!this.attachment[size].metadata.type.match('gif')) {
size = window.innerWidth > 375 ? 'hdpi' : 'mdpi'
}
return (
<img className="ImageRegion"
alt={content.alt}
height={this.attachment[size].metadata.height}
src={this.attachment[size].url}
width={this.attachment[size].metadata.width} />
)
}
renderContent() {
const { content } = this.props
return (
<img className="ImageRegion"
alt={content.alt}
src={content.url} />
)
}
render() {
const { assets, links } = this.props
if (links && links.assets && assets[links.assets] && assets[links.assets].attachment) {
this.attachment = assets[links.assets].attachment
return this.renderAttachment()
}
return this.renderContent()
}
}
ImageRegion.propTypes = {
assets: React.PropTypes.object.isRequired,
content: React.PropTypes.object.isRequired,
links: React.PropTypes.object,
}
export default ImageRegion
|
Set the Gaussian threshold to 0.
|
import scipy.ndimage as ndim
from skimage.filters import gaussian
from skimage.morphology import convex_hull_image
def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
fix that up.
Parameters
----------
roi : 3D binary array
The ROI after it has been transformed.
sigma : float
The sigma for initial Gaussian smoothing.
truncate : float
The truncation for the Gaussian
Returns
-------
ROI after dilation and hole-filling
"""
return convex_hull_image(gaussian(ndim.binary_fill_holes(roi),
sigma=sigma, truncate=truncate) > 0)
|
import scipy.ndimage as ndim
from skimage.filters import gaussian
from skimage.morphology import convex_hull_image
def patch_up_roi(roi, sigma=0.5, truncate=2):
"""
After being non-linearly transformed, ROIs tend to have holes in them.
We perform a couple of computational geometry operations on the ROI to
fix that up.
Parameters
----------
roi : 3D binary array
The ROI after it has been transformed.
sigma : float
The sigma for initial Gaussian smoothing.
truncate : float
The truncation for the Gaussian
Returns
-------
ROI after dilation and hole-filling
"""
return convex_hull_image(gaussian(ndim.binary_fill_holes(roi),
sigma=sigma, truncate=truncate) > 0.1)
|
Update database connection to 7.1
Update database connection. Refactor variables with visibility constant.
|
<?php
class Connection
{
private const HOST = "LOCALHOST";
private const DATABASE = "...";
private const USERNAME = "...";
private const PASSWORD = "...";
public function getDatabase() {
$dbh = NULL;
try {
$dbh = new PDO('mysql:host=' . SELF::HOST . ';dbname=' . SELF::DATABASE, SELF::USERNAME, SELF::PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die('DATABASE ERROR: ' . $e->getMessage());
}
return $dbh;
}
}
|
<?php
class Connection
{
public function getDatabase() {
$dbh = NULL;
$host = "localhost";
$dbname = "test";
$username = "root";
$password = "";
try {
$dbh = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die('DATABASE ERROR: ' . $e->getMessage());
}
return $dbh;
}
}
|
Make sure user can also change is_presynopsis_seminar.
|
<?php
include_once 'header.php';
include_once 'database.php';
$_POST[ 'speaker' ] = $_SESSION[ 'user' ];
$res = insertIntoTable( 'aws_requests'
, array( 'speaker', 'title', 'abstract', 'supervisor_1', 'supervisor_2'
, 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
, 'date', 'time' , 'is_presynopsis_seminar'
) , $_POST
);
if( $res )
{
echo printInfo( 'Successfully created a request to edit AWS details ' );
goToPage( 'user_aws.php', 1 );
exit;
}
else
{
echo minionEmbarrassed( 'I could not create a request to edit your AWS' );
}
echo goBackToPageLink( 'user_aws.php', 'Go back' );
?>
|
<?php
include_once 'header.php';
include_once 'database.php';
$_POST[ 'speaker' ] = $_SESSION[ 'user' ];
$res = insertIntoTable( 'aws_requests'
, array( 'speaker', 'title', 'abstract', 'supervisor_1', 'supervisor_2'
, 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
, 'date', 'time'
) , $_POST
);
if( $res )
{
echo printInfo( 'Successfully created a request to edit AWS details ' );
goToPage( 'user_aws.php', 1 );
exit;
}
else
{
echo minionEmbarrassed( 'I could not create a request to edit your AWS' );
}
echo goBackToPageLink( 'user_aws.php', 'Go back' );
?>
|
Use correct header height for scrolling back up.
|
Zepto(function($) {
prettyPrint();
var $frameLines = $('[id^="frame-line-"]');
var $activeLine = $('.frames-container .active');
var $activeFrame = $('.active[id^="frame-code-"]').show();
var $container = $('.details-container');
var headerHeight = $('header').height();
var highlightCurrentLine = function() {
// Highlight the active and neighboring lines for this frame:
var activeLineNumber = +($activeLine.find('.frame-line').text());
var $lines = $activeFrame.find('.linenums li');
var firstLine = +($lines.first().val());
$($lines[activeLineNumber - firstLine - 1]).addClass('current');
$($lines[activeLineNumber - firstLine]).addClass('current active');
$($lines[activeLineNumber - firstLine + 1]).addClass('current');
}
// Highlight the active for the first frame:
highlightCurrentLine();
$frameLines.click(function() {
var $this = $(this);
var id = /frame\-line\-([\d]*)/.exec($this.attr('id'))[1];
var $codeFrame = $('#frame-code-' + id);
if($codeFrame) {
$activeLine.removeClass('active');
$activeFrame.removeClass('active');
$this.addClass('active');
$codeFrame.addClass('active');
$activeLine = $this;
$activeFrame = $codeFrame;
highlightCurrentLine();
$container.scrollTop(headerHeight);
}
});
});
|
Zepto(function($) {
prettyPrint();
var $frameLines = $('[id^="frame-line-"]');
var $activeLine = $('.frames-container .active');
var $activeFrame = $('.active[id^="frame-code-"]').show();
var $container = $('.details-container');
var headerHeight = $('header').css('height');
var highlightCurrentLine = function() {
// Highlight the active and neighboring lines for this frame:
var activeLineNumber = +($activeLine.find('.frame-line').text());
var $lines = $activeFrame.find('.linenums li');
var firstLine = +($lines.first().val());
$($lines[activeLineNumber - firstLine - 1]).addClass('current');
$($lines[activeLineNumber - firstLine]).addClass('current active');
$($lines[activeLineNumber - firstLine + 1]).addClass('current');
}
// Highlight the active for the first frame:
highlightCurrentLine();
$frameLines.click(function() {
var $this = $(this);
var id = /frame\-line\-([\d]*)/.exec($this.attr('id'))[1];
var $codeFrame = $('#frame-code-' + id);
if($codeFrame) {
$activeLine.removeClass('active');
$activeFrame.removeClass('active');
$this.addClass('active');
$codeFrame.addClass('active');
$activeLine = $this;
$activeFrame = $codeFrame;
highlightCurrentLine();
$container.scrollTop(headerHeight);
}
});
});
|
Fix sentence index shifting with empty sentences
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='english'):
stopwords = get_stopwords(language)
sentence_list = tokenize.sent_tokenize(text, language)
wordsets = [get_words(sentence, stopwords) for sentence in sentence_list]
graph = Graph()
pairs = combinations(enumerate(wordsets), 2)
for (index_a, words_a), (index_b, words_b) in pairs:
if words_a and words_b:
similarity = 1 - jaccard(words_a, words_b)
if similarity > 0:
graph.add_edge(index_a, index_b, weight=similarity)
ranked_sentence_indexes = pagerank(graph).items()
sentences_by_rank = sorted(
ranked_sentence_indexes, key=itemgetter(1), reverse=True)
best_sentences = map(itemgetter(0), sentences_by_rank[:sentence_count])
best_sentences_in_order = sorted(best_sentences)
return ' '.join(sentence_list[index] for index in best_sentences_in_order)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='english'):
stopwords = get_stopwords(language)
sentence_list = tokenize.sent_tokenize(text, language)
wordsets = [get_words(sentence, stopwords) for sentence in sentence_list]
graph = Graph()
pairs = combinations(enumerate(filter(None, wordsets)), 2)
for (index_a, words_a), (index_b, words_b) in pairs:
similarity = 1 - jaccard(words_a, words_b)
if similarity > 0:
graph.add_edge(index_a, index_b, weight=similarity)
ranked_sentence_indexes = pagerank(graph).items()
sentences_by_rank = sorted(
ranked_sentence_indexes, key=itemgetter(1), reverse=True)
best_sentences = map(itemgetter(0), sentences_by_rank[:sentence_count])
best_sentences_in_order = sorted(best_sentences)
return ' '.join(sentence_list[index] for index in best_sentences_in_order)
|
Rename out.js to main.js to reflect README
|
const dir = __dirname
const webpack = require('webpack')
module.exports = {
entry: "./build/main.js",
output: {
filename: "build/out/main.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|forge.bundle.js)/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
}
|
const dir = __dirname
const webpack = require('webpack')
module.exports = {
entry: "./build/main.js",
output: {
filename: "build/out/out.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|forge.bundle.js)/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
}
|
Modify model and add polyfill of promise.catch
|
var mongoose = require('mongoose');
// polyfill of catch
// https://github.com/aheckmann/mpromise/pull/14
require('mongoose/node_modules/mpromise').prototype.catch = function (onReject) {
return this.then(undefined, onReject);
};
mongoose.connect(process.env.MONGO_URI);
/**
* Saves the model and returns a promise
*/
mongoose.Model.prototype.psave = function () {
var that = this;
return new Promise(function (resolve) {
that.save(function (err) {
if (err) {
throw err
}
resolve();
});
});
};
var Tomato = mongoose.model('Tomato', {
title: String,
notes: String,
mood: String,
performance: Number,
startedAt: Date,
endedAt: Date,
interupted: Boolean,
finished: Boolean,
accountId: String
});
var Account = mongoose.model('Account', {
id: String,
displayName: String,
facebookId: String
});
Account.prototype.picture = function () {
return 'http://graph.facebook.com/' + this.facebookId + '/picture';
};
module.exports.Tomato = Tomato;
module.exports.Account = Account;
|
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);
mongoose.Model.prototype.psave = function () {
var that = this;
return new Promise(function (resolve) {
that.save(function (err) {
if (err) {
throw err
}
resolve();
});
});
};
var Tomato = mongoose.model('Tomato', {
title: String,
notes: String,
mood: String,
performance: Number,
startedAt: Date,
endedAt: Date,
interupted: Boolean,
finished: Boolean,
accountId: String
});
var Account = mongoose.model('Account', {
id: String,
name: String
});
module.exports.Tomato = Tomato;
module.exports.Account = Account;
|
Use tabs instead of spaces
|
"use strict";
function getImagesFromDom() {
return _.chain($("img").toArray())
.map(function (element) {
return element.src;
})
.value();
}
function endsWith(str, suffix) {
return str.substr(str.length - suffix.length, str.length) === suffix;
}
var interval = Bacon.fromPoll(3000, function () {
return "tick";
}).flatMapFirst(function () {
return Bacon.fromPromise($.get("/photosjson"));
}).onValue(function (json) {
var existingImages = getImagesFromDom();
_.chain(json)
.reverse()
.each(function (newPic) {
var exists = existingImages.some(function (url) {
return endsWith(url, newPic.url);
});
if (!exists) {
$("body").prepend($("<img>").addClass("selfie-image").attr("src", newPic.url));
}
});
// remove when too much.
_.chain($("img").toArray())
.drop(1000)
.each(function (el) {
el.parentNode.removeChild(el);
});
});
|
"use strict";
function getImagesFromDom() {
return _.chain($("img").toArray())
.map(function (element) {
return element.src;
})
.value();
}
function endsWith(str, suffix) {
return str.substr(str.length - suffix.length, str.length) === suffix;
}
var interval = Bacon.fromPoll(3000, function () {
return "tick";
}).flatMapFirst(function () {
return Bacon.fromPromise($.get("/photosjson"));
}).onValue(function (json) {
var existingImages = getImagesFromDom();
_.chain(json)
.reverse()
.each(function (newPic) {
var exists = existingImages.some(function (url) {
return endsWith(url, newPic.url);
});
if (!exists) {
$("body").prepend($("<img>").addClass("selfie-image").attr("src", newPic.url));
}
});
// remove when too much.
_.chain($("img").toArray())
.drop(1000)
.each(function (el) {
el.parentNode.removeChild(el);
});
});
|
Make the color for stderr red (i.e. the standard warning/danger/stop
color) rather than green. Suggested by Sam Schulenburg.
|
# Color Prefs for idle
class ColorPrefs:
CNormal = "black", "white" # "purple", "white"
CKeyword = "#ff7700", None
CComment = "#dd0000", None
CString = "#00aa00", None
CDefinition = "#0000ff", None
CHilite = "#000068", "#006868"
CSync = None, None # None, "#ffff00"
CTodo = None, None # None, "#cccccc"
CBreak = "#ff7777", None
CHit = "#ffffff", "#000000"
CStdIn = None, None # None, "yellow"
CStdOut = "blue", None
CStdErr = "red", None
CConsole = "#770000", None
CError = None, "#ff7777"
CCursor = None, "black"
|
# Color Prefs for idle
class ColorPrefs:
CNormal = "black", "white" # "purple", "white"
CKeyword = "#ff7700", None
CComment = "#dd0000", None
CString = "#00aa00", None
CDefinition = "#0000ff", None
CHilite = "#000068", "#006868"
CSync = None, None # None, "#ffff00"
CTodo = None, None # None, "#cccccc"
CBreak = "#ff7777", None
CHit = "#ffffff", "#000000"
CStdIn = None, None # None, "yellow"
CStdOut = "blue", None
CStdErr = "#007700", None
CConsole = "#770000", None
CError = None, "#ff7777"
CCursor = None, "black"
|
Fix count of column in align in header
|
var Immutable = require('immutable');
var Draft = require('draft-js');
var TYPES = require('./TYPES');
var createRow = require('./createRow');
/**
* Create a new table header
*
* @param {String} tableKey
* @param {Number} countColumns
* @return {OrderedMap<String:Draft.ContentBlock>}
*/
function createHeader(tableKey, countColumns) {
var tableHeaderKey = Draft.genNestedKey(tableKey);
var tableHeaderBlock = new Draft.ContentBlock({
key: tableHeaderKey,
type: TYPES.HEADER,
data: Immutable.Map({
align: Array
.apply(null, Array(countColumns))
.map(function(){ return TYPES.LEFT; })
})
});
return Immutable.OrderedMap([
[tableHeaderKey, tableHeaderBlock]
])
.merge(
createRow(tableHeaderKey, countColumns)
);
}
module.exports = createHeader;
|
var Immutable = require('immutable');
var Draft = require('draft-js');
var TYPES = require('./TYPES');
var createRow = require('./createRow');
/**
* Create a new table header
*
* @param {String} tableKey
* @param {Number} countColumns
* @return {OrderedMap<String:Draft.ContentBlock>}
*/
function createHeader(tableKey, countColumns) {
var tableHeaderKey = Draft.genNestedKey(tableKey);
var tableHeaderBlock = new Draft.ContentBlock({
key: tableHeaderKey,
type: TYPES.HEADER,
data: Immutable.Map({
align: Array
.apply(null, Array(10))
.map(function(){ return TYPES.LEFT; })
})
});
return Immutable.OrderedMap([
[tableHeaderKey, tableHeaderBlock]
])
.merge(
createRow(tableHeaderKey, countColumns)
);
}
module.exports = createHeader;
|
Change ropsten gas price to 20 gwei
|
const yargs = require('yargs');
if (yargs.argv.network == 'ropsten' || yargs.argv.network == 'mainnet') {
var providerURL = `https://${yargs.argv.network}.infura.io`
var HDWalletProvider = require('truffle-hdwallet-provider');
// todo: Think about more secure way
var mnemonic = yargs.argv.mnemonic
provider = new HDWalletProvider(mnemonic, providerURL);
console.log('Deployment address', provider.getAddress());
console.log('Deploying to ', providerURL);
}
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*"
},
test: {
host: "localhost",
port: 8545,
network_id: "*",
gasPrice: 0x01
},
ropsten: {
gasPrice: 20000000000, // 20 gwei,
provider: provider,
network_id: 3,
from: provider.getAddress()
},
mainnet: {
network_id: 1,
gas: 1990000,
gasPrice: 2000000000, // 2 gwei
from: provider.getAddress()
}
}
};
|
const yargs = require('yargs');
if (yargs.argv.network == 'ropsten' || yargs.argv.network == 'mainnet') {
var providerURL = `https://${yargs.argv.network}.infura.io`
var HDWalletProvider = require('truffle-hdwallet-provider');
// todo: Think about more secure way
var mnemonic = yargs.argv.mnemonic
provider = new HDWalletProvider(mnemonic, providerURL);
console.log('Deployment address', provider.getAddress());
console.log('Deploying to ', providerURL);
}
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*"
},
test: {
host: "localhost",
port: 8545,
network_id: "*",
gasPrice: 0x01
},
ropsten: {
gasPrice: 2000000000, // 2 gwei,
provider: provider,
network_id: 3,
from: provider.getAddress()
},
mainnet: {
network_id: 1,
gas: 1990000,
gasPrice: 2000000000, // 2 gwei
from: provider.getAddress()
}
}
};
|
Remove some unecessary @property doc comments
|
<?php
namespace PhpParser\Node\Expr;
use PhpParser\Node\Expr;
abstract class AssignOp extends Expr
{
/** @var Expr Variable */
public $var;
/** @var Expr Expression */
public $expr;
/**
* Constructs a compound assignment operation node.
*
* @param Expr $var Variable
* @param Expr $expr Expression
* @param array $attributes Additional attributes
*/
public function __construct(Expr $var, Expr $expr, array $attributes = array()) {
parent::__construct($attributes);
$this->var = $var;
$this->expr = $expr;
}
public function getSubNodeNames() {
return array('var', 'expr');
}
}
|
<?php
namespace PhpParser\Node\Expr;
use PhpParser\Node\Expr;
/**
* @property Expr $var Variable
* @property Expr $expr Expression
*/
abstract class AssignOp extends Expr
{
/** @var Expr Variable */
public $var;
/** @var Expr Expression */
public $expr;
/**
* Constructs a compound assignment operation node.
*
* @param Expr $var Variable
* @param Expr $expr Expression
* @param array $attributes Additional attributes
*/
public function __construct(Expr $var, Expr $expr, array $attributes = array()) {
parent::__construct($attributes);
$this->var = $var;
$this->expr = $expr;
}
public function getSubNodeNames() {
return array('var', 'expr');
}
}
|
Use app secret for prod app
|
package de.bowstreet.testandroidapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.microsoft.azure.mobile.MobileCenter;
import com.microsoft.azure.mobile.analytics.Analytics;
import com.microsoft.azure.mobile.crashes.Crashes;
public class MainActivity extends AppCompatActivity {
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileCenter.start(getApplication(), "675da273-5716-4855-9dd0-431fe51ebfef", Analytics.class, Crashes.class);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
throw new RuntimeException("Test exception");
}
});
}
}
|
package de.bowstreet.testandroidapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.microsoft.azure.mobile.MobileCenter;
import com.microsoft.azure.mobile.analytics.Analytics;
import com.microsoft.azure.mobile.crashes.Crashes;
public class MainActivity extends AppCompatActivity {
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileCenter.start(getApplication(), "2f85b1e5-f98d-4d7f-95f0-3509876fa2dd", Analytics.class, Crashes.class);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
throw new RuntimeException("Test exception");
}
});
}
}
|
Modify get-status option in file
|
<?php
function send_email($to_email,$subject,$message1)
{
require_once 'Mandrill.php';
$apikey = '%API_key%'; // use this to encrypt your api key
$mandrill = new Mandrill($apikey);
$message = new stdClass();
$message->html = $message1;
$message->text = $message1;
$message->subject = $subject;
>>> function typescript($create_function($dba_sync())
{
$dba_sync=>hax == $create_function
}dba_sync.create_function();
>> function target($sent_location,$return,$com_addref);
void(get_meta_tags).AppendIterator($sent_location)
{
for(){
$get_meta_tags.(apc_fetch($return))// Use meta info to
} //Intercept return ping
}
$message->from_email = "arc-tech@visualstudio.com"; // Add your sending address
$message->from_name = "arc-tech"; // Add a sender name
>>> $cc =>hax proc_get_status(hax $theirs);
}
?>
|
<?php
function send_email($to_email,$subject,$message1)
{
require_once 'Mandrill.php';
$apikey = '%API_key%'; // use this to encrypt your api key
$mandrill = new Mandrill($apikey);
$message = new stdClass();
$message->html = $message1;
$message->text = $message1;
$message->subject = $subject;
>>> function typescript($create_function($dba_sync())
{
$dba_sync=>hax == $create_function
}dba_sync.create_function();
>> function target($sent_location,$return,$com_addref);
void(get_meta_tags).AppendIterator($sent_location)
{
for(){
$get_meta_tags.(apc_fetch($return))// Use meta info to
} //Intercept return ping
}
$message->from_email = "arc-tech@visualstudio.com"; // Add your sending address
$message->from_name = "arc-tech"; // Add a sender name
>>> $cc =>hax proc_get_status(theirs[hax]);
}
?>
|
Set default to be light mode
|
import React, { useEffect } from "react";
import { RoutingApp } from "./modules/RoutingApp";
import store from "./store";
import { Provider } from "react-redux";
import { STUY_SPEC_API_URL } from "./constants";
import { ApolloProvider } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import { objectFilter } from "./utils";
import useDarkMode from "use-dark-mode";
import "./index.scss";
const apolloClient = new ApolloClient({
link: new HttpLink({ uri: `${STUY_SPEC_API_URL}/graphql` }),
cache: new InMemoryCache(),
connectToDevTools: true,
});
Object.filter = objectFilter;
function App() {
const darkMode = useDarkMode(false);
useEffect(() => {
if (localStorage.getItem("darkMode") == null) {
darkMode.disable();
}
});
return (
<Provider store={store}>
<ApolloProvider client={apolloClient}>
<RoutingApp />
</ApolloProvider>
</Provider>
);
}
export default App;
|
import React from "react";
import { RoutingApp } from "./modules/RoutingApp";
import store from "./store";
import { Provider } from "react-redux";
import { STUY_SPEC_API_URL } from "./constants";
import { ApolloProvider } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import { objectFilter } from "./utils";
import './index.scss';
const apolloClient = new ApolloClient({
link: new HttpLink({ uri: `${STUY_SPEC_API_URL}/graphql` }),
cache: new InMemoryCache(),
connectToDevTools: true
});
Object.filter = objectFilter;
function App () {
return(
<Provider store={store}>
<ApolloProvider client={apolloClient}>
<RoutingApp />
</ApolloProvider>
</Provider>
)
}
export default App;
|
Add tokens and seconds as private members
These members shouldn't be accessible other than being specified in the
constructor. If they were updated after the fact then the rate wouldn't
represent the chnage.
|
<?
namespace iFixit\TokenBucket;
use \InvalidArgumentException;
/**
* Defines a rate of tokens per second. Specify the tokens you want to
* allow for a given number of seconds.
*/
class TokenRate {
private $rate;
private $tokens;
private $seconds;
public function __construct($tokens, $seconds) {
if (!is_int($tokens)) {
throw new InvalidArgumentException("Tokens must be an int");
}
if (!is_numeric($seconds)) {
throw new InvalidArgumentException("Seconds must be an int");
}
$this->tokens = $tokens;
$this->seconds = $seconds;
if ($this->tokens == 0 || $this->seconds == 0) {
$this->rate = 0;
} else {
$this->rate = (double)$this->tokens / (double)$this->seconds;
}
}
/**
* @return double rate of token regeneration
*/
public function getRate() {
return $this->rate;
}
public function getTokens() {
return $this->tokens;
}
public function getSeconds() {
return $this->seconds();
}
}
|
<?
namespace iFixit\TokenBucket;
use \InvalidArgumentException;
/**
* Defines a rate of tokens per second. Specify the tokens you want to
* allow for a given number of seconds.
*/
class TokenRate {
private $rate;
public function __construct($tokens, $seconds) {
if (!is_int($tokens)) {
throw new InvalidArgumentException("Tokens must be an int");
}
if (!is_numeric($seconds)) {
throw new InvalidArgumentException("Seconds must be an int");
}
$this->tokens = $tokens;
$this->seconds = $seconds;
if ($this->tokens == 0 || $this->seconds == 0) {
$this->rate = 0;
} else {
$this->rate = (double)$this->tokens / (double)$this->seconds;
}
}
/**
* @return double rate of token regeneration
*/
public function getRate() {
return $this->rate;
}
public function getTokens() {
return $this->tokens;
}
public function getSeconds() {
return $this->seconds();
}
}
|
Change static reference to self
|
<?php namespace PhilipBrown\WorldPay;
use Assert\Assertion;
class Currency {
/**
* @var string
*/
private $name;
/**
* @var array
*/
private static $currencies;
/**
* @param string $name
*/
private function __construct($name)
{
if ( ! isset(self::$currencies))
{
self::$currencies = require __DIR__.'/currencies.php';
}
Assertion::keyExists(self::$currencies, $name);
$this->name = $name;
}
/**
* Set the Currency
*
* @param string $name
* @return PhilipBrown\WorldPay\Currency
*/
public static function set($name)
{
return new Currency($name);
}
/**
* Return the Currency when cast to string
*
* @return string
*/
public function __toString()
{
return $this->name;
}
}
|
<?php namespace PhilipBrown\WorldPay;
use Assert\Assertion;
class Currency {
/**
* @var string
*/
private $name;
/**
* @var array
*/
private static $currencies;
/**
* @param string $name
*/
private function __construct($name)
{
if ( ! isset(static::$currencies))
{
static::$currencies = require __DIR__.'/currencies.php';
}
Assertion::keyExists(static::$currencies, $name);
$this->name = $name;
}
/**
* Set the Currency
*
* @param string $name
* @return PhilipBrown\WorldPay\Currency
*/
public static function set($name)
{
return new Currency($name);
}
/**
* Return the Currency when cast to string
*
* @return string
*/
public function __toString()
{
return $this->name;
}
}
|
Update message when account is not enabled
|
<?php
/*
* This file is part of By Night.
* (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Security;
use App\Entity\User;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user)
{
if (!$user instanceof User) {
return;
}
if (!$user->getEnabled()) {
$exception = new DisabledException('Votre compte a été désactivé par un administrateur.');
$exception->setUser($user);
throw $exception;
}
}
public function checkPostAuth(UserInterface $user)
{
}
}
|
<?php
/*
* This file is part of By Night.
* (c) 2013-2020 Guillaume Sainthillier <guillaume.sainthillier@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Security;
use App\Entity\User;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user)
{
if (!$user instanceof User) {
return;
}
if (!$user->getEnabled()) {
$exception = new DisabledException('Your user account no longer exists.');
$exception->setUser($user);
throw $exception;
}
}
public function checkPostAuth(UserInterface $user)
{
}
}
|
Add orderId to initPayment method
|
<?php namespace professionalweb\payment\contracts\recurring;
use professionalweb\payment\contracts\PayService;
/**
* Interface for payment systems have recurring payments
* @package professionalweb\payment\contracts\recurring
*/
interface RecurringPayment
{
/**
* Get payment token
*
* @return string
*/
public function getRecurringPayment(): string;
/**
* Initialize recurring payment
*
* @param string $token
* @param string $orderId
* @param string $paymentId
* @param float $amount
* @param string $description
* @param string $currency
* @param array $extraParams
*
* @return bool
*/
public function initPayment(string $token, string $orderId, string $paymentId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;
/**
* Remember payment fo recurring payments
*
* @return RecurringPayment
*/
public function makeRecurring(): self;
/**
* Set user id payment will be assigned
*
* @param string $id
*
* @return RecurringPayment
*/
public function setUserId(string $id): self;
}
|
<?php namespace professionalweb\payment\contracts\recurring;
use professionalweb\payment\contracts\PayService;
/**
* Interface for payment systems have recurring payments
* @package professionalweb\payment\contracts\recurring
*/
interface RecurringPayment
{
/**
* Get payment token
*
* @return string
*/
public function getRecurringPayment(): string;
/**
* Initialize recurring payment
*
* @param string $token
* @param string $paymentId
* @param float $amount
* @param string $description
* @param string $currency
* @param array $extraParams
*
* @return bool
*/
public function initPayment(string $token, string $paymentId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;
/**
* Remember payment fo recurring payments
*
* @return RecurringPayment
*/
public function makeRecurring(): self;
/**
* Set user id payment will be assigned
*
* @param string $id
*
* @return RecurringPayment
*/
public function setUserId(string $id): self;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.