text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix ember-app-loader error on invalid modules | const HarmonyExportExpressionDependency
= require( "webpack/lib/dependencies/HarmonyExportExpressionDependency" );
const HarmonyExportSpecifierDependency
= require( "webpack/lib/dependencies/HarmonyExportSpecifierDependency" );
const HarmonyExportImportedSpecifierDependency
= require( "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" );
module.exports = function getModuleExportsFactory( loaderContext ) {
return path => new Promise( ( resolve, reject ) => {
loaderContext.loadModule( path, ( error, source, sourceMap, { dependencies } = {} ) => {
if ( error || !dependencies ) {
return reject( error );
}
// does the module have a default export?
const exports = dependencies.find( d => d instanceof HarmonyExportExpressionDependency )
// just resolve with the default export name
? [ "default" ]
// get the list of all export names instead
: dependencies
.filter( d =>
d instanceof HarmonyExportSpecifierDependency
|| d instanceof HarmonyExportImportedSpecifierDependency
)
.map( dependency => dependency.name );
resolve( exports );
});
});
};
| const HarmonyExportExpressionDependency
= require( "webpack/lib/dependencies/HarmonyExportExpressionDependency" );
const HarmonyExportSpecifierDependency
= require( "webpack/lib/dependencies/HarmonyExportSpecifierDependency" );
const HarmonyExportImportedSpecifierDependency
= require( "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" );
module.exports = function getModuleExportsFactory( loaderContext ) {
return path => new Promise( ( resolve, reject ) => {
loaderContext.loadModule( path, ( error, source, sourceMap, { dependencies } ) => {
if ( error || !dependencies ) {
return reject( error );
}
// does the module have a default export?
const exports = dependencies.find( d => d instanceof HarmonyExportExpressionDependency )
// just resolve with the default export name
? [ "default" ]
// get the list of all export names instead
: dependencies
.filter( d =>
d instanceof HarmonyExportSpecifierDependency
|| d instanceof HarmonyExportImportedSpecifierDependency
)
.map( dependency => dependency.name );
resolve( exports );
});
});
};
|
Remove the noisy "Ignored line" messages for stats that are not used | package com.holmsted.gerrit;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import com.holmsted.json.JsonUtils;
public class GerritStatParser {
public List<Commit> parseCommits(String jsonCommitData) {
List<Commit> commits = new ArrayList<>();
String[] lines = jsonCommitData.split("\n");
for (String line : lines) {
try {
JSONObject lineJson = JsonUtils.readJsonString(line);
if (Commit.isCommit(lineJson)) {
commits.add(Commit.fromJson(lineJson));
// ignore the stats, log the rest in case the format changes
} else if (!lineJson.get("type").equals("stats")) {
System.err.println("Ignored line " + line);
}
} catch (JSONException ex) {
System.err.println(String.format("Not JsonObject: '%s'", line));
}
}
return commits;
}
}
| package com.holmsted.gerrit;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import com.holmsted.json.JsonUtils;
public class GerritStatParser {
public List<Commit> parseCommits(String jsonCommitData) {
List<Commit> commits = new ArrayList<>();
String[] lines = jsonCommitData.split("\n");
for (String line : lines) {
try {
JSONObject lineJson = JsonUtils.readJsonString(line);
if (Commit.isCommit(lineJson)) {
commits.add(Commit.fromJson(lineJson));
} else {
// TODO ignore for now
System.err.println("Ignored line " + line);
}
} catch (JSONException ex) {
System.err.println(String.format("Not JsonObject: '%s'", line));
}
}
return commits;
}
}
|
Fix namespace issue in plugin manager. | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-08-22 21:30
from __future__ import unicode_literals
import os
from django.conf import settings
from django.db import migrations, models
import sal.plugin
from server.models import Plugin
from server import utils
# TODO: I don't think we need this in the DB.
def update_os_families(apps, schema_editor):
enabled_plugins = Plugin.objects.all()
manager = sal.plugin.PluginManager()
enabled_plugins = apps.get_model("server", "MachineDetailPlugin")
for item in enabled_plugins.objects.all():
default_families = ['Darwin', 'Windows', 'Linux', 'ChromeOS']
plugin = manager.get_plugin_by_name(item.name)
if plugin:
try:
supported_os_families = plugin.plugin_object.get_supported_os_families()
except Exception:
supported_os_families = default_families
item.os_families = sorted(utils.stringify(supported_os_families))
item.save()
class Migration(migrations.Migration):
dependencies = [
('server', '0057_auto_20170822_1421'),
]
operations = [
migrations.RunPython(update_os_families),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-08-22 21:30
from __future__ import unicode_literals
import os
from django.conf import settings
from django.db import migrations, models
import sal.plugin
from server.models import Plugin
from server import utils
# TODO: I don't think we need this in the DB.
def update_os_families(apps, schema_editor):
enabled_plugins = Plugin.objects.all()
manager = PluginManager()
enabled_plugins = apps.get_model("server", "MachineDetailPlugin")
for item in enabled_plugins.objects.all():
default_families = ['Darwin', 'Windows', 'Linux', 'ChromeOS']
plugin = manager.get_plugin_by_name(item.name)
if plugin:
try:
supported_os_families = plugin.plugin_object.get_supported_os_families()
except Exception:
supported_os_families = default_families
item.os_families = sorted(utils.stringify(supported_os_families))
item.save()
class Migration(migrations.Migration):
dependencies = [
('server', '0057_auto_20170822_1421'),
]
operations = [
migrations.RunPython(update_os_families),
]
|
Bump django.VERSION for RC 1.
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@11289 bcc190cf-cafb-0310-a4f2-bffc1f526a37 | VERSION = (1, 1, 0, 'rc', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| VERSION = (1, 1, 0, 'beta', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
|
Add fix for browsers without window.console. | $(function() {
// Dummy console for IE7
if (window.console === undefined) window.console = {log: function() {}};
var cookie_name = $('body').attr('data-mobile-cookie');
$(".desktop-link").attr("href", window.location).click(function() {
$.cookie(cookie_name, "off", {expires:30});
});
$(".mobile-link").attr("href", window.location).click(function() {
$.cookie(cookie_name, "on", {expires:30});
});
$('#browserid').click(function(e) {
e.preventDefault();
navigator.id.getVerifiedEmail(function(assertion) {
if (assertion) {
var $e = $('#id_assertion');
$e.val(assertion.toString());
$e.parent().submit();
}
});
});
});
| $(function() {
var cookie_name = $('body').attr('data-mobile-cookie');
$(".desktop-link").attr("href", window.location).click(function() {
$.cookie(cookie_name, "off", {expires:30});
});
$(".mobile-link").attr("href", window.location).click(function() {
$.cookie(cookie_name, "on", {expires:30});
});
$('#browserid').click(function(e) {
e.preventDefault();
navigator.id.getVerifiedEmail(function(assertion) {
if (assertion) {
var $e = $('#id_assertion');
$e.val(assertion.toString());
$e.parent().submit();
}
});
});
});
|
Refactor to follow style guides | import Ember from 'ember';
/** @module sl-components/components/sl-loading-icon */
export default Ember.Component.extend({
/**
* The HTML element type for this component
*
* @property {Ember.String} tagName
* @default "span"
*/
tagName: 'span',
/**
* Class names for the root element
*
* @property {Ember.Array} classNames
*/
classNames: [ 'sl-loading-icon' ],
/**
* Class name bindings for the root element
*
* @property {Ember.Array} classNameBindings
*/
classNameBindings: [ 'inverse:sl-loading-icon-light:sl-loading-icon-dark' ],
/**
* Whether to use the inverse (lighter colored) icon
*
* @property {boolean} inverse
* @default false
*/
inverse: false
});
| import Ember from 'ember';
/**
* @module components
* @class sl-loading-icon
*/
export default Ember.Component.extend({
/**
* Class name bindings for the root element
*
* @property {array} classNameBindings
*/
classNameBindings: [ 'inverse:sl-loading-icon-light:sl-loading-icon-dark' ],
/**
* Class names for the root element
*
* @property {array} classNames
*/
classNames: [ 'sl-loading-icon' ],
/**
* Whether to use the inverse (lighter colored) icon
*
* @property {boolean} inverse
* @default false
*/
inverse: false,
/**
* The HTML element type for this component
*
* @property {string} tagName
* @default "span"
*/
tagName: 'span'
});
|
Add some basic video element. | /**
* External dependencies
*/
import PropTypes from 'prop-types';
import styled from 'styled-components';
/**
* Internal dependencies
*/
import { ElementWithPosition, ElementWithSize, ElementWithRotation } from '../shared';
const Element = styled.video`
${ ElementWithPosition }
${ ElementWithSize }
${ ElementWithRotation }
`;
function VideoDisplay( props ) {
const {
mimeType,
src,
id,
} = props;
return (
<Element { ...props } >
<source src={ src } type={ mimeType } />
</Element>
);
}
VideoDisplay.propTypes = {
rotationAngle: PropTypes.number.isRequired,
controls: PropTypes.bool,
autoPlay: PropTypes.bool,
loop: PropTypes.bool,
mimeType: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
};
export default VideoDisplay;
| /**
* External dependencies
*/
import PropTypes from 'prop-types';
import styled from 'styled-components';
/**
* Internal dependencies
*/
import { ElementWithPosition, ElementWithSize, ElementWithRotation } from '../shared';
const Element = styled.video`
${ ElementWithPosition }
${ ElementWithSize }
${ ElementWithRotation }
`;
function VideoDisplay( { src, width, height, x, y, rotationAngle, controls, mimeType } ) {
const props = {
width,
height,
x,
y,
rotationAngle,
controls,
};
return (
<Element { ...props }>
<source src={ src } type={ mimeType } />
</Element>
);
}
VideoDisplay.propTypes = {
rotationAngle: PropTypes.number.isRequired,
controls: PropTypes.bool,
mimeType: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
};
export default VideoDisplay;
|
Fix channel number in the comment | from time import time, sleep
from subprocess import call
from argparse import ArgumentParser
from atexit import register
from pyadtn.aDTN import aDTN
from pyadtn.utils import info, debug
EXPERIMENT_DURATION = 5 * 60 + 10 # 5 minutes and 5 seconds (in seconds)
IFACE = "wlan0"
FREQ = str(2432) # 802.11 channel 5
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument('device_id', type=str, help='the hostname of this device')
parser.add_argument('sending_freq', type=int, help='time between sending of a batch (in seconds)')
parser.add_argument('batch_size', type=int, help='batch size (in number of packets)')
args = parser.parse_args()
device_id = args.device_id
sf = args.sending_freq
bs = args.batch_size
call(("./network-setup.sh", IFACE))
call(["iw", IFACE, "ibss", "join", "test", FREQ])
# Inform about current config.
experiment_id = "throughput_" + "_".join(
[str(i) for i in ["bs", bs, "sf", sf, "cr"]])
info("\nNow running: {}".format(experiment_id))
# Start aDTN
adtn = aDTN(bs, sf, IFACE, experiment_id)
adtn.start()
sleep(EXPERIMENT_DURATION)
adtn.stop()
| from time import time, sleep
from subprocess import call
from argparse import ArgumentParser
from atexit import register
from pyadtn.aDTN import aDTN
from pyadtn.utils import info, debug
EXPERIMENT_DURATION = 5 * 60 + 10 # 5 minutes and 5 seconds (in seconds)
IFACE = "wlan0"
FREQ = str(2432) # 802.11 channel 1
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument('device_id', type=str, help='the hostname of this device')
parser.add_argument('sending_freq', type=int, help='time between sending of a batch (in seconds)')
parser.add_argument('batch_size', type=int, help='batch size (in number of packets)')
args = parser.parse_args()
device_id = args.device_id
sf = args.sending_freq
bs = args.batch_size
call(("./network-setup.sh", IFACE))
call(["iw", IFACE, "ibss", "join", "test", FREQ])
# Inform about current config.
experiment_id = "throughput_" + "_".join(
[str(i) for i in ["bs", bs, "sf", sf, "cr"]])
info("\nNow running: {}".format(experiment_id))
# Start aDTN
adtn = aDTN(bs, sf, IFACE, experiment_id)
adtn.start()
sleep(EXPERIMENT_DURATION)
adtn.stop()
|
Use async/await instead of Promise chains | 'use strict';
const fs = require('fs-extra');
const pkgUp = require('pkg-up');
const getDistTags = require('./fetch-dist-tags');
const calcDistTag = require('./calc-dist-tag');
module.exports = async function autoDistTag(cwd, options) {
let pkgPath = await pkgUp(cwd);
let pkg = await fs.readJson(pkgPath);
let tags = await getDistTags(pkg.name);
let tag = await calcDistTag(pkg.version, tags);
if (options && options.write) {
// skip writing to `package.json if an explicit publishConfig.tag is set
if ('publishConfig' in pkg && 'tag' in pkg.publishConfig) {
return;
}
// skip writing to `package.json if the calculated tag is "latest" because it's the default anyway
if (tag === 'latest') {
return;
}
pkg.publishConfig = pkg.publishConfig || {};
pkg.publishConfig.tag = tag;
fs.writeJson(pkgPath, pkg, { spaces: 2 });
}
return tag;
};
| 'use strict';
const fs = require('fs-extra');
const pkgUp = require('pkg-up');
const getDistTags = require('./fetch-dist-tags');
const calcDistTag = require('./calc-dist-tag');
module.exports = function autoDistTag(cwd, options) {
let pkgPath, pkg, tags, tag;
return pkgUp(cwd)
.then(_pkgPath => (pkgPath = _pkgPath))
.then(() => fs.readJson(pkgPath))
.then(_pkg => (pkg = _pkg))
.then(() => getDistTags(pkg.name))
.then(_tags => (tags = _tags))
.then(() => calcDistTag(pkg.version, tags))
.then(_tag => (tag = _tag))
.then(() => {
if (options && options.write) {
// skip writing to `package.json if an explicit publishConfig.tag is set
if ('publishConfig' in pkg && 'tag' in pkg.publishConfig) {
return;
}
// skip writing to `package.json if the calculated tag is "latest" because it's the default anyway
if (tag === 'latest') {
return;
}
pkg.publishConfig = pkg.publishConfig || {};
pkg.publishConfig.tag = tag;
return fs.writeJson(pkgPath, pkg, { spaces: 2 });
}
})
.then(() => tag);
};
|
Fix variable names in model. | from app import db
class User(db.Model):
__tablename__ = 'users'
username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True)
password = db.Column(db.String(192), nullable=False)
def __init__(self, username, password):
self.username = username
self.password = password
def __repr__(self):
return 'The users name is: %r' % self.username
class Patient(db.Model):
__tablename__ = 'patients'
# Used to determine which nurse triaged a patient.
# clientname = db.Column(db.String(64), db.ForeignKey('users.username'))
mobile = db.Column(db.Integer, unique=True, primary_key=True)
forename = db.Column(db.String(64), nullable=False)
surname = db.Column(db.String(64), nullable=False)
dob = db.Column(db.Date)
def __init__(self, mobile, forename, surname, dob):
self.mobile = mobile
self.forename = forename
self.surname = surname
self.dob = dob
def __repr__(self):
return 'The mobile number and name are: %r, %r %r' % (self.mobile, self.forename, self.surname)
| from app import db
class User(db.Model):
__tablename__ = 'users'
username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True)
password = db.Column(db.String(192), nullable=False)
def __init__(self, username, password):
self.username = username
self.email = password
def __repr__(self):
return 'The users name is: %r' % self.name
class Patient(db.Model):
__tablename__ = 'patients'
# Used to determine which nurse triaged a patient.
# clientname = db.Column(db.String(64), db.ForeignKey('users.username'))
mobile = db.Column(db.Integer, unique=True, primary_key=True)
forename = db.Column(db.String(64), nullable=False)
surname = db.Column(db.String(64), nullable=False)
dob = db.Column(db.Date)
def __init__(self, mobile, forename, surname, dob):
self.mobile = mobile
self.forename = forename
self.surname = surname
self.dob = dob
def __repr__(self):
return 'The mobile number and name are: %r, %r %r' % (self.mobile, self.forename, self.surname)
|
Increase rate of random sounds with broken earmuffs | package dmillerw.sound.core.item;
import dmillerw.sound.client.sound.SoundHelper;
import dmillerw.sound.client.sound.SoundReplaced;
import net.minecraft.client.audio.ISound;
import net.minecraft.client.audio.SoundCategory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
/**
* @author dmillerw
*/
public class ItemBrokenEarmuffs extends ItemMagicalEarmuffs {
public static int cooldown = 0;
public ItemBrokenEarmuffs() {
super();
setUnlocalizedName("brokenEarmuffs");
}
@Override
public boolean hasEffect(ItemStack itemStack, int pass) {
return true;
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) {
return itemStack;
}
@Override
public ISound getMuffledSound(ItemStack itemStack, String name, ISound sound, SoundCategory soundCategory) {
// Fire a random sound every other sound
if (cooldown == 0) {
cooldown = 1;
return SoundHelper.getRandomSound(sound, soundCategory);
} else {
cooldown--;
return new SoundReplaced(sound, sound.getPositionedSoundLocation());
}
}
}
| package dmillerw.sound.core.item;
import dmillerw.sound.client.sound.SoundHelper;
import dmillerw.sound.client.sound.SoundReplaced;
import net.minecraft.client.audio.ISound;
import net.minecraft.client.audio.SoundCategory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
/**
* @author dmillerw
*/
public class ItemBrokenEarmuffs extends ItemMagicalEarmuffs {
public static int cooldown = 0;
public ItemBrokenEarmuffs() {
super();
setUnlocalizedName("brokenEarmuffs");
}
@Override
public boolean hasEffect(ItemStack itemStack, int pass) {
return true;
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) {
return itemStack;
}
@Override
public ISound getMuffledSound(ItemStack itemStack, String name, ISound sound, SoundCategory soundCategory) {
// Fire a random sound once per 5 sounds
if (cooldown == 0) {
cooldown = 5;
return SoundHelper.getRandomSound(sound, soundCategory);
} else {
cooldown--;
return new SoundReplaced(sound, sound.getPositionedSoundLocation());
}
}
}
|
Use replace instead of set to not mess with browser's back button
Fix #1072 | /**
* Show an appriopriate UI based on if we have any users yet.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
const API = require('./api');
if (API.isLoggedIn()) {
API.verifyJWT().then((valid) => {
if (!valid) {
redirectUnauthed();
} else if (document.body) {
document.body.classList.remove('hidden');
} else {
document.addEventListener('DOMContentLoaded', () => {
document.body.classList.remove('hidden');
});
}
});
} else {
redirectUnauthed();
}
function redirectUnauthed() {
API.userCount().then((count) => {
let url;
if (count > 0) {
const redirectPath = window.location.pathname + window.location.search;
url = `/login/?url=${encodeURIComponent(redirectPath)}`;
} else {
url = '/signup/';
}
if (window.location.pathname !== url.split('?')[0]) {
window.location.replace(url);
}
});
}
| /**
* Show an appriopriate UI based on if we have any users yet.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
const API = require('./api');
if (API.isLoggedIn()) {
API.verifyJWT().then((valid) => {
if (!valid) {
redirectUnauthed();
} else if (document.body) {
document.body.classList.remove('hidden');
} else {
document.addEventListener('DOMContentLoaded', () => {
document.body.classList.remove('hidden');
});
}
});
} else {
redirectUnauthed();
}
function redirectUnauthed() {
API.userCount().then((count) => {
let url;
if (count > 0) {
const redirectPath = window.location.pathname + window.location.search;
url = `/login/?url=${encodeURIComponent(redirectPath)}`;
} else {
url = '/signup/';
}
if (window.location.pathname !== url.split('?')[0]) {
window.location.href = url;
}
});
}
|
Change exception to more appropriate | <?php
namespace JWX\JWE\KeyAlgorithm;
use JWX\JWA\JWA;
use JWX\JWE\KeyManagementAlgorithm;
use JWX\JWT\Parameter\AlgorithmParameter;
/**
* Algorithm to carry CEK in plaintext.
*
* @link https://tools.ietf.org/html/rfc7518#section-4.5
*/
class DirectCEKAlgorithm implements KeyManagementAlgorithm
{
/**
* Content encryption key.
*
* @var string $_cek
*/
protected $_cek;
/**
* Constructor
*
* @param string $key Content encryption key
*/
public function __construct($cek) {
$this->_cek = $cek;
}
/**
* Get content encryption key.
*
* @return string
*/
public function cek() {
return $this->_cek;
}
public function encrypt($cek) {
return "";
}
public function decrypt($data) {
if ($data !== "") {
throw new \UnexpectedValueException(
"Encrypted key must be an empty octet sequence.");
}
return $this->_cek;
}
public function cekForEncryption($length) {
if (strlen($this->_cek) != $length) {
throw new \UnexpectedValueException("Invalid key length.");
}
return $this->_cek;
}
public function algorithmParamValue() {
return JWA::ALGO_DIR;
}
public function headerParameters() {
return array(AlgorithmParameter::fromAlgorithm($this));
}
}
| <?php
namespace JWX\JWE\KeyAlgorithm;
use JWX\JWA\JWA;
use JWX\JWE\KeyManagementAlgorithm;
use JWX\JWT\Parameter\AlgorithmParameter;
/**
* Algorithm to carry CEK in plaintext.
*
* @link https://tools.ietf.org/html/rfc7518#section-4.5
*/
class DirectCEKAlgorithm implements KeyManagementAlgorithm
{
/**
* Content encryption key.
*
* @var string $_cek
*/
protected $_cek;
/**
* Constructor
*
* @param string $key Content encryption key
*/
public function __construct($cek) {
$this->_cek = $cek;
}
/**
* Get content encryption key.
*
* @return string
*/
public function cek() {
return $this->_cek;
}
public function encrypt($cek) {
return "";
}
public function decrypt($data) {
if ($data !== "") {
throw new \UnexpectedValueException(
"Encrypted key must be an empty octet sequence.");
}
return $this->_cek;
}
public function cekForEncryption($length) {
if (strlen($this->_cek) != $length) {
throw new \RuntimeException("Invalid key length.");
}
return $this->_cek;
}
public function algorithmParamValue() {
return JWA::ALGO_DIR;
}
public function headerParameters() {
return array(AlgorithmParameter::fromAlgorithm($this));
}
}
|
Make entity fall if there is no solid block below it. | package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
/**
* Lua API function to move one block forward.
*/
public class MoveForwardFunction extends EduCraftApiFunction {
@Override
public Varargs execute(Varargs varargs) {
Block blockAhead = getApi().getBlockAhead();
Location locationAhead = blockAhead.getLocation();
if (!blockAhead.getType().isSolid()
&& !blockAhead.getRelative(BlockFace.UP).getType().isSolid()
&& getApi().getEnvironment().getSheepAt(locationAhead) == null
&& getApi().getEnvironment().contains(locationAhead)) {
getApi().moveTo(locationAhead, false);
}
while (!blockAhead.getRelative(BlockFace.DOWN).getType().isSolid() && blockAhead.getY() > 0) {
blockAhead = blockAhead.getRelative(BlockFace.DOWN);
}
getApi().moveTo(blockAhead.getLocation(), false);
return LuaValue.NIL;
}
}
| package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import java.util.Collection;
/**
* Lua API function to move one block forward.
*/
public class MoveForwardFunction extends EduCraftApiFunction {
@Override
public Varargs execute(Varargs varargs) {
Block blockAhead = getApi().getBlockAhead();
Location locationAhead = blockAhead.getLocation();
Collection<Entity> entities = getApi().getEntitiesAhead();
if (!blockAhead.getType().isSolid()
&& !blockAhead.getRelative(BlockFace.UP).getType().isSolid()
&& getApi().getEnvironment().getSheepAt(locationAhead) == null
&& getApi().getEnvironment().contains(locationAhead)) {
getApi().moveTo(locationAhead, false);
}
return LuaValue.NIL;
}
}
|
Clear login form upon login. | core.controller('LoginController', function ($controller, $location, $scope, RestApi, StorageService, User) {
angular.extend(this, $controller('AbstractController', {$scope: $scope}));
$scope.account = {
email: '',
password: ''
};
$scope.login = function() {
RestApi.anonymousGet({
controller: 'auth',
method: 'login',
data: $scope.account
}).then(function(data) {
if(typeof data.payload.JWT == 'undefined') {
console.log("User does not exist!");
}
else {
$scope.account = {
email: '',
password: ''
};
StorageService.set("token", data.payload.JWT.tokenAsString);
delete sessionStorage.role;
var user = User.login();
User.ready().then(function() {
StorageService.set("role", user.role);
});
}
});
};
}); | core.controller('LoginController', function ($controller, $location, $scope, RestApi, StorageService, User) {
angular.extend(this, $controller('AbstractController', {$scope: $scope}));
$scope.account = {
email: '',
password: ''
};
$scope.login = function() {
RestApi.anonymousGet({
controller: 'auth',
method: 'login',
data: $scope.account
}).then(function(data) {
if(typeof data.payload.JWT == 'undefined') {
console.log("User does not exist!");
}
else {
StorageService.set("token", data.payload.JWT.tokenAsString);
delete sessionStorage.role;
var user = User.login();
User.ready().then(function() {
StorageService.set("role", user.role);
});
}
});
};
}); |
OEE-620: Create REST API resource to get dictionary/enum items | <?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\EntityBundle\ORM\SqlQueryBuilder;
interface DictionaryValueListProviderInterface
{
/**
* Checks whether the provider supports a given entity
*
* @param string $className The FQCN of an entity
*
* @return bool TRUE if this provider supports the given entity; otherwise, FALSE
*/
public function supports($className);
/**
* Gets a query builder for getting dictionary item values for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return QueryBuilder|SqlQueryBuilder|null QueryBuilder or SqlQueryBuilder if the provider can get values
* NULL if the provider cannot process the given entity
*/
public function getValueListQueryBuilder($className);
/**
* Returns the configuration of the entity serializer for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return array|null
*/
public function getSerializationConfig($className);
/**
* Gets a list of entity classes supported by this provider
*
* @return string[]
*/
public function getSupportedEntityClasses();
}
| <?php
namespace Oro\Bundle\EntityBundle\Provider;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\EntityBundle\ORM\SqlQueryBuilder;
interface DictionaryValueListProviderInterface
{
/**
* Gets a query builder for getting dictionary item values for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return QueryBuilder|SqlQueryBuilder|null QueryBuilder or SqlQueryBuilder if the provider can get values
* NULL if the provider cannot process the given entity
*/
public function getValueListQueryBuilder($className);
/**
* Returns the configuration of the entity serializer for a given dictionary class
*
* @param string $className The FQCN of a dictionary entity
*
* @return array|null
*/
public function getSerializationConfig($className);
/**
* Gets a list of entity classes supported by this provider
*
* @return string[]
*/
public function getSupportedEntityClasses();
}
|
Fix the telemetry sample test
This test works fine on devstack, but on the test gate not all
the meters have samples, so only iterate over them if there are
samples.
Partial-bug: #1665495
Change-Id: I8f327737a53194aeba08925391f1976f1b506aa0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
from openstack.telemetry.v2 import sample
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestSample(base.BaseFunctionalTest):
def test_list(self):
for meter in self.conn.telemetry.meters():
for sot in self.conn.telemetry.samples(meter):
assert isinstance(sot, sample.Sample)
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
from openstack.telemetry.v2 import sample
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestSample(base.BaseFunctionalTest):
def test_list(self):
for meter in self.conn.telemetry.meters():
sot = next(self.conn.telemetry.samples(meter))
assert isinstance(sot, sample.Sample)
|
Clean up test framework configuration | /* Copyright 2014 The Johns Hopkins University Applied Physics Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.jhuapl.tinkerpop;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.GraphFactory;
import edu.jhuapl.tinkerpop.AccumuloGraphConfiguration.InstanceType;
public class AccumuloGraphTestUtils {
public static AccumuloGraphConfiguration generateGraphConfig(String graphDirectoryName) {
return new AccumuloGraphConfiguration().setInstanceType(InstanceType.Mock)
.setGraphName(graphDirectoryName).setCreate(true);
}
public static Graph makeGraph(String name) {
return GraphFactory.open(generateGraphConfig(name));
}
}
| /* Copyright 2014 The Johns Hopkins University Applied Physics Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.jhuapl.tinkerpop;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.GraphFactory;
import edu.jhuapl.tinkerpop.AccumuloGraphConfiguration.InstanceType;
public class AccumuloGraphTestUtils {
public static AccumuloGraphConfiguration generateGraphConfig(String graphDirectoryName) {
AccumuloGraphConfiguration cfg = new AccumuloGraphConfiguration();
cfg.setInstanceName("instanceName").setZooKeeperHosts("ZookeeperHostsString");
cfg.setUser("root").setPassword("");
cfg.setGraphName(graphDirectoryName).setCreate(true).setAutoFlush(true).setInstanceType(InstanceType.Mock);
return cfg;
}
public static Graph makeGraph(String name) {
return GraphFactory.open(generateGraphConfig(name).getConfiguration());
}
}
|
Add another test to check that the "See new artists" page is basically rendered correctly | from tornado.testing import AsyncHTTPTestCase
from tornado.websocket import websocket_connect
from . import app
class TestMyApp(AsyncHTTPTestCase):
def get_app(self):
return app.get_app()
def test_homepage(self):
response = self.fetch('/')
self.assertEqual(response.code, 200)
body = response.body.decode('utf-8')
# Check that title is there.
self.assertIn('<h1>CHIRP Command Center</h1>', body)
# Check that links are present.
self.assertRegexpMatches(
body,
r'<a href="/new-artists/" class="[^"]+">See new artists</a>')
def test_new_artists_page(self):
response = self.fetch('/new-artists/')
self.assertEqual(response.code, 200)
body = response.body.decode('utf-8')
self.assertIn('See new artists</h1>', body)
self.assertIn(
'This command will show you what artists are (supposedly) not yet in the database.',
body)
| from tornado.testing import AsyncHTTPTestCase
from tornado.websocket import websocket_connect
from . import app
class TestMyApp(AsyncHTTPTestCase):
def get_app(self):
return app.get_app()
def test_homepage(self):
response = self.fetch('/')
self.assertEqual(response.code, 200)
body = response.body.decode('utf-8')
# Check that title is there.
self.assertIn('<h1>CHIRP Command Center</h1>', body)
# Check that links are present.
self.assertRegexpMatches(
body,
r'<a href="/new-artists/" class="[^"]+">See new artists</a>')
|
Remove top padding from the iframe's wrapping div and set minimum height. Also, remove the .col-xs-12 class | 'use strict';
var _ = require('lodash');
var $ = require('jquery');
function render(container, options) {
container = $(container);
options = _.extend({
items: []
}, options);
_.each(options.items, function(url) {
var wrapper = $('<div>')
.css({
position: 'relative',
minHeight: '250vh'
})
.append(
$('<iframe>')
.attr({
width: '100%',
height: '100%',
border: '0',
frameborder: '0',
seamless: 'on',
src: url
})
.css({
border: 0,
margin: 0,
padding: 0,
position: 'absolute',
left: 0,
top: 0,
width: '100%',
height: '100%'
})
);
$('<div>').addClass('content-grid-item')
.append(wrapper).appendTo(container);
});
}
module.exports.render = render;
| 'use strict';
var _ = require('lodash');
var $ = require('jquery');
function render(container, options) {
container = $(container);
options = _.extend({
items: []
}, options);
_.each(options.items, function(url) {
var wrapper = $('<div>')
.css({
position: 'relative',
paddingTop: '100%'
})
.append(
$('<iframe>')
.attr({
width: '100%',
height: '100%',
border: '0',
frameborder: '0',
seamless: 'on',
src: url
})
.css({
border: 0,
margin: 0,
padding: 0,
position: 'absolute',
left: 0,
top: 0,
width: '100%',
height: '100%'
})
);
$('<div>').addClass('content-grid-item col-md-6')
.append(wrapper).appendTo(container);
});
}
module.exports.render = render;
|
Write coverage reports after running tests | var gulp = require('gulp'),
tsc = require('gulp-tsc'),
tape = require('gulp-tape'),
tapSpec = require('tap-spec'),
del = require('del'),
runSequence = require('run-sequence'),
istanbul = require('gulp-istanbul');
gulp.task("test:clean", function(done) {
del(['build-test/**']).then(function(paths) {
console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n=====");
done();
});
});
gulp.task("test:build", function (done) {
gulp.src('test/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('build-test/'))
.on('end', done);
});
gulp.task("test:istanbul-hook", function (done) {
gulp.src('build-test/src/**/*.js')
.pipe(istanbul())
.on('end', done);
});
gulp.task("test:run", function (done) {
gulp.src('build-test/test/**/*.test.js')
.pipe(tape({
reporter: tapSpec()
}))
.pipe(istanbul.writeReports())
.on('end', done);
});
gulp.task("test", function (done) {
runSequence('test:clean', 'test:build', 'test:run', done);
});
| var gulp = require('gulp'),
tsc = require('gulp-tsc'),
tape = require('gulp-tape'),
tapSpec = require('tap-spec'),
del = require('del'),
runSequence = require('run-sequence'),
istanbul = require('gulp-istanbul');
gulp.task("test:clean", function(done) {
del(['build-test/**']).then(function(paths) {
console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n=====");
done();
});
});
gulp.task("test:build", function (done) {
gulp.src('test/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('build-test/'))
.on('end', done);
});
gulp.task("test:istanbul-hook", function (done) {
gulp.src('build-test/src/**/*.js')
.pipe(istanbul())
.on('end', done);
});
gulp.task("test:run", function (done) {
gulp.src('build-test/test/**/*.test.js')
.pipe(tape({
reporter: tapSpec()
}))
.on('end', done);
});
gulp.task("test", function (done) {
runSequence('test:clean', 'test:build', 'test:run', done);
});
|
Remove environment variable in integration test suit
Signed-off-by: Phan Le <f2c5995718b197bbd6f63c99e8aab6ee2af1c495@pivotallabs.com> | package integration_test
import (
"io/ioutil"
"os"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
bmtestutils "github.com/cloudfoundry/bosh-micro-cli/testutils"
)
var testCpiFilePath string
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
err := bmtestutils.BuildExecutable()
Expect(err).NotTo(HaveOccurred())
testCpiFilePath, err = bmtestutils.DownloadTestCpiRelease("")
Expect(err).NotTo(HaveOccurred())
})
var (
homePath string
oldHome string
)
BeforeEach(func() {
oldHome = os.Getenv("HOME")
var err error
homePath, err = ioutil.TempDir("", "micro-bosh-cli-integration")
Expect(err).NotTo(HaveOccurred())
os.Setenv("HOME", homePath)
})
AfterEach(func() {
os.Setenv("HOME", oldHome)
os.RemoveAll(homePath)
})
AfterSuite(func() {
os.Remove(testCpiFilePath)
})
RunSpecs(t, "bosh-micro-cli Integration Suite")
}
| package integration_test
import (
"io/ioutil"
"os"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
bmtestutils "github.com/cloudfoundry/bosh-micro-cli/testutils"
)
var testCpiFilePath string
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
err := bmtestutils.BuildExecutable()
Expect(err).NotTo(HaveOccurred())
testCpiFilePath, err = bmtestutils.DownloadTestCpiRelease(os.Getenv("CPI_RELEASE_URL"))
Expect(err).NotTo(HaveOccurred())
})
var (
homePath string
oldHome string
)
BeforeEach(func() {
oldHome = os.Getenv("HOME")
var err error
homePath, err = ioutil.TempDir("", "micro-bosh-cli-integration")
Expect(err).NotTo(HaveOccurred())
os.Setenv("HOME", homePath)
})
AfterEach(func() {
os.Setenv("HOME", oldHome)
os.RemoveAll(homePath)
})
AfterSuite(func() {
os.Remove(testCpiFilePath)
})
RunSpecs(t, "bosh-micro-cli Integration Suite")
}
|
Make the name of an organization required | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
'website', 'email')
class ManageOrganizationSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(required=False, allow_null=True)
name = serializers.CharField(required=True)
website = URLField(required=False, allow_blank=True)
email = serializers.EmailField(required=False, allow_blank=True)
class Meta:
model = Organization
fields = OrganizationSerializer.Meta.fields + ('partner_organizations',
'created', 'updated')
| from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
'website', 'email')
class ManageOrganizationSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(required=False, allow_null=True)
name = serializers.CharField(required=True, allow_blank=True)
website = URLField(required=False, allow_blank=True)
email = serializers.EmailField(required=False, allow_blank=True)
class Meta:
model = Organization
fields = OrganizationSerializer.Meta.fields + ('partner_organizations',
'created', 'updated')
|
Fix metric dimensions having only key
When metric dimensions have only key, query parameter will be ending with
':' delimiter. But api can not handle this query parameter.
So change to eliminate ':' delimiter when metric dimensions have only key.
Change-Id: I1327f8fe641fe98cf16c28911ef19908468d1bc0 | # (C) Copyright 2014 Hewlett Packard Enterprise Development Company LP
#
# 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 monascaclient.openstack.common.apiclient import base
class MonascaManager(base.BaseManager):
def __init__(self, client, **kwargs):
super(MonascaManager, self).__init__(client)
def get_headers(self):
headers = self.client.credentials_headers()
return headers
def get_dimensions_url_string(self, dimdict):
dim_list = list()
for k, v in dimdict.items():
# In case user specifies a dimension multiple times
if isinstance(v, (list, tuple)):
v = v[-1]
if v:
dim_str = k + ':' + v
else:
dim_str = k
dim_list.append(dim_str)
return ','.join(dim_list)
| # (C) Copyright 2014 Hewlett Packard Enterprise Development Company LP
#
# 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 monascaclient.openstack.common.apiclient import base
class MonascaManager(base.BaseManager):
def __init__(self, client, **kwargs):
super(MonascaManager, self).__init__(client)
def get_headers(self):
headers = self.client.credentials_headers()
return headers
def get_dimensions_url_string(self, dimdict):
dim_list = list()
for k, v in dimdict.items():
# In case user specifies a dimension multiple times
if isinstance(v, (list, tuple)):
v = v[-1]
dim_str = k + ':' + v
dim_list.append(dim_str)
return ','.join(dim_list)
|
Allow credentials for CORS requests | HAL.Http.Client = function(opts) {
this.vent = opts.vent;
this.defaultHeaders = { 'Accept': 'application/hal+json, application/json, */*; q=0.01' };
};
HAL.Http.Client.prototype.get = function(url) {
var self = this;
this.vent.trigger('location-change', { url: url });
var jqxhr = $.ajax({
url: url,
dataType: 'json',
xhrFields: {
withCredentials: true
},
headers: this.defaultHeaders,
success: function(resource, textStatus, jqXHR) {
self.vent.trigger('response', {
resource: resource,
jqxhr: jqXHR,
headers: jqXHR.getAllResponseHeaders()
});
}
}).error(function() {
self.vent.trigger('fail-response', { jqxhr: jqxhr });
});
};
HAL.Http.Client.prototype.request = function(opts) {
var self = this;
opts.dataType = 'json';
opts.xhrFields = opts.xhrFields || {};
opts.xhrFields.withCredentials = opts.xhrFields.withCredentials || true;
self.vent.trigger('location-change', { url: opts.url });
return jqxhr = $.ajax(opts);
};
HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) {
this.defaultHeaders = headers;
};
HAL.Http.Client.prototype.getDefaultHeaders = function() {
return this.defaultHeaders;
};
| HAL.Http.Client = function(opts) {
this.vent = opts.vent;
this.defaultHeaders = { 'Accept': 'application/hal+json, application/json, */*; q=0.01' };
};
HAL.Http.Client.prototype.get = function(url) {
var self = this;
this.vent.trigger('location-change', { url: url });
var jqxhr = $.ajax({
url: url,
dataType: 'json',
headers: this.defaultHeaders,
success: function(resource, textStatus, jqXHR) {
self.vent.trigger('response', {
resource: resource,
jqxhr: jqXHR,
headers: jqXHR.getAllResponseHeaders()
});
}
}).error(function() {
self.vent.trigger('fail-response', { jqxhr: jqxhr });
});
};
HAL.Http.Client.prototype.request = function(opts) {
var self = this;
opts.dataType = 'json';
self.vent.trigger('location-change', { url: opts.url });
return jqxhr = $.ajax(opts);
};
HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) {
this.defaultHeaders = headers;
};
HAL.Http.Client.prototype.getDefaultHeaders = function() {
return this.defaultHeaders;
};
|
Improve benchmark by reporting stream position once stream closes | <?php
require __DIR__ . '/../vendor/autoload.php';
$args = getopt('i:o:t:');
$if = isset($args['i']) ? $args['i'] : '/dev/zero';
$of = isset($args['o']) ? $args['o'] : '/dev/null';
$t = isset($args['t']) ? $args['t'] : 1;
echo 'piping for ' . $t . ' second(s) from ' . $if . ' to ' . $of . '...'. PHP_EOL;
$loop = new React\EventLoop\StreamSelectLoop();
// setup input and output streams and pipe inbetween
$in = new React\Stream\Stream(fopen($if, 'r'), $loop);
$out = new React\Stream\Stream(fopen($of, 'w'), $loop);
$out->pause();
$in->pipe($out);
// stop input stream in $t seconds
$start = microtime(true);
$timeout = $loop->addTimer($t, function () use ($in, &$bytes) {
$in->close();
});
// print stream position once stream closes
$in->on('close', function () use ($in, $start, $timeout) {
$t = microtime(true) - $start;
$timeout->cancel();
$bytes = ftell($in->stream);
echo 'read ' . $bytes . ' byte(s) in ' . round($t, 3) . ' second(s) => ' . round($bytes / 1024 / 1024 / $t, 1) . ' MiB/s' . PHP_EOL;
});
$loop->run();
| <?php
require __DIR__ . '/../vendor/autoload.php';
$args = getopt('i:o:t:');
$if = isset($args['i']) ? $args['i'] : '/dev/zero';
$of = isset($args['o']) ? $args['o'] : '/dev/null';
$t = isset($args['t']) ? $args['t'] : 1;
echo 'piping for ' . $t . ' second(s) from ' . $if . ' to ' . $of . '...'. PHP_EOL;
$loop = new React\EventLoop\StreamSelectLoop();
// setup input and output streams and pipe inbetween
$in = new React\Stream\Stream(fopen($if, 'r'), $loop);
$out = new React\Stream\Stream(fopen($of, 'w'), $loop);
$out->pause();
$in->pipe($out);
// count number of bytes from input stream
$bytes = 0;
$in->on('data', function ($chunk) use (&$bytes) {
$bytes += strlen($chunk);
});
// stop input stream in $t seconds
$loop->addTimer($t, function () use ($in) {
$in->close();
});
$loop->run();
echo 'read ' . $bytes . ' byte(s) in ' . $t . ' second(s) => ' . round($bytes / 1024 / 1024 / $t, 1) . ' MiB/s' . PHP_EOL;
|
Fix sourcemap generation and source roots. | 'use strict';
let gulp = require( 'gulp' );
let sequence = require( 'run-sequence' );
let plugins = require( 'gulp-load-plugins' )();
let typescript = plugins.typescript.createProject( './src/tsconfig.json', {
typescript: require( 'typescript' ),
} );
gulp.task( 'clean', function()
{
return gulp.src( './build/**/*', { read: false } )
.pipe( plugins.rimraf() );
} );
gulp.task( 'js', function()
{
return gulp.src( './src/**/*.ts' )
.pipe( plugins.plumber() )
.pipe( plugins.sourcemaps.init() )
.pipe( plugins.typescript( typescript ) )
.pipe( plugins.babel() )
.pipe( plugins.sourcemaps.write( '.', {
sourceRoot: '../src/',
} ) )
.pipe( gulp.dest( './build' ) );
} );
gulp.task( 'build', function( cb )
{
return sequence( 'clean', 'js', cb );
} );
gulp.task( 'watch', [ 'build' ], function()
{
gulp.watch( [ './src/**/*' ], [ 'build' ] );
} ); | 'use strict';
let gulp = require( 'gulp' );
let sequence = require( 'run-sequence' );
let plugins = require( 'gulp-load-plugins' )();
let typescript = plugins.typescript.createProject( './src/tsconfig.json', {
typescript: require( 'typescript' ),
} );
gulp.task( 'clean', function()
{
return gulp.src( './build/**/*', { read: false } )
.pipe( plugins.rimraf() );
} );
gulp.task( 'js', function()
{
return gulp.src( './src/**/*.ts' )
.pipe( plugins.plumber() )
.pipe( plugins.sourcemaps.init() )
.pipe( plugins.typescript( typescript ) )
.pipe( plugins.babel() )
.pipe( plugins.sourcemaps.write() )
.pipe( gulp.dest( './build' ) );
} );
gulp.task( 'build', function( cb )
{
return sequence( 'clean', 'js', cb );
} );
gulp.task( 'watch', [ 'build' ], function()
{
gulp.watch( [ './src/**/*' ], [ 'build' ] );
} ); |
Update copyright year on file header | /**
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring.boot.autoconfigure.domain;
public class City implements Domain {
private Long id;
private String name;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
| /**
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring.boot.autoconfigure.domain;
public class City implements Domain {
private Long id;
private String name;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
|
Fix unit test to pass Guzzle as a dependency | <?php
namespace MusicBrainz\Tests;
use MusicBrainz\MusicBrainz;
use Guzzle\Http\Client;
/**
* @covers MusicBrainz\MusicBrainz
*/
class MusicBrainzTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->brainz = new MusicBrainz(new Client());
}
public function MBIDProvider()
{
return array(
array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
, array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
, array(false, '4dbf5678-7a314-06aabb-e232f-8ac2cd63') // invalid spacing for UUID's
, array(false, '4dbf5678-7a31-406a-abbe-232f8az2cd63') // z is an invalid character
);
}
/**
* @dataProvider MBIDProvider
*/
public function testIsValidMBID($validation, $mbid)
{
$this->assertEquals($validation, $this->brainz->isValidMBID($mbid));
}
}
| <?php
namespace MusicBrainz\Tests;
use MusicBrainz\MusicBrainz;
/**
* @covers MusicBrainz\MusicBrainz
*/
class MusicBrainzTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->brainz = new MusicBrainz();
}
public function MBIDProvider()
{
return array(
array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
, array(true, '4dbf5678-7a31-406a-abbe-232f8ac2cd63')
, array(false, '4dbf5678-7a314-06aabb-e232f-8ac2cd63') // invalid spacing for UUID's
, array(false, '4dbf5678-7a31-406a-abbe-232f8az2cd63') // z is an invalid character
);
}
/**
* @dataProvider MBIDProvider
*/
public function testIsValidMBID($validation, $mbid)
{
$this->assertEquals($validation, $this->brainz->isValidMBID($mbid));
}
}
|
Fix privileges of package frontend. | # coding=utf-8
"""
DCRM - Darwin Cydia Repository Manager
Copyright (C) 2017 WU Zheng <i.82@me.com> & 0xJacky <jacky-943572677@qq.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/>.
Notice: You have used class-based views, that's awesome.
If not necessary, you can try function-based views.
You may add lines above as license.
"""
from django.views.generic import ListView
from WEIPDCRM.models.package import Package
class ChartView(ListView):
model = Package
context_object_name = 'package_list'
ordering = '-download_count'
template_name = 'frontend/chart.html'
def get_queryset(self):
"""
Get 24 packages ordering by download times.
:return: QuerySet
"""
queryset = super(ChartView, self).get_queryset().all()[:24]
return queryset
| # coding=utf-8
"""
DCRM - Darwin Cydia Repository Manager
Copyright (C) 2017 WU Zheng <i.82@me.com> & 0xJacky <jacky-943572677@qq.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/>.
Notice: You have used class-based views, that's awesome.
If not necessary, you can try function-based views.
You may add lines above as license.
"""
from django.views.generic import ListView
from WEIPDCRM.models.package import Package
class ChartView(ListView):
model = Package
context_object_name = 'package_list'
ordering = '-download_times'
template_name = 'frontend/chart.html'
def get_queryset(self):
"""
Get 24 packages ordering by download times.
:return: QuerySet
"""
queryset = super(ChartView, self).get_queryset().all()[:24]
return queryset
|
Add a setting so that people can disable mirrored saves | import os
__VERSION__ = ''
__PLUGIN_VERSION__ = ''
# Config settings
USERNAME = ''
SECRET = ''
API_KEY = ''
DEBUG = False
SOCK_DEBUG = False
ALERT_ON_MSG = True
LOG_TO_CONSOLE = False
BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits'))
# Shared globals
DEFAULT_HOST = 'floobits.com'
DEFAULT_PORT = 3448
SECURE = True
SHARE_DIR = None
COLAB_DIR = ''
PROJECT_PATH = ''
JOINED_WORKSPACE = False
PERMS = []
STALKER_MODE = False
SPLIT_MODE = False
MIRRORED_SAVES = True
AUTO_GENERATED_ACCOUNT = False
PLUGIN_PATH = None
WORKSPACE_WINDOW = None
CHAT_VIEW = None
CHAT_VIEW_PATH = None
TICK_TIME = 100
AGENT = None
IGNORE_MODIFIED_EVENTS = False
VIEW_TO_HASH = {}
FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
| import os
__VERSION__ = ''
__PLUGIN_VERSION__ = ''
# Config settings
USERNAME = ''
SECRET = ''
API_KEY = ''
DEBUG = False
SOCK_DEBUG = False
ALERT_ON_MSG = True
LOG_TO_CONSOLE = False
BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits'))
# Shared globals
DEFAULT_HOST = 'floobits.com'
DEFAULT_PORT = 3448
SECURE = True
SHARE_DIR = None
COLAB_DIR = ''
PROJECT_PATH = ''
JOINED_WORKSPACE = False
PERMS = []
STALKER_MODE = False
SPLIT_MODE = False
AUTO_GENERATED_ACCOUNT = False
PLUGIN_PATH = None
WORKSPACE_WINDOW = None
CHAT_VIEW = None
CHAT_VIEW_PATH = None
TICK_TIME = 100
AGENT = None
IGNORE_MODIFIED_EVENTS = False
VIEW_TO_HASH = {}
FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
|
Use formatError to expose errors | 'use strict';
const Foxx = require('org/arangodb/foxx');
const schema = require('./schema');
const graphql = require('graphql-sync').graphql;
const formatError = require('graphql-sync').formatError;
const ctrl = new Foxx.Controller(applicationContext);
// This is a regular Foxx HTTP API endpoint.
ctrl.post('/graphql', function (req, res) {
// By just passing the raw body string to graphql
// we let the GraphQL library take care of making
// sure the query is well-formed and valid.
// Our HTTP API doesn't have to know anything about
// GraphQL to handle it.
const result = graphql(schema, req.rawBody(), null, req.parameters);
console.log(req.parameters);
if (result.errors) {
res.status(400);
res.json({
errors: result.errors.map(function (error) {
return formatError(error);
})
});
} else {
res.json(result);
}
})
.summary('GraphQL endpoint')
.notes('GraphQL endpoint for the Star Wars GraphQL example.');
| 'use strict';
const Foxx = require('org/arangodb/foxx');
const schema = require('./schema');
const graphql = require('graphql-sync').graphql;
const ctrl = new Foxx.Controller(applicationContext);
// This is a regular Foxx HTTP API endpoint.
ctrl.post('/graphql', function (req, res) {
// By just passing the raw body string to graphql
// we let the GraphQL library take care of making
// sure the query is well-formed and valid.
// Our HTTP API doesn't have to know anything about
// GraphQL to handle it.
const result = graphql(schema, req.rawBody(), null, req.parameters);
console.log(req.parameters);
if (result.errors) {
res.status(400);
res.json({
errors: result.errors
});
} else {
res.json(result);
}
})
.summary('GraphQL endpoint')
.notes('GraphQL endpoint for the Star Wars GraphQL example.');
|
Remove support for parsing legacy interfaces
Reviewed By: kassens
Differential Revision: D6972027
fbshipit-source-id: 6af12e0fad969b8f0a8348c17347cec07f2047b2 | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const fs = require('fs');
const path = require('path');
const {SCHEMA_EXTENSION} = require('./GraphQLRelayDirective');
const {parse} = require('graphql');
function getSchemaIntrospection(schemaPath: string, basePath: ?string) {
try {
let fullSchemaPath = schemaPath;
if (!fs.existsSync(fullSchemaPath) && basePath) {
fullSchemaPath = path.join(basePath, schemaPath);
}
const source = fs.readFileSync(fullSchemaPath, 'utf8');
if (source[0] === '{') {
return JSON.parse(source);
}
return parse(SCHEMA_EXTENSION + '\n' + source);
} catch (error) {
// Log a more helpful warning (by including the schema path).
console.error(
'Encountered the following error while loading the GraphQL schema: ' +
schemaPath +
'\n\n' +
error.stack
.split('\n')
.map(line => '> ' + line)
.join('\n'),
);
throw error;
}
}
module.exports = getSchemaIntrospection;
| /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const fs = require('fs');
const path = require('path');
const {SCHEMA_EXTENSION} = require('./GraphQLRelayDirective');
const {parse} = require('graphql');
function getSchemaIntrospection(schemaPath: string, basePath: ?string) {
try {
let fullSchemaPath = schemaPath;
if (!fs.existsSync(fullSchemaPath) && basePath) {
fullSchemaPath = path.join(basePath, schemaPath);
}
const source = fs.readFileSync(fullSchemaPath, 'utf8');
if (source[0] === '{') {
return JSON.parse(source);
}
return parse(SCHEMA_EXTENSION + '\n' + source, {
// TODO(T25914961) remove after schema syncs with the new format.
allowLegacySDLImplementsInterfaces: true,
});
} catch (error) {
// Log a more helpful warning (by including the schema path).
console.error(
'Encountered the following error while loading the GraphQL schema: ' +
schemaPath +
'\n\n' +
error.stack
.split('\n')
.map(line => '> ' + line)
.join('\n'),
);
throw error;
}
}
module.exports = getSchemaIntrospection;
|
Allow the same 'hosts' settings that Elasticsearch does | # -*- coding: utf-8 -*-
from functools import wraps
from elasticsearch.client import _normalize_hosts
from mock import patch
from elasticmock.fake_elasticsearch import FakeElasticsearch
ELASTIC_INSTANCES = {}
def _get_elasticmock(hosts=None, *args, **kwargs):
host = _normalize_hosts(hosts)[0]
elastic_key = '{0}:{1}'.format(
host.get('host', 'localhost'), host.get('port', 9200)
)
if elastic_key in ELASTIC_INSTANCES:
connection = ELASTIC_INSTANCES.get(elastic_key)
else:
connection = FakeElasticsearch()
ELASTIC_INSTANCES[elastic_key] = connection
return connection
def elasticmock(f):
@wraps(f)
def decorated(*args, **kwargs):
ELASTIC_INSTANCES.clear()
with patch('elasticsearch.Elasticsearch', _get_elasticmock):
result = f(*args, **kwargs)
return result
return decorated
| # -*- coding: utf-8 -*-
from functools import wraps
from mock import patch
from elasticmock.fake_elasticsearch import FakeElasticsearch
ELASTIC_INSTANCES = {}
def _get_elasticmock(hosts=None, *args, **kwargs):
elastic_key = 'localhost:9200' if hosts is None else '{0}:{1}'.format(hosts[0].get('host'), hosts[0].get('port'))
if elastic_key in ELASTIC_INSTANCES:
connection = ELASTIC_INSTANCES.get(elastic_key)
else:
connection = FakeElasticsearch()
ELASTIC_INSTANCES[elastic_key] = connection
return connection
def elasticmock(f):
@wraps(f)
def decorated(*args, **kwargs):
ELASTIC_INSTANCES.clear()
with patch('elasticsearch.Elasticsearch', _get_elasticmock):
result = f(*args, **kwargs)
return result
return decorated
|
Remove duplicated code from RegisterAPIRoutes | package api
import (
api "github.com/diyan/assimilator/api/endpoints"
mw "github.com/diyan/assimilator/api/middleware"
"github.com/labstack/echo"
)
// RegisterAPIRoutes adds API routes to the Echo's route group
func RegisterAPIRoutes(g *echo.Group) {
// Organizations
g.GET("/organizations/", api.OrganizationIndexGetEndpoint)
g.GET("/organizations/:organization_slug/", api.OrganizationDetailsGetEndpoint)
// Projects
p := g.Group("/projects/:organization_slug/:project_slug")
//p.Use(mw.RequireUser)
p.Use(mw.RequireOrganization)
p.Use(mw.RequireProject)
p.GET("/environments/", api.ProjectEnvironmentsGetEndpoint)
p.GET("/issues/", api.ProjectGroupIndexGetEndpoint)
p.GET("/groups/", api.ProjectGroupIndexGetEndpoint)
p.GET("/searches/", api.ProjectSearchesGetEndpoint)
p.GET("/members/", api.ProjectMemberIndexGetEndpoint)
p.GET("/tags/", api.ProjectTagsGetEndpoint)
// Internal
g.GET("/internal/health/", api.SystemHealthGetEndpoint)
}
| package api
import (
api "github.com/diyan/assimilator/api/endpoints"
"github.com/labstack/echo"
)
// RegisterAPIRoutes adds API routes to the Echo's route group
func RegisterAPIRoutes(g *echo.Group) {
// Organizations
g.GET("/organizations/", api.OrganizationIndexGetEndpoint)
g.GET("/organizations/:organization_slug/", api.OrganizationDetailsGetEndpoint)
// Projects
g.GET("/projects/:organization_slug/:project_slug/environments/", api.ProjectEnvironmentsGetEndpoint)
g.GET("/projects/:organization_slug/:project_slug/issues/", api.ProjectGroupIndexGetEndpoint)
g.GET("/projects/:organization_slug/:project_slug/groups/", api.ProjectGroupIndexGetEndpoint)
g.GET("/projects/:organization_slug/:project_slug/searches/", api.ProjectSearchesGetEndpoint)
g.GET("/projects/:organization_slug/:project_slug/members/", api.ProjectMemberIndexGetEndpoint)
g.GET("/projects/:organization_slug/:project_slug/tags/", api.ProjectTagsGetEndpoint)
// Internal
g.GET("/internal/health/", api.SystemHealthGetEndpoint)
}
|
Revert "Make IntComparator a bit more direct" | // Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package utils
// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
// negative , if a < b
// zero , if a == b
// positive , if a > b
type Comparator func(a, b interface{}) int
// IntComparator provides a basic comparison on ints
func IntComparator(a, b interface{}) int {
aInt := a.(int)
bInt := b.(int)
switch {
case aInt > bInt:
return 1
case aInt < bInt:
return -1
default:
return 0
}
}
// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
s1 := a.(string)
s2 := b.(string)
min := len(s2)
if len(s1) < len(s2) {
min = len(s1)
}
diff := 0
for i := 0; i < min && diff == 0; i++ {
diff = int(s1[i]) - int(s2[i])
}
if diff == 0 {
diff = len(s1) - len(s2)
}
if diff < 0 {
return -1
}
if diff > 0 {
return 1
}
return 0
}
| // Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package utils
// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
// negative , if a < b
// zero , if a == b
// positive , if a > b
type Comparator func(a, b interface{}) int
// IntComparator provides a basic comparison on ints
func IntComparator(a, b interface{}) int {
return a.(int) - b.(int)
}
// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
s1 := a.(string)
s2 := b.(string)
min := len(s2)
if len(s1) < len(s2) {
min = len(s1)
}
diff := 0
for i := 0; i < min && diff == 0; i++ {
diff = int(s1[i]) - int(s2[i])
}
if diff == 0 {
diff = len(s1) - len(s2)
}
if diff < 0 {
return -1
}
if diff > 0 {
return 1
}
return 0
}
|
Set diagnostics into old UI | // This function is run when the app is ready to start interacting with the host application.
// It ensures the DOM is ready before updating the span elements with values from the current message.
Office.initialize = function () {
$(document).ready(function () {
$(window).resize(onResize);
initViewModels();
updateStatus(ImportedStrings.mha_loading);
sendHeadersRequest();
$("#diagnostics").text(viewModel.diagnostics);
});
};
function enableSpinner() {
$("#response").css("background-image", "url(../Resources/loader.gif)");
$("#response").css("background-repeat", "no-repeat");
$("#response").css("background-position", "center");
}
function disableSpinner() {
$("#response").css("background", "none");
}
function hideStatus() {
disableSpinner();
}
function updateStatus(statusText) {
enableSpinner();
$("#status").text(statusText);
if (viewModel !== null) {
viewModel.status = statusText;
}
positionResponse();
recalculateVisibility();
}
function getHeadersComplete(headers) {
updateStatus(ImportedStrings.mha_foundHeaders);
$("#originalHeaders").text(headers);
parseHeadersToTables(headers);
}
function showError(message) {
updateStatus(message);
disableSpinner();
rebuildSections();
} | // This function is run when the app is ready to start interacting with the host application.
// It ensures the DOM is ready before updating the span elements with values from the current message.
Office.initialize = function () {
$(document).ready(function () {
$(window).resize(onResize);
initViewModels();
updateStatus(ImportedStrings.mha_loading);
sendHeadersRequest();
});
};
function enableSpinner() {
$("#response").css("background-image", "url(../Resources/loader.gif)");
$("#response").css("background-repeat", "no-repeat");
$("#response").css("background-position", "center");
}
function disableSpinner() {
$("#response").css("background", "none");
}
function hideStatus() {
disableSpinner();
}
function updateStatus(statusText) {
enableSpinner();
$("#status").text(statusText);
if (viewModel !== null) {
viewModel.status = statusText;
}
positionResponse();
recalculateVisibility();
}
function getHeadersComplete(headers) {
updateStatus(ImportedStrings.mha_foundHeaders);
$("#originalHeaders").text(headers);
parseHeadersToTables(headers);
}
function showError(message) {
updateStatus(message);
disableSpinner();
rebuildSections();
} |
Make default start command watch toolkit | #!/usr/bin/env node
/**
* Module dependencies.
*/
const debug = require('debug')('docsmith:start');
const program = require('commander');
const start = require('./docsmith/start');
const config = require('./docsmith/utils/settings').config;
let workspace;
program
.arguments('[workspace]')
.option('-s, --source [path]', '[migrate] Source folder path]')
.option('--baseurl [baseurl]', 'Set site.baseurl metadata value.')
.option('-n, --no-watch', 'Do not watch content folder and serve on local server. Watches by default.')
.option('-d, --debug', 'Enable /debug-ui url for debugging pipeline.')
.option('-f, --force', 'Initialise whether the current directory is empty or not.')
.option('-l, --link', 'For development purposes. Link local packages.')
.action(function(wksp) {
workspace = wksp;
});
program.parse(process.argv);
const { link, source, baseurl, watch, debug: dbg } = program;
if (typeof workspace === 'undefined') workspace = 'toolkit';
// check if we could resolve the config.
if (config) {
debug('config', config);
// called from a content as code instance, initialise from the instance configuration
start.run({ workspace, config, link, source, watch, dbg, baseurl });
} else {
console.warn('Could not find config. Aborting start. Please contact the developer');
}
| #!/usr/bin/env node
/**
* Module dependencies.
*/
const debug = require('debug')('docsmith:start');
const program = require('commander');
const start = require('./docsmith/start');
const config = require('./docsmith/utils/settings').config;
let workspace;
program
.arguments('[workspace]')
.option('-s, --source [path]', '[migrate] Source folder path]')
.option('--baseurl [baseurl]', 'Set site.baseurl metadata value.')
.option('-w, --watch', 'Watch content folder and serve on local server.')
.option('-d, --debug', 'Enable /debug-ui url for debugging pipeline.')
.option('-f, --force', 'Initialise whether the current directory is empty or not.')
.option('-l, --link', 'For development purposes. Link local packages.')
.action(function(wksp) {
workspace = wksp;
})
.parse(process.argv);
const { link, source, baseurl, watch, debug: dbg } = program;
// check if we could resolve the config.
if (config) {
debug('config', config);
// called from a content as code instance, initialise from the instance configuration
start.run({ workspace, config, link, source, watch, dbg, baseurl });
} else {
console.warn('Could not find config. Aborting start. Please contact the developer');
}
|
Put Lexical in its own namespace: Pharen. | <?php
namespace Pharen;
class Lexical{
static $scopes = array();
public static function init_closure($ns, $id){
if(isset(self::$scopes[$ns][$id])){
self::$scopes[$ns][$id][] = array();
}else{
self::$scopes[$ns][$id] = array(array());
}
return $id;
}
public static function get_closure_id($ns, $id){
if($id === Null){
return Null;
}else{
return count(self::$scopes[$ns][$id])-1;
}
}
public static function bind_lexing($ns, $id, $var, &$val){
$closure_id = self::get_closure_id($ns, $id);
self::$scopes[$ns][$id][$closure_id][$var] =& $val;
}
public static function get_lexical_binding($ns, $id, $var, $closure_id){
return self::$scopes[$ns][$id][$closure_id][$var];
}
}
| <?php
class Lexical{
static $scopes = array();
public static function init_closure($ns, $id){
if(isset(self::$scopes[$ns][$id])){
self::$scopes[$ns][$id][] = array();
}else{
self::$scopes[$ns][$id] = array(array());
}
return $id;
}
public static function get_closure_id($ns, $id){
if($id === Null){
return Null;
}else{
return count(self::$scopes[$ns][$id])-1;
}
}
public static function bind_lexing($ns, $id, $var, &$val){
$closure_id = self::get_closure_id($ns, $id);
self::$scopes[$ns][$id][$closure_id][$var] =& $val;
}
public static function get_lexical_binding($ns, $id, $var, $closure_id){
return self::$scopes[$ns][$id][$closure_id][$var];
}
}
|
Use userinfo URI for user profile info | import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["GOOGLE_OAUTH_CLIENT_ID"] = os.environ.get("GOOGLE_OAUTH_CLIENT_ID")
app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET")
google_bp = make_google_blueprint(scope=["profile", "email"])
app.register_blueprint(google_bp, url_prefix="/login")
@app.route("/")
def index():
if not google.authorized:
return redirect(url_for("google.login"))
resp = google.get("/oauth2/v1/userinfo")
assert resp.ok, resp.text
return "You are {email} on Google".format(email=resp.json()["emails"][0]["value"])
if __name__ == "__main__":
app.run()
| import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["GOOGLE_OAUTH_CLIENT_ID"] = os.environ.get("GOOGLE_OAUTH_CLIENT_ID")
app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET")
google_bp = make_google_blueprint(scope=["profile", "email"])
app.register_blueprint(google_bp, url_prefix="/login")
@app.route("/")
def index():
if not google.authorized:
return redirect(url_for("google.login"))
resp = google.get("/plus/v1/people/me")
assert resp.ok, resp.text
return "You are {email} on Google".format(email=resp.json()["emails"][0]["value"])
if __name__ == "__main__":
app.run()
|
Document workaround for `got` `FormData` bug
See: https://github.com/sindresorhus/got/pull/466 | /* eslint-env node */
const FormData = require('form-data');
const got = require('got');
const BASE_URL = 'https://debuglogs.org';
// Workaround: Submitting `FormData` using native `FormData::submit` procedure
// as integration with `got` results in S3 error saying we haven’t set the
// `Content-Length` header:
// https://github.com/sindresorhus/got/pull/466
const submitFormData = (form, url) =>
new Promise((resolve, reject) => {
form.submit(url, (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});
// upload :: String -> Promise URL
exports.upload = async (content) => {
const signedForm = await got.get(BASE_URL, { json: true });
const { fields, url } = signedForm.body;
const form = new FormData();
// The API expects `key` to be the first field:
form.append('key', fields.key);
Object.entries(fields)
.filter(([key]) => key !== 'key')
.forEach(([key, value]) => {
form.append(key, value);
});
const contentBuffer = Buffer.from(content, 'utf8');
const contentType = 'text/plain';
form.append('Content-Type', contentType);
form.append('file', contentBuffer, {
contentType,
filename: 'signal-desktop-debug-log.txt',
});
// WORKAROUND: See comment on `submitFormData`:
// await got.post(url, { body: form });
await submitFormData(form, url);
return `${BASE_URL}/${fields.key}`;
};
| /* eslint-env node */
const FormData = require('form-data');
const got = require('got');
const BASE_URL = 'https://debuglogs.org';
// Workaround: Submitting `FormData` using native `FormData::submit` procedure
// as integration with `got` results in S3 error saying we haven’t set the
// `Content-Length` header:
const submitFormData = (form, url) =>
new Promise((resolve, reject) => {
form.submit(url, (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});
// upload :: String -> Promise URL
exports.upload = async (content) => {
const signedForm = await got.get(BASE_URL, { json: true });
const { fields, url } = signedForm.body;
const form = new FormData();
// The API expects `key` to be the first field:
form.append('key', fields.key);
Object.entries(fields)
.filter(([key]) => key !== 'key')
.forEach(([key, value]) => {
form.append(key, value);
});
const contentBuffer = Buffer.from(content, 'utf8');
const contentType = 'text/plain';
form.append('Content-Type', contentType);
form.append('file', contentBuffer, {
contentType,
filename: 'signal-desktop-debug-log.txt',
});
await submitFormData(form, url);
return `${BASE_URL}/${fields.key}`;
};
|
Reduce class and method visibility | package nu.studer.teamcity.buildscan.internal;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class Util {
private static final Pattern BUILD_SCAN_URL_PATTERN = Pattern.compile("https?://.*/s/(.*)");
static boolean isBuildScanUrl(String text) {
return doGetBuildScanId(text).isPresent();
}
static String getBuildScanId(String text) {
//noinspection OptionalGetWithoutIsPresent
return doGetBuildScanId(text).get();
}
private static Optional<String> doGetBuildScanId(String text) {
Matcher matcher = BUILD_SCAN_URL_PATTERN.matcher(text);
return matcher.matches() ? Optional.of(matcher.group(1)) : Optional.empty();
}
private Util() {
}
}
| package nu.studer.teamcity.buildscan.internal;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Util {
private static final Pattern BUILD_SCAN_URL_PATTERN = Pattern.compile("https?://.*/s/(.*)");
private Util() {
}
public static boolean isBuildScanUrl(String text) {
return doGetBuildScanId(text).isPresent();
}
public static String getBuildScanId(String text) {
//noinspection OptionalGetWithoutIsPresent
return doGetBuildScanId(text).get();
}
private static Optional<String> doGetBuildScanId(String text) {
Matcher matcher = BUILD_SCAN_URL_PATTERN.matcher(text);
return matcher.matches() ? Optional.of(matcher.group(1)) : Optional.empty();
}
}
|
Remove website from recent comments | from core.models import Comment, Tag
from django import template
register = template.Library()
#May want to ditch this for a middleware that passes in the comments object so that I can do the manipulations in the actual template
@register.simple_tag
def recent_comments():
comments = Comment.objects.select_related('entry').filter(deleted=False, spam=False).order_by('-id')[:3]
output = '<ul id="recent">'
for comment in comments:
if not comment.name:
comment.name = "Anonymous"
elif comment.user:
output += '<li><a href="http://www.github.com/mburst">' + comment.user.get_full_name() + '</a> - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>'
else:
output += '<li>' + comment.name + ' - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>'
output += '</ul>'
return output
@register.simple_tag
def tags():
tags = Tag.objects.order_by('?')[:10]
return tags | from core.models import Comment, Tag
from django import template
register = template.Library()
#May want to ditch this for a middleware that passes in the comments object so that I can do the manipulations in the actual template
@register.simple_tag
def recent_comments():
comments = Comment.objects.select_related('entry').filter(deleted=False, spam=False).order_by('-id')[:3]
output = '<ul id="recent">'
for comment in comments:
if not comment.name:
comment.name = "Anonymous"
if comment.website:
output += '<li><a href="' + comment.website + '">' + comment.name + '</a> - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>'
elif comment.user:
output += '<li><a href="http://www.github.com/mburst">' + comment.user.get_full_name() + '</a> - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>'
else:
output += '<li>' + comment.name + ' - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>'
output += '</ul>'
return output
@register.simple_tag
def tags():
tags = Tag.objects.order_by('?')[:10]
return tags |
Fix network dict value in list | #!/usr/bin/env python
import yaml
import json
my_list = [1, 2, 3, 4, 5, 6, 7, 8, "Firewall", "Router", "Switch", {"network": "10.11.12.0", "subnet": "255.255.255.0",
"gateway": "10.11.12.1"}, {"Model": "WS3560",
"Vendor": "Cisco"}]
# Write YAML file
with open("my_yaml_file.yml", "w") as f:
f.write(yaml.dump(my_list, default_flow_style=False))
# Write JSON file
with open("my_json_file.json", "w") as f:
json.dump(my_list, f)
| #!/usr/bin/env python
import yaml
import json
my_list = [1, 2, 3, 4, 5, 6, 7, 8, "Firewall", "Router", "Switch", {"network": "10.11.12.1", "subnet": "255.255.255.0",
"gateway": "10.11.12.1"}, {"Model": "WS3560",
"Vendor": "Cisco"}]
# Write YAML file
with open("my_yaml_file.yml", "w") as f:
f.write(yaml.dump(my_list, default_flow_style=False))
# Write JSON file
with open("my_json_file.json", "w") as f:
json.dump(my_list, f)
|
Revert "Set version to b for beta"
This reverts commit db3395cc44f6b18d59a06593ad48f14e4c99ad05. | from distutils.core import setup
setup(name='pyresttest',
version='1.0',
description='Python RESTful API Testing & Microbenchmarking Tool',
long_description='Python RESTful API Testing & Microbenchmarking Tool',
maintainer='Sam Van Oort',
maintainer_email='acetonespam@gmail.com',
url='https://github.com/svanoort/pyresttest',
keywords=['rest', 'web', 'http', 'testing'],
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Utilities'
],
py_modules=['pyresttest.resttest','pyresttest.generators','pyresttest.binding',
'pyresttest.parsing', 'pyresttest.validators', 'pyresttest.contenthandling',
'pyresttest.benchmarks','pyresttest.tests'],
license='Apache License, Version 2.0',
requires=['yaml','pycurl'],
scripts=['pyresttest/resttest.py'], #Make this executable from command line when installed
provides=['pyresttest']
)
| from distutils.core import setup
setup(name='pyresttest',
version='1.0b',
description='Python RESTful API Testing & Microbenchmarking Tool',
long_description='Python RESTful API Testing & Microbenchmarking Tool',
maintainer='Sam Van Oort',
maintainer_email='acetonespam@gmail.com',
url='https://github.com/svanoort/pyresttest',
keywords=['rest', 'web', 'http', 'testing'],
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Utilities'
],
py_modules=['pyresttest.resttest','pyresttest.generators','pyresttest.binding',
'pyresttest.parsing', 'pyresttest.validators', 'pyresttest.contenthandling',
'pyresttest.benchmarks','pyresttest.tests'],
license='Apache License, Version 2.0',
requires=['yaml','pycurl'],
scripts=['pyresttest/resttest.py'], #Make this executable from command line when installed
provides=['pyresttest']
)
|
Fix typo with the usage of req.query | var express = require('express')
, router = express.Router()
, Qpv = require('../models/qpv.js')
, geojson = require('../helpers/geojson.js')
, isvalidgeo = require('../helpers/isvalidgeo')
, turf = require('turf')
router.get('/layer', function(req, res) {
if (req.query.bbox){
var bbox = req.query.bbox.split(",");
var geojsonbbox = turf.bboxPolygon(bbox);
var isvalid = isvalidgeo(geojsonbbox);
}
if (isvalid || !req.query.bbox){
var qpv = Qpv.getLayer(bbox);
qpv.then( function (data){
var featureCollection = geojson.rows_to_geojson(data, Qpv.properties);
res.json(featureCollection);
}).catch(function (err){
console.error(err)
res.status(500).send({error:'something bad happens'})
})
}
else{
res.status(500).send({error:'invalid bbox'})
}
})
router.post('/intersects', function(req, res) {
var qpv = Qpv.intersects(req.query.geom);
res.send();
})
module.exports = router
| var express = require('express')
, router = express.Router()
, Qpv = require('../models/qpv.js')
, geojson = require('../helpers/geojson.js')
, isvalidgeo = require('../helpers/isvalidgeo')
, turf = require('turf')
router.get('/layer', function(req, res) {
if (req.query.bbox){
var bbox = req.query.bbox.split(",");
var geojsonbbox = turf.bboxPolygon(bbox);
var isvalid = isvalidgeo(geojsonbbox);
}
if (isvalid || !req.bbox){
var qpv = Qpv.getLayer(bbox);
qpv.then( function (data){
var featureCollection = geojson.rows_to_geojson(data, Qpv.properties);
res.json(featureCollection);
}).catch(function (err){
console.error(err)
res.status(500).send({error:'something bad happens'})
})
}
else{
res.status(500).send({error:'invalid GeoJSON'})
}
})
router.post('/intersects', function(req, res) {
var qpv = Qpv.intersects(req.query.geom);
res.send();
})
module.exports = router
|
Fix atributo serializable de gravidades | from . import APIMetadataModel
from .properties import PropertyDescriptor
class InteracaoMetadata(APIMetadataModel):
@property
@PropertyDescriptor.serializable('evidencia')
def evidencias(self):
return self.__evidencias
@evidencias.setter
@PropertyDescriptor.list
def evidencias(self, val):
self.__evidencias = val
@property
@PropertyDescriptor.serializable('acao')
def acoes(self):
return self.__acoes
@acoes.setter
@PropertyDescriptor.list
def acoes(self, val):
self.__acoes = val
@property
@PropertyDescriptor.serializable('gravidade')
def gravidades(self):
return self.__gravidades
@gravidades.setter
@PropertyDescriptor.list
def gravidades(self, val):
self.__gravidades = val
| from . import APIMetadataModel
from .properties import PropertyDescriptor
class InteracaoMetadata(APIMetadataModel):
@property
@PropertyDescriptor.serializable('evidencia')
def evidencias(self):
return self.__evidencias
@evidencias.setter
@PropertyDescriptor.list
def evidencias(self, val):
self.__evidencias = val
@property
@PropertyDescriptor.serializable('acao')
def acoes(self):
return self.__acoes
@acoes.setter
@PropertyDescriptor.list
def acoes(self, val):
self.__acoes = val
@property
@PropertyDescriptor.serializable('acao')
def gravidades(self):
return self.__gravidades
@gravidades.setter
@PropertyDescriptor.list
def gravidades(self, val):
self.__gravidades = val
|
Update the read status of a thread when it's viewed | from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from user_messages.models import Thread, Message
@login_required
def inbox(request, template_name='user_messages/inbox.html'):
threads = list(Thread.objects.inbox(request.user))
threads.sort(key=lambda o: o.latest_message.sent_at, reversed=True)
return render_to_response(template_name, {'threads': threads}, context_instance=RequestContext(request))
@login_required
def thread_detail(request, thread_id,
template_name='user_messages/thread_detail.html'):
qs = Thread.objects.filter(Q(to_user=request.user) | Q(from_user=request.user))
thread = get_object_or_404(qs, pk=thread_id)
if request.user == thread.to_user:
thread.to_user_unread = False
else:
thread.from_user_unread = False
thread.save()
return render_to_response(template_name, {'thread': thread}, context_instance=RequestContext(request))
| from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from user_messages.models import Thread, Message
@login_required
def inbox(request, template_name='user_messages/inbox.html'):
threads = list(Thread.objects.inbox(request.user))
threads.sort(key=lambda o: o.latest_message.sent_at, reversed=True)
return render_to_response(template_name, {'threads': threads}, context_instance=RequestContext(request))
@login_required
def thread_detail(request, thread_id,
template_name='user_messages/thread_detail.html'):
qs = Thread.objects.filter(Q(to_user=request.user) | Q(from_user=request.user))
thread = get_object_or_404(qs, pk=thread_id)
return render_to_response(template_name, {'thread': thread}, context_instance=RequestContext(request))
|
Fix pop to raise ValueError when empty Stack is popped | class StackItem(object):
def __init__(self, data, next_item=None):
self.data = data
self.next_item = next_item
def __str__(self):
return self.data
class StackFrame(object):
def __init__(self, first_item=None):
self.first_item = first_item
def push(self, new_item):
# push new_item to beginning of list
if not self.first_item:
self.first_item = new_item
else:
new_item.next_item = self.first_item
self.first_item = new_item
def pop(self):
# poops first value from list and returns it
if self.first_item is None:
return ValueError("No items in stack!")
else:
obsolete_item = self.first_item
self.first_item = self.first_item.next_item
return obsolete_item.data
| class StackItem(object):
def __init__(self, data, next_item=None):
self.data = data
self.next_item = next_item
def __str__(self):
return self.data
class StackFrame(object):
def __init__(self, first_item=None):
self.first_item = first_item
def push(self, new_item):
# push new_item to beginning of list
if not self.first_item:
self.first_item = new_item
else:
new_item.next_item = self.first_item
self.first_item = new_item
def pop(self):
# poops first value from list and returns it
obsolete_item = self.first_item
self.first_item = self.first_item.next_item
return obsolete_item.data
|
Add conditionnalOn to EndpointObfuscator ensure it won't be avaiable in non-web context | package org.araymond.joal.web.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
/**
* Created by raymo on 25/07/2017.
*/
@ConditionalOnProperty(name = "spring.main.web-environment", havingValue = "true")
@Configuration
public class EndpointObfuscatorConfiguration {
private final String pathPrefix;
public EndpointObfuscatorConfiguration(@Value("${joal.ui.path.prefix}")final String pathPrefix) {
this.pathPrefix = pathPrefix;
}
@Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
final ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet(),
"/" + this.pathPrefix + "/*"
);
registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
return registration;
}
}
| package org.araymond.joal.web.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
/**
* Created by raymo on 25/07/2017.
*/
@Configuration
public class EndpointObfuscatorConfiguration {
private final String pathPrefix;
public EndpointObfuscatorConfiguration(@Value("${joal.ui.path.prefix}")final String pathPrefix) {
this.pathPrefix = pathPrefix;
}
@Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
final ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet(),
"/" + this.pathPrefix + "/*"
);
registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
return registration;
}
}
|
Fix links in ANDS RIF-CS script | """
Create an ANDS RIF-CS XML file.
Links
-----
- http://ands.org.au/guides/cpguide/cpgrifcs.html
- http://ands.org.au/resource/rif-cs.html
- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
"""
import logging
import os
from settings import (
ANDS_XML_FILE_NAME, ANDS_XML_FOLDER_PATH, ANDS_XML_START, ANDS_XML_STOP
)
logger = logging.getLogger(__name__)
def main():
with open(ANDS_XML_FILE_NAME, 'w') as w:
w.write(ANDS_XML_START)
for file_path in os.listdir(ANDS_XML_FOLDER_PATH):
with open(file_path) as r:
w.write(r.read())
w.write(ANDS_XML_STOP)
if '__main__' == __name__:
logging.basicConfig(level=logging.DEBUG)
main()
| """
Create an ANDS RIF-CS XML file.
Links
-----
- http://ands.org.au/guides/cpguide/cpgrifcs.html
- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
- http://www.ands.org.au/resource/rif-cs.html
"""
import logging
import os
from settings import (
ANDS_XML_FILE_NAME, ANDS_XML_FOLDER_PATH, ANDS_XML_START, ANDS_XML_STOP
)
logger = logging.getLogger(__name__)
def main():
with open(ANDS_XML_FILE_NAME, 'w') as w:
w.write(ANDS_XML_START)
for file_path in os.listdir(ANDS_XML_FOLDER_PATH):
with open(file_path) as r:
w.write(r.read())
w.write(ANDS_XML_STOP)
if '__main__' == __name__:
logging.basicConfig(level=logging.DEBUG)
main()
|
Update RLDS to 0.1.5 (already uploaded to Pypi)
PiperOrigin-RevId: 467605984
Change-Id: I421e884c38da5be935e085d5419642b8decf5373 | # Copyright 2022 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# coding=utf-8
"""Package metadata for RLDS.
This is kept in a separate module so that it can be imported from setup.py, at
a time when RLDS's dependencies may not have been installed yet.
"""
# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '1'
_PATCH_VERSION = '5'
# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
| # Copyright 2022 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# coding=utf-8
"""Package metadata for RLDS.
This is kept in a separate module so that it can be imported from setup.py, at
a time when RLDS's dependencies may not have been installed yet.
"""
# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '1'
_PATCH_VERSION = '4'
# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
|
Set homepage for package as github url | # -*- coding: utf-8 -*-
"""
setup
:copyright: (c) 2012-2014 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from setuptools import setup
setup(name='trytond_sentry',
version='3.0.1.0',
description='Sentry Client for Tryton',
long_description=open('README.rst').read(),
author="Openlabs Technologies & Consulting (P) Limited",
author_email="info@openlabs.co.in",
url="https://github.com/openlabs/trytond-sentry",
package_dir={'trytond_sentry': '.'},
packages=[
'trytond_sentry',
],
scripts=[
'bin/trytond_sentry',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Office/Business',
],
license='GPL-3',
install_requires=[
"trytond>=3.0,<3.1",
"raven",
],
zip_safe=False,
)
| # -*- coding: utf-8 -*-
"""
setup
:copyright: (c) 2012-2014 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from setuptools import setup
setup(name='trytond_sentry',
version='3.0.1.0',
description='Sentry Client for Tryton',
long_description=open('README.rst').read(),
author="Openlabs Technologies & Consulting (P) Limited",
author_email="info@openlabs.co.in",
url="http://www.openlabs.co.in",
package_dir={'trytond_sentry': '.'},
packages=[
'trytond_sentry',
],
scripts=[
'bin/trytond_sentry',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Office/Business',
],
license='GPL-3',
install_requires=[
"trytond>=3.0,<3.1",
"raven",
],
zip_safe=False,
)
|
Disable CLI tests since CLI was rewritten | package main
// func ExampleCliNoArguments() {
// repos := map[string]Repo{
// "zathura": Repo{},
// "test": Repo{},
// "gamma": Repo{},
// }
// app := BuildCLI(repos, Config{})
// args := make([]string, 1)
// app.Run(args)
// // Output: gamma
// // test
// // zathura
// }
// func ExampleCliPrintItem() {
// repos := map[string]Repo{
// "joanjett": Repo{
// Info: map[string]Info{
// "bad_reputation": Info{
// Type: "info",
// Body: "I don't give a damn about my bad reputation!",
// },
// },
// },
// }
// app := BuildCLI(repos, Config{})
// args := []string{"/go/bin/sagacity", "joanjett", "bad_reputation"}
// app.Run(args)
// // Output: I don't give a damn about my bad reputation!
// }
| package main
import ()
func ExampleCliNoArguments() {
repos := map[string]Repo{
"zathura": Repo{},
"test": Repo{},
"gamma": Repo{},
}
app := BuildCLI(repos, Config{})
args := make([]string, 1)
app.Run(args)
// Output: gamma
// test
// zathura
}
func ExampleCliPrintItem() {
repos := map[string]Repo{
"joanjett": Repo{
Info: map[string]Info{
"bad_reputation": Info{
Type: "info",
Body: "I don't give a damn about my bad reputation!",
},
},
},
}
app := BuildCLI(repos, Config{})
args := []string{"/go/bin/sagacity", "joanjett", "bad_reputation"}
app.Run(args)
// Output: I don't give a damn about my bad reputation!
}
|
Change User-agent header during unittests | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from hcalendar import hCalendar
import unittest
try:
import urllib.request as urllib2
except:
import urllib2
class UfXtractSetup(unittest.TestCase):
def setUp(self):
self.file = urllib2.urlopen(urllib2.Request(self.href, headers={'User-agent': 'hCalendar'}))
self.data = hCalendar(self.file, 'uf')
def tearDown(self):
self.data = None
self.file.close()
self.file = None
def test_hcalendar(self):
self.assertTrue(self.data is not None)
def test_vcalendar(self):
self.assertTrue(self.data[0] is not None)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from hcalendar import hCalendar
import unittest
try:
import urllib.request as urllib2
except:
import urllib2
class UfXtractSetup(unittest.TestCase):
def setUp(self):
self.file = urllib2.urlopen(urllib2.Request(self.href, headers={'User-agent': 'Python hCalendar UnitTest'}))
self.data = hCalendar(self.file, 'uf')
def tearDown(self):
self.data = None
self.file.close()
self.file = None
def test_hcalendar(self):
self.assertTrue(self.data is not None)
def test_vcalendar(self):
self.assertTrue(self.data[0] is not None)
|
Set cursor to hand when over simplestyle points. | function simplestyle_factory(feature) {
var sizes = {
small: [20, 50],
medium: [30, 70],
large: [35, 90]
};
var fp = feature.properties || {};
var size = fp['marker-size'] || 'medium';
var symbol = (fp['marker-symbol']) ? '-' + fp['marker-symbol'] : '';
var color = fp['marker-color'] || '7e7e7e';
color = color.replace('#', '');
var d = document.createElement('div');
d.className = 'simplestyle-marker';
var ds = d.style;
ds.position = 'absolute';
ds.width = sizes[size][0] + 'px';
ds.height = sizes[size][1] + 'px';
ds.marginTop = -(sizes[size][1] / 2) + 'px';
ds.marginLeft = -(sizes[size][0] / 2) + 'px';
ds.cursor = 'pointer';
ds.backgroundImage = 'url(http://a.tiles.mapbox.com/v3/marker/' +
'pin-' + size[0] + symbol + '+' + color + '.png)';
ds.textIndent = '-10000px';
d.innerHTML = fp.title || '';
return d;
}
| function simplestyle_factory(feature) {
var sizes = {
small: [20, 50],
medium: [30, 70],
large: [35, 90]
};
var fp = feature.properties || {};
var size = fp['marker-size'] || 'medium';
var symbol = (fp['marker-symbol']) ? '-' + fp['marker-symbol'] : '';
var color = fp['marker-color'] || '7e7e7e';
color = color.replace('#', '');
var d = document.createElement('div');
d.className = 'simplestyle-marker';
var ds = d.style;
ds.position = 'absolute';
ds.width = sizes[size][0] + 'px';
ds.height = sizes[size][1] + 'px';
ds.marginTop = -(sizes[size][1] / 2) + 'px';
ds.marginLeft = -(sizes[size][0] / 2) + 'px';
ds.backgroundImage = 'url(http://a.tiles.mapbox.com/v3/marker/' +
'pin-' + size[0] + symbol + '+' + color + '.png)';
ds.textIndent = '-10000px';
d.innerHTML = fp.title || '';
return d;
}
|
Document unhexlify requirements in hash_token() | import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
| import binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes
from knox.settings import knox_settings, CONSTANTS
sha = knox_settings.SECURE_HASH_ALGORITHM
def create_token_string():
return binascii.hexlify(
generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
).decode()
def create_salt_string():
return binascii.hexlify(
generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()
def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode()
|
Use the same towgs84 value (not a rounded one)
http://spatialreference.org/ref/epsg/2056/proj4/
http://spatialreference.org/ref/epsg/21781/proj4/ | goog.provide('ngeo.proj.EPSG21781');
goog.require('ol.proj');
if (typeof proj4 == 'function') {
var epsg21781def = [
'+proj=somerc',
'+lat_0=46.95240555555556',
'+lon_0=7.439583333333333',
'+k_0=1',
'+x_0=600000',
'+y_0=200000',
'+ellps=bessel',
'+towgs84=674.374,15.056,405.346,0,0,0,0',
'+units=m',
'+no_defs'
].join(' ');
var epsg21781extent = [420000, 30000, 900000, 350000];
proj4.defs('epsg:21781', epsg21781def);
proj4.defs('EPSG:21781', epsg21781def);
ol.proj.get('epsg:21781').setExtent(epsg21781extent);
ol.proj.get('EPSG:21781').setExtent(epsg21781extent);
}
| goog.provide('ngeo.proj.EPSG21781');
goog.require('ol.proj');
if (typeof proj4 == 'function') {
var epsg21781def = [
'+proj=somerc',
'+lat_0=46.95240555555556',
'+lon_0=7.439583333333333',
'+k_0=1',
'+x_0=600000',
'+y_0=200000',
'+ellps=bessel',
'+towgs84=674.4,15.1,405.3,0,0,0,0',
'+units=m',
'+no_defs'
].join(' ');
var epsg21781extent = [420000, 30000, 900000, 350000];
proj4.defs('epsg:21781', epsg21781def);
proj4.defs('EPSG:21781', epsg21781def);
ol.proj.get('epsg:21781').setExtent(epsg21781extent);
ol.proj.get('EPSG:21781').setExtent(epsg21781extent);
}
|
Fix the webpack file port number. | var webpack = require('webpack');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:3001',
'webpack/hot/only-dev-server',
'./src/index.js'
],
resolve: {
root: __dirname + '/src'
},
output: {
path: __dirname + '/dist',
publicPath: 'http://localhost:3001/dist/',
filename: 'bundle.js'
},
module: {
loaders: [
{test: /\.css$/, loader: 'style-loader!css-loader!autoprefixer-loader'},
{test: /\.js$/, loader: 'react-hot!babel-loader?experimental', exclude: /node_modules/},
{test: /\.(png|jpg|svg|ttf|eot|woff|woff2)$/, loader: 'url-loader?limit=8192'}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
| var webpack = require('webpack');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index.js'
],
resolve: {
root: __dirname + '/src'
},
output: {
path: __dirname + '/dist',
publicPath: 'http://localhost:3000/dist/',
filename: 'bundle.js'
},
module: {
loaders: [
{test: /\.css$/, loader: 'style-loader!css-loader!autoprefixer-loader'},
{test: /\.js$/, loader: 'react-hot!babel-loader?experimental', exclude: /node_modules/},
{test: /\.(png|jpg|svg|ttf|eot|woff|woff2)$/, loader: 'url-loader?limit=8192'}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
|
Add new user form data to db | from flask import Flask, render_template, request
from models import db, User
from forms import SignupForm
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/strabo'
db.init_app(app)
app.secret_key = ""
@app.route("/")
def index():
return render_template("index.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/signup", methods=["GET", "POST"])
def signup():
form = SignupForm()
if request.method == "POST":
if form.validate() == False:
return render_template('signup.html', form=form)
else:
newuser = User(form.first_name.data, form.last_name.data, form.email.data, form.password.data)
db.session.add(newuser)
db.session.commit()
return 'Success!'
elif request.method == "GET":
return render_template('signup.html', form=form)
if __name__ == "__main__":
app.run(debug=True) | from flask import Flask, render_template, request
from models import db
from forms import SignupForm
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/strabo'
db.init_app(app)
app.secret_key = ""
@app.route("/")
def index():
return render_template("index.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/signup", methods=["GET", "POST"])
def signup():
form = SignupForm()
if request.method == "POST":
if form.validate() == False:
return render_template('signup.html', form=form)
else:
return "Success!"
elif request.method == "GET":
return render_template('signup.html', form=form)
if __name__ == "__main__":
app.run(debug=True) |
Bump version numer to 1.0.1 | # coding: utf-8
from __future__ import absolute_import, division, print_function
from .api import DBStats, ShortenedURL
from .core import YOURLSAPIMixin, YOURLSClient, YOURLSClientBase
from .exc import (
YOURLSAPIError, YOURLSHTTPError, YOURLSKeywordExistsError,
YOURLSNoLoopError, YOURLSNoURLError, YOURLSURLExistsError)
from .log import logger
__author__ = 'Frazer McLean <frazer@frazermclean.co.uk>'
__version__ = '1.0.1'
__license__ = 'MIT'
__description__ = 'Python client for YOURLS.'
__all__ = (
'DBStats',
'logger',
'ShortenedURL',
'YOURLSAPIError',
'YOURLSAPIMixin',
'YOURLSClient',
'YOURLSClientBase',
'YOURLSHTTPError',
'YOURLSKeywordExistsError',
'YOURLSNoLoopError',
'YOURLSNoURLError',
'YOURLSURLExistsError',
)
| # coding: utf-8
from __future__ import absolute_import, division, print_function
from .api import DBStats, ShortenedURL
from .core import YOURLSAPIMixin, YOURLSClient, YOURLSClientBase
from .exc import (
YOURLSAPIError, YOURLSHTTPError, YOURLSKeywordExistsError,
YOURLSNoLoopError, YOURLSNoURLError, YOURLSURLExistsError)
from .log import logger
__author__ = 'Frazer McLean <frazer@frazermclean.co.uk>'
__version__ = '1.0.0'
__license__ = 'MIT'
__description__ = 'Python client for YOURLS.'
__all__ = (
'DBStats',
'logger',
'ShortenedURL',
'YOURLSAPIError',
'YOURLSAPIMixin',
'YOURLSClient',
'YOURLSClientBase',
'YOURLSHTTPError',
'YOURLSKeywordExistsError',
'YOURLSNoLoopError',
'YOURLSNoURLError',
'YOURLSURLExistsError',
)
|
Fix super call to get from GitHub model | const fs = require('fs')
const path = require('path')
const Config = require('../config.json')
const Fetcher = require('./fetcher')
class GitHub extends Fetcher {
// https://developer.github.com/v3/activity/notifications/#list-your-notifications
getNotifications() {
return this.get('notifications')
}
static getToken() {
const tokenPath = path.join(__dirname, '..', '..', '.env')
return fs.readFileSync(tokenPath).toString()
}
get(relativeUrl) {
const url = `${Config.githubApiUrl}/${relativeUrl}`
const token = GitHub.getToken()
const options = {
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `token ${token}`,
},
}
return super.get(url, options)
}
}
module.exports = GitHub
| const fs = require('fs')
const path = require('path')
const Config = require('../config.json')
const Fetcher = require('./fetcher')
class GitHub extends Fetcher {
// https://developer.github.com/v3/activity/notifications/#list-your-notifications
getNotifications() {
return this.get('notifications')
}
static getToken() {
const tokenPath = path.join(__dirname, '..', '..', '.env')
return fs.readFileSync(tokenPath).toString()
}
get(relativeUrl) {
const url = `${Config.githubApiUrl}/${relativeUrl}`
const token = this.getToken()
const options = {
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `token ${token}`,
},
}
console.log('github get', url, options)
return this.get(url, options)
}
}
module.exports = GitHub
|
Add favicon tag to header.
git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@867 54a900ba-8191-11dd-a5c9-f1483cedc3eb | <?php session_start(); ?>
<!DOCTYPE html>
<head>
<title>ClinicCases - Online Case Management Software for Law School Clinics</title>
<meta name="robots" content="noindex">
<link rel="stylesheet" href="html/css/cm.css" type="text/css">
<link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css">
<link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css">
<link rel="shortcut icon" type="image/x-icon" href="html/images/favicon.ico">
<script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script>
<script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script>
<script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>
| <?php session_start(); ?>
<!DOCTYPE html>
<head>
<title>ClinicCases - Online Case Management Software for Law School Clinics</title>
<meta name="robots" content="noindex">
<link rel="stylesheet" href="html/css/cm.css" type="text/css">
<link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css">
<link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css">
<script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script>
<script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script>
<script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>
|
Use GDRIVE prefix in env vars | /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
maxSize: process.env.MAX_SIZE || 50,
mongoUrl: process.env.MONGOLAB_URI,
redisUrl: process.env.REDISCLOUD_URL,
googleId: process.env.GDRIVE_ID,
googleSecret: process.env.GDRIVE_SECRET,
appId: process.env.GDRIVE_ANYFETCH_ID,
appSecret: process.env.GDRIVE_ANYFETCH_SECRET,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GDRIVE_TEST_REFRESH_TOKEN
};
| /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
maxSize: process.env.MAX_SIZE || 50,
mongoUrl: process.env.MONGOLAB_URI,
redisUrl: process.env.REDISCLOUD_URL,
googleId: process.env.GOOGLE_DRIVE_ID,
googleSecret: process.env.GOOGLE_DRIVE_SECRET,
appId: process.env.GOOGLE_DRIVE_ANYFETCH_ID,
appSecret: process.env.GOOGLE_DRIVE_ANYFETCH_SECRET,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GOOGLE_DRIVE_TEST_REFRESH_TOKEN
};
|
Fix worker creation with * as queues selector
Fix worker creation with * as queues selector. With the current implementation it doesn't work.
Example of usage:
monqClient = monq('connstr');
worker = monqClient.worker('*', { ... }); | var mongo = require('mongojs');
var job = require('./job');
var Queue = require('./queue');
var Worker = require('./worker');
module.exports = Connection;
/**
* @constructor
* @param {string} uri - MongoDB connection string
* @param {Object} options - connection options
*/
function Connection(uri, options) {
this.db = mongo(uri, [], options);
}
/**
* Returns a new {@link Worker}
* @param {string[]|string} queues - list of queue names, a single queue name, or '*' for a universal worker
* @param {Object} options - an object with worker options
*/
Connection.prototype.worker = function (queues, options) {
var self = this;
if (queues === "*") {
var opts = {universal: true, collection: options.collection || 'jobs' };
options.universal = true;
queues = [self.queue('*', opts)];
} else {
if (!Array.isArray(queues)) {
queues = [queues];
}
var queues = queues.map(function (queue) {
if (typeof queue === 'string') {
queue = self.queue(queue);
}
return queue;
});
}
return new Worker(queues, options);
};
Connection.prototype.queue = function (name, options) {
return new Queue(this, name, options);
};
Connection.prototype.close = function () {
this.db.close();
};
| var mongo = require('mongojs');
var job = require('./job');
var Queue = require('./queue');
var Worker = require('./worker');
module.exports = Connection;
/**
* @constructor
* @param {string} uri - MongoDB connection string
* @param {Object} options - connection options
*/
function Connection(uri, options) {
this.db = mongo(uri, [], options);
}
/**
* Returns a new {@link Worker}
* @param {string[]|string} queues - list of queue names, a single queue name, or '*' for a universal worker
* @param {Object} options - an object with worker options
*/
Connection.prototype.worker = function (queues, options) {
var self = this;
if (queues === "*") {
var opts = {universal: true, collection: options.collection || 'jobs' };
options.universal = true;
queues = [new Queue('*', opts)];
} else {
if (!Array.isArray(queues)) {
queues = [queues];
}
var queues = queues.map(function (queue) {
if (typeof queue === 'string') {
queue = self.queue(queue);
}
return queue;
});
}
return new Worker(queues, options);
};
Connection.prototype.queue = function (name, options) {
return new Queue(this, name, options);
};
Connection.prototype.close = function () {
this.db.close();
};
|
Disable gzip compression for libraries
Disable gzip compression to let services like wget get libraries uncompressed | var gulp = require('gulp');
var awspublish = require('gulp-awspublish');
var rename = require('gulp-rename');
var fs = require('fs');
gulp.task('upload-bower-lib', function() {
// create a new publisher
var publisher = awspublish.create({ bucket: "www.bastly.com", region: "eu-central-1" });
// define custom headers
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
var releaseVersion = JSON.parse(fs.readFileSync('./bower.json')).version;
return gulp.src('./dist/browser/*.*')
// Rename files and specify directories
.pipe(rename(function (path) {
path.dirname += '/releases/browser';
path.basename = path.basename.replace('bastly', 'bastly-' + releaseVersion);
}))
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
.pipe(publisher.cache())
// print upload updates to console
.pipe(awspublish.reporter());
});
| var gulp = require('gulp');
var awspublish = require('gulp-awspublish');
var rename = require('gulp-rename');
var fs = require('fs');
gulp.task('upload-bower-lib', function() {
// create a new publisher
var publisher = awspublish.create({ bucket: "www.bastly.com", region: "eu-central-1" });
// define custom headers
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
var releaseVersion = JSON.parse(fs.readFileSync('./bower.json')).version;
return gulp.src('./dist/browser/*.*')
// Rename files and specify directories
.pipe(rename(function (path) {
path.dirname += '/releases/browser';
path.basename = path.basename.replace('bastly', 'bastly-' + releaseVersion);
}))
// gzip, Set Content-Encoding headers and add .gz extension
.pipe(awspublish.gzip())
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
.pipe(publisher.cache())
// print upload updates to console
.pipe(awspublish.reporter());
});
|
Remove the logging handler since heroku's log is good enough | package main
import (
"net/http"
)
func optionsOk(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("access-control-allow-origin", "*")
w.Header().Set("access-control-allow-methods", "GET, POST, PATCH, DELETE")
w.Header().Set("access-control-allow-headers", "accept, content-type")
if r.Method == "OPTIONS" {
return // Preflight sets headers and we're done
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func contentTypeJsonHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func commonHandlers(next http.HandlerFunc) http.Handler {
return contentTypeJsonHandler(optionsOk(next))
}
| package main
import (
"log"
"net/http"
"time"
)
func optionsOk(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("access-control-allow-origin", "*")
w.Header().Set("access-control-allow-methods", "GET, POST, PATCH, DELETE")
w.Header().Set("access-control-allow-headers", "accept, content-type")
if r.Method == "OPTIONS" {
return // Preflight sets headers and we're done
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func contentTypeJsonHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func loggingHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
next.ServeHTTP(w, r)
t2 := time.Now()
log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
}
return http.HandlerFunc(fn)
}
func commonHandlers(next http.HandlerFunc) http.Handler {
return loggingHandler(contentTypeJsonHandler(optionsOk(next)))
}
|
Add migrations to package data | #!/usr/bin/env python
from setuptools import setup
from fandjango import __version__
setup(
name = 'fandjango',
version = __version__,
description = "Fandjango makes it stupidly easy to create Facebook applications with Django.",
long_description = open('README.rst').read(),
author = "Johannes Gorset",
author_email = "jgorset@gmail.com",
url = "http://github.com/jgorset/fandjango",
packages = [
'fandjango',
'fandjango.migrations',
'fandjango.templatetags'
],
package_data = {
'fandjango': [
'templates/*',
'locale/*'
'migrations/*'
]
},
install_requires = [
'facepy==0.5.1',
'requests==0.7.6'
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
]
)
| #!/usr/bin/env python
from setuptools import setup
from fandjango import __version__
setup(
name = 'fandjango',
version = __version__,
description = "Fandjango makes it stupidly easy to create Facebook applications with Django.",
long_description = open('README.rst').read(),
author = "Johannes Gorset",
author_email = "jgorset@gmail.com",
url = "http://github.com/jgorset/fandjango",
packages = [
'fandjango',
'fandjango.migrations',
'fandjango.templatetags'
],
package_data = {
'fandjango': ['templates/*', 'locale/*']
},
install_requires = [
'facepy==0.5.1',
'requests==0.7.6'
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
]
)
|
Hide locations for trip which have no matching location | import { getKeyForAddresses } from './helpers';
export function getLocations( state ) {
return state.library.locations;
}
export function getLocationById( state, id ) {
return getLocations( state ).reduce( ( found, location ) => {
if ( location._id === id ) return location;
return found;
}, null );
}
export function getLocationsForTrip( state ) {
return state.trip.map( id => getLocationById( state, id ) )
.filter( location => !! location );
}
export function getAddressesForTrip( state ) {
return getLocationsForTrip( state )
.map( location => location.address );
}
export function getAddressPairs( state ) {
const addrs = getAddressesForTrip( state );
return addrs.reduce( ( pairs, start, index ) => {
const dest = addrs[ index + 1 ];
return dest ? pairs.concat( { start, dest } ) : pairs;
}, [] );
}
export function getTripDistances( state ) {
const pairs = getAddressPairs( state );
return pairs.map( pair => getDistanceForKey( state, getKeyForAddresses( pair.start, pair.dest ) ) );
}
export function getTotalTripDistance( state ) {
return getTripDistances( state ).reduce( ( prev, num ) => prev + num, 0 );
}
export function getDistanceForKey( state, key ) {
return state.distances[ key ];
}
| import { getKeyForAddresses } from './helpers';
export function getLocations( state ) {
return state.library.locations;
}
export function getLocationById( state, id ) {
return getLocations( state ).reduce( ( found, location ) => {
if ( location._id === id ) return location;
return found;
}, null );
}
export function getLocationsForTrip( state ) {
return state.trip.map( id => getLocationById( state, id ) );
}
export function getAddressesForTrip( state ) {
return getLocationsForTrip( state )
.map( location => location.address );
}
export function getAddressPairs( state ) {
const addrs = getAddressesForTrip( state );
return addrs.reduce( ( pairs, start, index ) => {
const dest = addrs[ index + 1 ];
return dest ? pairs.concat( { start, dest } ) : pairs;
}, [] );
}
export function getTripDistances( state ) {
const pairs = getAddressPairs( state );
return pairs.map( pair => getDistanceForKey( state, getKeyForAddresses( pair.start, pair.dest ) ) );
}
export function getTotalTripDistance( state ) {
return getTripDistances( state ).reduce( ( prev, num ) => prev + num, 0 );
}
export function getDistanceForKey( state, key ) {
return state.distances[ key ];
}
|
Make the collision tests pass | var assert = require('chai').assert;
var Bubble = require('../lib/bubbles');
var Dinosaur = require('../lib/dinosaur');
var Collision = require('../lib/collision');
describe('collision', function(){
beforeEach(function(){
this.canvas = { width: 200, height: 100};
this.bubble = new Bubble(35, 65, "right", this.canvas);
this.dino_img_left = document.createElement('img');
this.dino_img_right = document.createElement('img');
this.dino = new Dinosaur(this.canvas, this.dino_img_left, this.dino_img_right);
});
it('is a collision if both x and y are in range', function(){
this.bubble.x = 175;
this.dino.x = 155;
this.bubble.y = 82.5;
this.dino.y = 75;
assert.isTrue(Collision.collision(this.bubble, this.dino));
});
it('is a collision only if both x and y are in range', function(){
this.dino.x = 155;
this.dino.y = 75;
this.bubble.x = 50;
this.bubble.y = 82.5;
assert.isFalse(Collision.collision(this.bubble, this.dino));
this.bubble.x = 50;
this.bubble.y = 30;
assert.isFalse(Collision.collision(this.bubble, this.dino));
this.bubble.x = 50;
this.bubble.y = 30;
assert.isFalse(Collision.collision(this.bubble, this.dino));
});
});
| var assert = require('chai').assert;
var Bubble = require('../lib/bubbles');
var Dinosaur = require('../lib/dinosaur');
var Collision = require('../lib/collision');
describe('collision', function(){
beforeEach(function(){
this.canvas = { width: 200, height: 100};
this.bubble = new Bubble(35, 65, "right", this.canvas);
this.dino_img_left = document.createElement('img');
this.dino_img_right = document.createElement('img');
this.dino = new Dinosaur(this.canvas, this.dino_img_left, this.dino_img_right);
});
it('collides', function(){
this.bubble.x = 175;
this.dino.x = 155;
this.bubble.y = 82.5;
this.dino.y = 75;
assert.isTrue(Collision.collideBubbleDinosaur(this.bubble, this.dino));
});
});
|
Embed the ProviderClient struct in ServiceClient.
This lets us inherit the AuthenticatedHeaders method, rather than
having to walk the references all the time. | package gophercloud
import "strings"
// ServiceClient stores details required to interact with a specific service API implemented by a provider.
// Generally, you'll acquire these by calling the appropriate `New` method on a ProviderClient.
type ServiceClient struct {
// ProviderClient is a reference to the provider that implements this service.
*ProviderClient
// Endpoint is the base URL of the service's API, acquired from a service catalog.
// It MUST end with a /.
Endpoint string
// ResourceBase is the base URL shared by the resources within a service's API. It should include
// the API version and, like Endpoint, MUST end with a / if set. If not set, the Endpoint is used
// as-is, instead.
ResourceBase string
}
// ResourceBaseURL returns the base URL of any resources used by this service. It MUST end with a /.
func (client *ServiceClient) ResourceBaseURL() string {
if client.ResourceBase != "" {
return client.ResourceBase
}
return client.Endpoint
}
// ServiceURL constructs a URL for a resource belonging to this provider.
func (client *ServiceClient) ServiceURL(parts ...string) string {
return client.ResourceBaseURL() + strings.Join(parts, "/")
}
| package gophercloud
import "strings"
// ServiceClient stores details required to interact with a specific service API implemented by a provider.
// Generally, you'll acquire these by calling the appropriate `New` method on a ProviderClient.
type ServiceClient struct {
// Provider is a reference to the provider that implements this service.
Provider *ProviderClient
// Endpoint is the base URL of the service's API, acquired from a service catalog.
// It MUST end with a /.
Endpoint string
// ResourceBase is the base URL shared by the resources within a service's API. It should include
// the API version and, like Endpoint, MUST end with a / if set. If not set, the Endpoint is used
// as-is, instead.
ResourceBase string
}
// ResourceBaseURL returns the base URL of any resources used by this service. It MUST end with a /.
func (client *ServiceClient) ResourceBaseURL() string {
if client.ResourceBase != "" {
return client.ResourceBase
}
return client.Endpoint
}
// ServiceURL constructs a URL for a resource belonging to this provider.
func (client *ServiceClient) ServiceURL(parts ...string) string {
return client.ResourceBaseURL() + strings.Join(parts, "/")
}
// AuthenticatedHeaders returns a collection of HTTP request headers that mark a request as
// belonging to the currently authenticated user.
func (client *ServiceClient) AuthenticatedHeaders() map[string]string {
return client.Provider.AuthenticatedHeaders()
}
|
Fix the package repetition bug | package controllers
import (
"github.com/astaxie/beego"
)
type ImageController struct {
beego.Controller
}
func (this *ImageController) Prepare() {
this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Version", beego.AppConfig.String("Version"))
this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Standalone", beego.AppConfig.String("Standalone"))
}
func (this *ImageController) GETPrivateLayer() {
}
func (this *ImageController) GETLayer() {
}
func (this *ImageController) PUTLayer() {
}
func (this *ImageController) PUTChecksum() {
}
func (this *ImageController) GETPrivateJSON() {
}
func (this *ImageController) GETJSON() {
}
func (this *ImageController) GETAncestry() {
}
func (this *ImageController) PUTJSON() {
}
func (this *ImageController) GETPrivateFiles() {
}
func (this *ImageController) GETFiles() {
}
| package controllers
package controllers
import (
"github.com/astaxie/beego"
)
type ImageController struct {
beego.Controller
}
func (this *ImageController) Prepare() {
this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Version", beego.AppConfig.String("Version"))
this.Ctx.Output.Context.ResponseWriter.Header().Set("X-Docker-Registry-Standalone", beego.AppConfig.String("Standalone"))
}
func (this *ImageController) GETPrivateLayer() {
}
func (this *ImageController) GETLayer() {
}
func (this *ImageController) PUTLayer() {
}
func (this *ImageController) PUTChecksum() {
}
func (this *ImageController) GETPrivateJSON() {
}
func (this *ImageController) GETJSON() {
}
func (this *ImageController) GETAncestry() {
}
func (this *ImageController) PUTJSON() {
}
func (this *ImageController) GETPrivateFiles() {
}
func (this *ImageController) GETFiles() {
} |
Handle ctrl-C-ing out of palm-log | import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def build():
"""Package up the app."""
call('palm-package', '.')
@task
def halt():
call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain')
@task
@needs('halt')
def uninstall():
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
@task
@needs('build', 'uninstall')
def push():
"""Reinstall the app and start it."""
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
@task
def tail():
"""Follow the device's log."""
call('palm-log', '--device=emulator', '--system-log-level', 'info')
try:
call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
except KeyboardInterrupt:
print
| import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def build():
"""Package up the app."""
call('palm-package', '.')
@task
def halt():
call('palm-launch', '--device=emulator', '-c', 'org.markpasc.paperplain')
@task
@needs('halt')
def uninstall():
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
@task
@needs('build', 'uninstall')
def push():
"""Reinstall the app and start it."""
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
@task
def tail():
"""Follow the device's log."""
call('palm-log', '--device=emulator', '--system-log-level', 'info')
call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
|
Use const/let instead of var | 'use strict';
const peg = require('pegjs');
class PegJsPlugin {
constructor(config) {
this.config = config.plugins.pegjs;
// The output of the below peg.generate() function must be a string, not an
// object
this.config.output = 'source';
}
compile(file) {
let parser;
try {
parser = peg.generate(file.data, this.config);
} catch(error) {
if (error instanceof peg.parser.SyntaxError) {
error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`;
}
return Promise.reject(error);
}
return Promise.resolve({data: parser});
}
}
// brunchPlugin must be set to true for all Brunch plugins
PegJsPlugin.prototype.brunchPlugin = true;
// The type of file to generate
PegJsPlugin.prototype.type = 'javascript';
// The extension for files to process
PegJsPlugin.prototype.extension = 'pegjs';
// The extension for processed files (this allows for compiler chaining)
PegJsPlugin.prototype.targetExtension = 'js';
module.exports = PegJsPlugin;
| 'use strict';
var peg = require('pegjs');
class PegJsPlugin {
constructor(config) {
this.config = config.plugins.pegjs;
// The output of the below peg.generate() function must be a string, not an
// object
this.config.output = 'source';
}
compile(file) {
var parser;
try {
parser = peg.generate(file.data, this.config);
} catch(error) {
if (error instanceof peg.parser.SyntaxError) {
error.message = `${error.message} at ${error.location.start.line}:${error.location.start.column}`;
}
return Promise.reject(error);
}
return Promise.resolve({data: parser});
}
}
// brunchPlugin must be set to true for all Brunch plugins
PegJsPlugin.prototype.brunchPlugin = true;
// The type of file to generate
PegJsPlugin.prototype.type = 'javascript';
// The extension for files to process
PegJsPlugin.prototype.extension = 'pegjs';
// The extension for processed files (this allows for compiler chaining)
PegJsPlugin.prototype.targetExtension = 'js';
module.exports = PegJsPlugin;
|
Format missing fields in errors more nicely | module.exports = {
dropExcludedProperties: function(propertyList, originalObject) {
return propertyList.reduce(function(incompleteObject, property) {
incompleteObject[property] = originalObject[property];
return incompleteObject;
}, {});
},
requireNotVagueFlag: function(req) {
if (req.body.notVague === 'true') {
// Now the flag won't be left hanging around
req.body = {};
} else if (Object.getOwnPropertyNames(req.body).length === 0) {
return new Error('Possibly too vague: use notVague=true to enforce');
}
return null;
},
requireFields: function(req, requiredFields) {
let missingFields = requiredFields.reduce(function(mf, rf) {
return req.body[rf] === undefined ? mf.concat(rf) : mf;
}, []);
let missingFormattedFields = missingFields.join(', ');
// Early exit in case of missing fields
if (missingFields.length !== 0) {
return new Error(`Missing fields: ${missingFormattedFields}`);
}
}
};
| module.exports = {
dropExcludedProperties: function(propertyList, originalObject) {
return propertyList.reduce(function(incompleteObject, property) {
incompleteObject[property] = originalObject[property];
return incompleteObject;
}, {});
},
requireNotVagueFlag: function(req) {
if (req.body.notVague === 'true') {
// Now the flag won't be left hanging around
req.body = {};
} else if (Object.getOwnPropertyNames(req.body).length === 0) {
return new Error('Possibly too vague: use notVague=true to enforce');
}
return null;
},
requireFields: function(req, requiredFields) {
let missingFields = requiredFields.reduce(function(mf, rf) {
return req.body[rf] === undefined ? mf.concat(rf) : mf;
}, []);
// Early exit in case of missing fields
if (missingFields.length !== 0) {
return new Error(`Missing fields: ${missingFields}`);
}
}
};
|
Add Flask-session as a dependency | from setuptools import setup
setup(
name='Fulfil-Shop',
version='0.1dev',
packages=['shop'],
license='BSD',
include_package_data=True,
zip_safe=False,
long_description=open('README.rst').read(),
install_requires=[
'Flask',
'Flask-WTF',
'Flask-Assets',
'cssmin',
'jsmin',
'Flask-Login',
'Flask-Cache',
'Flask-DebugToolbar',
'Flask-Themes2',
'Flask-Babel',
'Flask-Redis',
'Flask-Session',
'Flask-Fulfil',
'raven[flask]',
'premailer',
]
)
| from setuptools import setup
setup(
name='Fulfil-Shop',
version='0.1dev',
packages=['shop'],
license='BSD',
include_package_data=True,
zip_safe=False,
long_description=open('README.rst').read(),
install_requires=[
'Flask',
'Flask-WTF',
'Flask-Assets',
'cssmin',
'jsmin',
'Flask-Login',
'Flask-Cache',
'Flask-DebugToolbar',
'Flask-Themes2',
'Flask-Babel',
'Flask-Redis',
'Flask-Fulfil',
'raven[flask]',
'premailer',
]
)
|
Remove unneeded import of json module. | # This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number)
# - description (String)
import requests, urllib
SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'
class core_handler:
def get_score(self, identifier, **kwargs):
"""Return the number of mentions in CORE and a descriptor, as a tuple.
Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
params = {
'api_key': API_KEY,
'format': 'json',
}
params.update(kwargs)
response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
response.raise_for_status()
results = response.json()
score = results['ListRecords'][0]['total_hits']
return score
def get_description(self):
return 'mentions in Open Access articles (via http://core.ac.uk/)'
| # This is a software index handler that gives a score based on the
# number of mentions in open access articles. It uses the CORE
# aggregator (http://core.ac.uk/) to search the full text of indexed
# articles.
#
# Inputs:
# - identifier (String)
#
# Outputs:
# - score (Number)
# - description (String)
import requests, json, urllib
SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'
class core_handler:
def get_score(self, identifier, **kwargs):
"""Return the number of mentions in CORE and a descriptor, as a tuple.
Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
params = {
'api_key': API_KEY,
'format': 'json',
}
params.update(kwargs)
response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
response.raise_for_status()
results = response.json()
score = results['ListRecords'][0]['total_hits']
return score
def get_description(self):
return 'mentions in Open Access articles (via http://core.ac.uk/)'
|
Fix SpongeAnvilGUI so that it actually extends a calss that exists. | package io.musician101.musicianlibrary.java.minecraft.sponge.gui.anvil;
import java.util.function.BiConsumer;
import javax.annotation.Nonnull;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
public class SpongeJumpToPage<P extends PluginContainer> extends SpongeAnvilGUI {
public SpongeJumpToPage(@Nonnull P plugin, @Nonnull Player player, int maxPage, @Nonnull BiConsumer<Player, Integer> biConsumer) {
super(player, (p, name) -> {
int page;
try {
page = Integer.parseInt(name);
}
catch (NumberFormatException e) {
return "That is not a number!";
}
if (page > maxPage) {
return "Page cannot exceed " + maxPage;
}
Task.builder().delayTicks(1L).execute(() -> biConsumer.accept(player, page)).submit(plugin.getInstance().get());
return null;
});
}
}
| package io.musician101.musicianlibrary.java.minecraft.sponge.gui.anvil;
import io.musician101.musicianlibrary.java.minecraft.config.AbstractConfig;
import io.musician101.musicianlibrary.java.minecraft.sponge.plugin.AbstractSpongePlugin;
import java.util.function.BiConsumer;
import javax.annotation.Nonnull;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.scheduler.Task;
public class SpongeJumpToPage<C extends AbstractConfig, P extends AbstractSpongePlugin<C>> extends SpongeAnvilGUI {
public SpongeJumpToPage(@Nonnull P plugin, @Nonnull Player player, int maxPage, @Nonnull BiConsumer<Player, Integer> biConsumer) {
super(player, (p, name) -> {
int page;
try {
page = Integer.parseInt(name);
}
catch (NumberFormatException e) {
return "That is not a number!";
}
if (page > maxPage) {
return "Page cannot exceed " + maxPage;
}
Task.builder().delayTicks(1L).execute(() -> biConsumer.accept(player, page)).submit(plugin.getInstance().get());
return null;
});
}
}
|
Fix out dir in report | import os
import shutil
import logging
#try:
# from bcbio.install import _set_matplotlib_default_backend
# _set_matplotlib_default_backend()
#except (ImportError, OSError, IOError):
# pass
#import matplotlib
#matplotlib.use('Agg', force=True)
from libs.read import load_data
from libs.report import make_profile
from libs.utils import safe_dirs
from db import make_database
import templates
logger = logging.getLogger('report')
def report(args):
"""
Create report in html format
"""
logger.info("reading sequeces")
data = load_data(args.json)
logger.info("create profile")
data = make_profile(data, args.out, args)
logger.info("create database")
make_database(data, "seqcluster.db", args.out)
logger.info("Done. Download https://github.com/lpantano/seqclusterViz/archive/master.zip to browse the output.")
| import os
import shutil
import logging
#try:
# from bcbio.install import _set_matplotlib_default_backend
# _set_matplotlib_default_backend()
#except (ImportError, OSError, IOError):
# pass
#import matplotlib
#matplotlib.use('Agg', force=True)
from libs.read import load_data
from libs.report import make_profile
from libs.utils import safe_dirs
from db import make_database
import templates
logger = logging.getLogger('report')
def report(args):
"""
Create report in html format
"""
logger.info("reading sequeces")
data = load_data(args.json)
logger.info("create profile")
data = make_profile(data, out_dir, args)
logger.info("create database")
make_database(data, "seqcluster.db", args.out)
logger.info("Done. Download https://github.com/lpantano/seqclusterViz/archive/master.zip to browse the output.")
|
Generalize scss bundle to track all scss files | from flask.ext.assets import Bundle
app_css = Bundle(
'*.scss',
filters='scss',
output='styles/app.css'
)
app_js = Bundle(
'app.js',
'descriptor.js',
'map.js',
'resources.js',
filters='jsmin',
output='scripts/app.js'
)
vendor_css = Bundle(
'vendor/semantic.min.css',
output='styles/vendor.css'
)
vendor_js = Bundle(
'vendor/jquery.min.js',
'vendor/async.js',
'vendor/address-autocomplete.js',
'vendor/papaparse.min.js',
'vendor/semantic.min.js',
'vendor/tablesort.min.js',
filters='jsmin',
output='scripts/vendor.js'
)
| from flask.ext.assets import Bundle
app_css = Bundle(
'app.scss',
'map.scss',
filters='scss',
output='styles/app.css'
)
app_js = Bundle(
'app.js',
'descriptor.js',
'map.js',
'resources.js',
filters='jsmin',
output='scripts/app.js'
)
vendor_css = Bundle(
'vendor/semantic.min.css',
output='styles/vendor.css'
)
vendor_js = Bundle(
'vendor/jquery.min.js',
'vendor/async.js',
'vendor/address-autocomplete.js',
'vendor/papaparse.min.js',
'vendor/semantic.min.js',
'vendor/tablesort.min.js',
filters='jsmin',
output='scripts/vendor.js'
)
|
Fix bad program/cycle error message. | <?php
/**
* Base controller for unauthenticated Apply controllers
* @author Jon Johnson <jon.johnson@ucsf.edu>
* @package jazzee
* @subpackage apply
*/
class ApplyGuestController extends JazzeeController{
/**
* The program if it is available
* @var Program
*/
protected $program;
/**
* The application if it is available
* @var Application
*/
protected $application;
/**
* Before any action do some setup
* Set the navigation to horizontal
* If we know the program and cycle load the applicant var
* If we only know the program fill that in
* @return null
*/
protected function beforeAction(){
parent::beforeAction();
if(!empty($this->actionParams['programShortName']) AND !empty($this->actionParams['cycleName'])){
$program = Doctrine::getTable('Program')->findOneByShortName($this->actionParams['programShortName']);
$cycle = Doctrine::getTable('Cycle')->findOneByName($this->actionParams['cycleName']);
if(!$this->application = Doctrine::getTable('Application')->findOneByProgramIDAndCycleID($program->id, $cycle->id)){
throw new Exception("{$this->actionParams['cycleName']} {$this->actionParams['programShortName']} is not a valid program");
}
} else if(!empty($this->actionParams['programShortName'])){
if(!$this->program = Doctrine::getTable('Program')->findOneByShortName($this->actionParams['programShortName'])){
throw new Exception("{$this->actionParams['programShortName']} is not a valid program");
}
}
}
}
?> | <?php
/**
* Base controller for unauthenticated Apply controllers
* @author Jon Johnson <jon.johnson@ucsf.edu>
* @package jazzee
* @subpackage apply
*/
class ApplyGuestController extends JazzeeController{
/**
* The program if it is available
* @var Program
*/
protected $program;
/**
* The application if it is available
* @var Application
*/
protected $application;
/**
* Before any action do some setup
* Set the navigation to horizontal
* If we know the program and cycle load the applicant var
* If we only know the program fill that in
* @return null
*/
protected function beforeAction(){
parent::beforeAction();
if(!empty($this->actionParams['programShortName']) AND !empty($this->actionParams['cycleName'])){
$program = Doctrine::getTable('Program')->findOneByShortName($this->actionParams['programShortName']);
$cycle = Doctrine::getTable('Cycle')->findOneByName($this->actionParams['cycleName']);
if(!$this->application = Doctrine::getTable('Application')->findOneByProgramIDAndCycleID($program->id, $cycle->id)){
throw new Exception("{$this->actionParams['programShortName']} is not a valid program");
}
} else if(!empty($this->actionParams['programShortName'])){
if(!$this->program = Doctrine::getTable('Program')->findOneByShortName($this->actionParams['programShortName'])){
throw new Exception("{$this->actionParams['programShortName']} is not a valid program");
}
}
}
}
?> |
Change PATCH verb in POST, Slim seems to have problems using getParsedBody method :( | <?php
/**
* Register routes for each available item types
*/
foreach ($app->getContainer()['item_types'] as $item_type) {
$app->group('/' . $item_type, function () use ($item_type) {
// List all items
$this->get('', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:listItems');
// Get item's data
$this->get('/{id:[0-9]+}', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:getItem');
// Create a new item
$this->post('', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:createItem');
// Update an item
// Should be more correct use PATCH verb but Slim seems to have problems with getParsedBody method :(
$this->post('/{id:[0-9]+}', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:updateItem');
// Delete an item
$this->delete('/{id:[0-9]+}', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:deleteItem');
});
}
/**
* Generic fallback route
*/
$app->any('[/{path:.*}]', function ($request, $response, $args) {
return $response->withStatus(400)->withJson([
'status' => 400,
'message' => 'Bad request',
]);
}); | <?php
/**
* Register routes for each available item types
*/
foreach ($app->getContainer()['item_types'] as $item_type) {
$app->group('/' . $item_type, function () use ($item_type) {
// List all items
$this->get('', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:listItems');
// Get item's data
$this->get('/{id:[0-9]+}', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:getItem');
// Create a new item
$this->post('', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:createItem');
// Update an item
$this->patch('/{id:[0-9]+}', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:updateItem');
// Delete an item
$this->delete('/{id:[0-9]+}', 'WalletLogger\\' . ucfirst($item_type) . 'Controller:deleteItem');
});
}
/**
* Generic fallback route
*/
$app->any('[/{path:.*}]', function ($request, $response, $args) {
return $response->withStatus(400)->withJson(['message' => 'Bad request']);
}); |
Make these exception messages translatable | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import TemplateView
from django.utils.translation import ugettext as _
class SimpleWellView(TemplateView):
def render_to_response(self, context, **response_kwargs):
if not 'params' in context:
raise ImproperlyConfigured(
_(u"Expects `params` to be provided in the context"))
if not self.template_name:
if not 'template_name' in context['params']:
raise ImproperlyConfigured(
_(u"Expects `template_name` to be provided"))
else:
self.template_name = context['params']['template_name']
if not 'well' in context['params']:
raise ImproperlyConfigured(_(u"Expects a `well` to be provided"))
return super(SimpleWellView, self).render_to_response(context,
**response_kwargs)
| from django.core.exceptions import ImproperlyConfigured
from django.views.generic import TemplateView
class SimpleWellView(TemplateView):
def render_to_response(self, context, **response_kwargs):
if not 'params' in context:
raise ImproperlyConfigured(
"Expects `params` to be provided in the context")
if not self.template_name:
if not 'template_name' in context['params']:
raise ImproperlyConfigured(
"Expects `template_name` to be provided")
else:
self.template_name = context['params']['template_name']
if not 'well' in context['params']:
raise ImproperlyConfigured("Expects a `well` to be provided")
return super(SimpleWellView, self).render_to_response(context,
**response_kwargs)
|
Add "include_initial" kwarg to support tailing stack updates
`get_events` will return all events that have occurred for a stack. This
is useless if we're tailing an update to a stack. | import time
def _tail_print(e):
print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))
def get_events(conn, stackname):
"""Get the events in batches and return in chronological order"""
next = None
event_list = []
while 1:
events = conn.describe_stack_events(stackname, next)
event_list.append(events)
if events.next_token is None:
break
next = events.next_token
time.sleep(1)
return reversed(sum(event_list, []))
def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_name)
for e in initial_events:
if include_initial:
log_func(e)
seen.add(e.event_id)
# Now keep looping through and dump the new events
while 1:
events = get_events(conn, stack_name)
for e in events:
if e.event_id not in seen:
log_func(e)
seen.add(e.event_id)
time.sleep(sleep_time)
| import time
def _tail_print(e):
print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))
def get_events(conn, stackname):
"""Get the events in batches and return in chronological order"""
next = None
event_list = []
while 1:
events = conn.describe_stack_events(stackname, next)
event_list.append(events)
if events.next_token is None:
break
next = events.next_token
time.sleep(1)
return reversed(sum(event_list, []))
def tail(conn, stack_name, log_func=_tail_print, sleep_time=5):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_name)
for e in initial_events:
log_func(e)
seen.add(e.event_id)
# Now keep looping through and dump the new events
while 1:
events = get_events(conn, stack_name)
for e in events:
if e.event_id not in seen:
log_func(e)
seen.add(e.event_id)
time.sleep(sleep_time)
|
Improve check in method "on" | package org.bouncycastle.asn1;
public class ASN1ObjectIdentifier
extends DERObjectIdentifier
{
public ASN1ObjectIdentifier(String identifier)
{
super(identifier);
}
ASN1ObjectIdentifier(byte[] bytes)
{
super(bytes);
}
/**
* Return an OID that creates a branch under the current one.
*
* @param branchID node numbers for the new branch.
* @return
*/
public ASN1ObjectIdentifier branch(String branchID)
{
return new ASN1ObjectIdentifier(getId() + "." + branchID);
}
/**
* Return true if this oid is an extension of the passed in branch, stem.
* @param stem the arc or branch that is a possible parent.
* @return true if the branch is on the passed in stem, false otherwise.
*/
public boolean on(ASN1ObjectIdentifier stem)
{
String id = getId(), stemId = stem.getId();
return id.length() > stemId.length() && id.charAt(stemId.length()) == '.' && id.startsWith(stemId);
}
}
| package org.bouncycastle.asn1;
public class ASN1ObjectIdentifier
extends DERObjectIdentifier
{
public ASN1ObjectIdentifier(String identifier)
{
super(identifier);
}
ASN1ObjectIdentifier(byte[] bytes)
{
super(bytes);
}
/**
* Return an OID that creates a branch under the current one.
*
* @param branchID node numbers for the new branch.
* @return
*/
public ASN1ObjectIdentifier branch(String branchID)
{
return new ASN1ObjectIdentifier(getId() + "." + branchID);
}
/**
* Return true if this oid is an extension of the passed in branch, stem.
* @param stem the arc or branch that is a possible parent.
* @return true if the branch is on the passed in stem, false otherwise.
*/
public boolean on(ASN1ObjectIdentifier stem)
{
return this.getId().startsWith(stem.getId());
}
}
|
Append friendly query name to gql request
Reviewed By: jstejada
Differential Revision: D23665236
fbshipit-source-id: c89018597ab327d6339f96d556ab81edfdb97b3f | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
type FeatureFlags = {|
ENABLE_VARIABLE_CONNECTION_KEY: boolean,
ENABLE_PARTIAL_RENDERING_DEFAULT: boolean,
ENABLE_RELAY_CONTAINERS_SUSPENSE: boolean,
ENABLE_PRECISE_TYPE_REFINEMENT: boolean,
ENABLE_REACT_FLIGHT_COMPONENT_FIELD: boolean,
ENABLE_REQUIRED_DIRECTIVES: boolean | string,
ENABLE_GETFRAGMENTIDENTIFIER_OPTIMIZATION: boolean,
ENABLE_FRIENDLY_QUERY_NAME_GQL_URL: boolean,
|};
const RelayFeatureFlags: FeatureFlags = {
ENABLE_VARIABLE_CONNECTION_KEY: false,
ENABLE_PARTIAL_RENDERING_DEFAULT: false,
ENABLE_RELAY_CONTAINERS_SUSPENSE: false,
ENABLE_PRECISE_TYPE_REFINEMENT: false,
ENABLE_REACT_FLIGHT_COMPONENT_FIELD: false,
ENABLE_REQUIRED_DIRECTIVES: false,
ENABLE_GETFRAGMENTIDENTIFIER_OPTIMIZATION: false,
ENABLE_FRIENDLY_QUERY_NAME_GQL_URL: false,
};
module.exports = RelayFeatureFlags;
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
type FeatureFlags = {|
ENABLE_VARIABLE_CONNECTION_KEY: boolean,
ENABLE_PARTIAL_RENDERING_DEFAULT: boolean,
ENABLE_RELAY_CONTAINERS_SUSPENSE: boolean,
ENABLE_PRECISE_TYPE_REFINEMENT: boolean,
ENABLE_REACT_FLIGHT_COMPONENT_FIELD: boolean,
ENABLE_REQUIRED_DIRECTIVES: boolean | string,
ENABLE_GETFRAGMENTIDENTIFIER_OPTIMIZATION: boolean,
|};
const RelayFeatureFlags: FeatureFlags = {
ENABLE_VARIABLE_CONNECTION_KEY: false,
ENABLE_PARTIAL_RENDERING_DEFAULT: false,
ENABLE_RELAY_CONTAINERS_SUSPENSE: false,
ENABLE_PRECISE_TYPE_REFINEMENT: false,
ENABLE_REACT_FLIGHT_COMPONENT_FIELD: false,
ENABLE_REQUIRED_DIRECTIVES: false,
ENABLE_GETFRAGMENTIDENTIFIER_OPTIMIZATION: false,
};
module.exports = RelayFeatureFlags;
|
Use setattr() instead of a direct access to __dict__
Closes Feature Request 3110077 "new style classes"
https://sourceforge.net/tracker/?func=detail&aid=3110077&group_id=196342&atid=957075 | """
from Thinking in Python, Bruce Eckel
http://mindview.net/Books/TIPython
Simple emulation of Java's 'synchronized'
keyword, from Peter Norvig.
"""
from threading import RLock
def synchronized(method):
def f(*args):
self = args[0]
self.mutex.acquire()
# print method.__name__, 'acquired'
try:
return apply(method, args)
finally:
self.mutex.release()
# print method.__name__, 'released'
return f
def synchronize(klass, names=None):
"""Synchronize methods in the given class.
Only synchronize the methods whose names are
given, or all methods if names=None."""
if type(names) == type(''):
names = names.split()
for (name, val) in klass.__dict__.items():
if callable(val) and name != '__init__' and \
(names == None or name in names):
# print "synchronizing", name
setattr(klass, name, synchronized(val))
class Synchronization(object):
# You can create your own self.mutex, or inherit from this class:
def __init__(self):
self.mutex = RLock()
| """
from Thinking in Python, Bruce Eckel
http://mindview.net/Books/TIPython
Simple emulation of Java's 'synchronized'
keyword, from Peter Norvig.
"""
from threading import RLock
def synchronized(method):
def f(*args):
self = args[0]
self.mutex.acquire()
# print method.__name__, 'acquired'
try:
return apply(method, args)
finally:
self.mutex.release()
# print method.__name__, 'released'
return f
def synchronize(klass, names=None):
"""Synchronize methods in the given class.
Only synchronize the methods whose names are
given, or all methods if names=None."""
if type(names) == type(''):
names = names.split()
for (name, val) in klass.__dict__.items():
if callable(val) and name != '__init__' and \
(names == None or name in names):
# print "synchronizing", name
klass.__dict__[name] = synchronized(val)
class Synchronization:
# You can create your own self.mutex, or inherit from this class:
def __init__(self):
self.mutex = RLock()
|
Add shift tag to exported enrollments | <!DOCTYPE html>
<html>
<table>
<tr>
<th>Course ID</th>
<th>Course</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Student E-mail</th>
<th>Enrollment Date</th>
<th>Shift</th>
</tr>
@foreach($enrollments as $enrollment)
<tr>
<td>{{ $enrollment->course->code }}</td>
<td>{{ $enrollment->course->name }}</td>
<td>{{ $enrollment->student->student_number }}</td>
<td>{{ $enrollment->student->user->name }}</td>
<td>{{ $enrollment->student->user->email }}</td>
<td>{{ $enrollment->student->created_at }}</td>
<td>{{ $enrollment->present()->getShiftTag('') }}</td>
</tr>
@endforeach
</table>
</html>
| <!DOCTYPE html>
<html>
<table>
<tr>
<th>Course ID</th>
<th>Course</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Student E-mail</th>
<th>Enrollment Date</th>
<th>Shift</th>
</tr>
@foreach($enrollments as $enrollment)
<tr>
<td>{{ $enrollment->course->code }}</td>
<td>{{ $enrollment->course->name }}</td>
<td>{{ $enrollment->student->student_number }}</td>
<td>{{ $enrollment->student->user->name }}</td>
<td>{{ $enrollment->student->user->email }}</td>
<td>{{ $enrollment->student->created_at }}</td>
<td>{{-- Shift field --}}</td>
</tr>
@endforeach
</table>
</html>
|
Add full url in js to get graph. | $(document).ready(function(){
var graph = Graph ();
function getGraph(url, btnLoading) {
$("#graph").html("");
url = url ? url : "/graph";
$('#graph-loading').show();
if (btnLoading) {
btnLoading.start();
}
$.get(APP_URL + url, function( data ) {
graph.createGraph(data);
$('#graph-loading').hide();
if (btnLoading) {
btnLoading.stop();
}
});
}
$(".updateGraph").click(function(e){
e.preventDefault();
$('.selected').removeClass('selected');
$(this).closest('tr').addClass('selected');
var l = Ladda.create(this);
getGraph($(this).attr('href'), l);
});
$('#expandAllBtn').click(function(e){
e.preventDefault();
graph.expandAll();
});
$('#collapseAllBtn').click(function(e){
e.preventDefault();
graph.collapseAll();
});
getGraph();
});
| $(document).ready(function(){
var graph = Graph ();
function getGraph(url, btnLoading) {
$("#graph").html("");
url = url ? url : "/graph";
$('#graph-loading').show();
if (btnLoading) {
btnLoading.start();
}
$.get(url, function( data ) {
graph.createGraph(data);
$('#graph-loading').hide();
if (btnLoading) {
btnLoading.stop();
}
});
}
$(".updateGraph").click(function(e){
e.preventDefault();
$('.selected').removeClass('selected');
$(this).closest('tr').addClass('selected');
var l = Ladda.create(this);
getGraph($(this).attr('href'), l);
});
$('#expandAllBtn').click(function(e){
e.preventDefault();
graph.expandAll();
});
$('#collapseAllBtn').click(function(e){
e.preventDefault();
graph.collapseAll();
});
getGraph();
});
|
Add 'today' translation for Bahasa | /**
* Bahasa translation for bootstrap-datetimepicker
* Azwar Akbar <azwar.akbar@gmail.com>
*/
;(function($){
$.fn.datetimepicker.dates['id'] = {
days: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"],
daysShort: ["Mgu", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Mgu"],
daysMin: ["Mg", "Sn", "Sl", "Ra", "Ka", "Ju", "Sa", "Mg"],
months: ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ags", "Sep", "Okt", "Nov", "Des"],
today: "Hari Ini",
suffix: [],
meridiem: []
};
}(jQuery));
| /**
* Bahasa translation for bootstrap-datetimepicker
* Azwar Akbar <azwar.akbar@gmail.com>
*/
;(function($){
$.fn.datetimepicker.dates['id'] = {
days: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"],
daysShort: ["Mgu", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Mgu"],
daysMin: ["Mg", "Sn", "Sl", "Ra", "Ka", "Ju", "Sa", "Mg"],
months: ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ags", "Sep", "Okt", "Nov", "Des"],
suffix: [],
meridiem: []
};
}(jQuery));
|
Allow setting thumbnail width & height. | var gm = require('gm'),
fs = require('fs'),
common = require('./common'),
root = process.argv[2],
width = process.argv[3] || 250,
height = process.argv[4] || 400
var TEASER_IMAGE_PATTERN = '.+-teaser';
var TEASER_FILE_NAME = '-teaser.jpg';
var createThumbnail = function(file) {
var outFile = file.slice(0, -4) + TEASER_FILE_NAME;
var image = gm(file)
.resize(width, height)
.write(outFile, function(err) {
if(err) {
console.log(err);
}
else {
console.log('Creating: ' + outFile);
}
});
}
if(!root) {
console.log('Specify a file or directory');
return;
}
var isFile = null;
var isDirectory = null;
try {
var stats = fs.statSync(root);
isFile = stats.isFile();
isDirectory = stats.isDirectory();
}
catch(e) {
console.log(e);
}
if(isDirectory) {
var results = [];
common.walk(root, results, function(error) {
if(error) {
throw error;
}
results = results.filter(function(value) {
return value.search(TEASER_IMAGE_PATTERN) === -1;
});
results.forEach(createThumbnail);
});
}
else if(isFile) {
createThumbnail(root);
}
| var gm = require('gm'),
fs = require('fs'),
common = require('./common'),
root = process.argv[2];
var TEASER_IMAGE_PATTERN = '.+-teaser';
var TEASER_FILE_NAME = '-teaser.jpg';
var createThumbnail = function(file) {
var outFile = file.slice(0, -4) + TEASER_FILE_NAME;
var image = gm(file)
.resize(400, 400)
.write(outFile, function(err) {
if(err) {
console.log(err);
}
else {
console.log('Creating: ' + outFile);
}
});
}
if(!root) {
console.log('Specify a file or directory');
return;
}
var isFile = null;
var isDirectory = null;
try {
var stats = fs.statSync(root);
isFile = stats.isFile();
isDirectory = stats.isDirectory();
}
catch(e) {
console.log(e);
}
if(isDirectory) {
var results = [];
common.walk(root, results, function(error) {
if(error) {
throw error;
}
results = results.filter(function(value) {
return value.search(TEASER_IMAGE_PATTERN) === -1;
});
results.forEach(createThumbnail);
});
}
else if(isFile) {
createThumbnail(root);
}
|
Use startswith in favor of indexing | from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
if self.raw['path'][0].startswith('/'):
return self.raw['path']
return '/' + self.raw['path']
@property
def modified(self):
return self.raw.get('modified')
@property
def size(self):
return self.raw.get('size')
@property
def content_type(self):
return None
@property
def extra(self):
return {
'downloads': self.raw['downloads']
}
class OsfStorageFolderMetadata(BaseOsfStorageMetadata, metadata.BaseFolderMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
return self.raw['path']
| from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
if self.raw['path'][0] != '/':
return '/' + self.raw['path']
return self.raw['path']
@property
def modified(self):
return self.raw.get('modified')
@property
def size(self):
return self.raw.get('size')
@property
def content_type(self):
return None
@property
def extra(self):
return {
'downloads': self.raw['downloads']
}
class OsfStorageFolderMetadata(BaseOsfStorageMetadata, metadata.BaseFolderMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
return self.raw['path']
|
Add supported Python versions to classifier troves | from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
setup(
name='django-model-utils',
version='1.3.1.post1',
description='Django model mixins and utilities',
long_description=long_description,
author='Carl Meyer',
author_email='carl@oddbird.net',
url='https://github.com/carljm/django-model-utils/',
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
],
zip_safe=False,
tests_require=["Django>=1.2"],
test_suite='runtests.runtests'
)
| from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
setup(
name='django-model-utils',
version='1.3.1.post1',
description='Django model mixins and utilities',
long_description=long_description,
author='Carl Meyer',
author_email='carl@oddbird.net',
url='https://github.com/carljm/django-model-utils/',
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
zip_safe=False,
tests_require=["Django>=1.2"],
test_suite='runtests.runtests'
)
|
Fix regular expression to match all after | | <?php
namespace Oneup\Contao\J2B;
class Runner
{
public function moveJs(\PageModel $objPage, \LayoutModel $objLayout, \PageRegular $objPageRegular)
{
if ('FE' === TL_MODE) {
foreach($GLOBALS['TL_JAVASCRIPT'] as $index => $javascript) {
$javascript = preg_replace('/\|.*/', '', $javascript);
$GLOBALS['TL_BODY'][] = '<script type="text/javascript" src="' . $javascript . '"></script>';
unset($GLOBALS['TL_JAVASCRIPT'][$index]);
}
}
}
}
| <?php
namespace Oneup\Contao\J2B;
class Runner
{
public function moveJs(\PageModel $objPage, \LayoutModel $objLayout, \PageRegular $objPageRegular)
{
if ('FE' === TL_MODE) {
foreach($GLOBALS['TL_JAVASCRIPT'] as $index => $javascript) {
$javascript = preg_replace('/\|static/', '', $javascript);
$GLOBALS['TL_BODY'][] = '<script type="text/javascript" src="' . $javascript . '"></script>';
unset($GLOBALS['TL_JAVASCRIPT'][$index]);
}
}
}
}
|
Add application.properties to hot reload | /*
* Copyright 2018 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.quarkus.deployment.steps;
import java.util.Arrays;
import java.util.List;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.HotDeploymentConfigFileBuildItem;
class DevModeBuildStep {
@BuildStep
List<HotDeploymentConfigFileBuildItem> config() {
return Arrays.asList(new HotDeploymentConfigFileBuildItem("META-INF/microprofile-config.properties"),
new HotDeploymentConfigFileBuildItem("application.properties"));
}
}
| /*
* Copyright 2018 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.quarkus.deployment.steps;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.HotDeploymentConfigFileBuildItem;
class DevModeBuildStep {
@BuildStep
HotDeploymentConfigFileBuildItem config() {
return new HotDeploymentConfigFileBuildItem("META-INF/microprofile-config.properties");
}
}
|
Check if the session is already started | <?php
namespace DaMess\Http;
use Aura\Session\Session;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
final class SessionMiddleware
{
/**
* @var Session
*/
protected $session;
/**
* @param Session $session
*/
public function __construct(Session $session)
{
$this->session = $session;
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
if (!$this->session->isStarted()) {
$this->session->start();
}
$request = $request->withAttribute('session', $this->session);
if ($next) {
return $next($request, $response);
}
return $response;
}
}
| <?php
namespace DaMess\Http;
use Aura\Session\Session;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
final class SessionMiddleware
{
/**
* @var Session
*/
protected $session;
/**
* @param Session $session
*/
public function __construct(Session $session)
{
$this->session = $session;
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
$this->session->start();
$request = $request->withAttribute('session', $this->session);
if ($next) {
return $next($request, $response);
}
return $response;
}
}
|
Remove the periods from the region tags. | <?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START index_php]
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/', function () {
return 'Hello World';
});
$app->get('/goodbye', function () {
return 'Goodbye World';
});
// @codeCoverageIgnoreStart
if (PHP_SAPI != 'cli') {
$app->run();
}
// @codeCoverageIgnoreEnd
return $app;
// [END index_php]
| <?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START index.php]
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/', function () {
return 'Hello World';
});
$app->get('/goodbye', function () {
return 'Goodbye World';
});
// @codeCoverageIgnoreStart
if (PHP_SAPI != 'cli') {
$app->run();
}
// @codeCoverageIgnoreEnd
return $app;
// [END index.php]
|
chore(testactular): Add Chrome browser back in |
// base path, that will be used to resolve files and exclude
basePath = '.';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'misc/test-lib/jquery-1.8.2.min.js',
'misc/test-lib/angular.js',
'misc/test-lib/angular-mocks.js',
'misc/test-lib/helpers.js',
'src/**/*.js',
'template/**/*.js'
];
// list of files to exclude
exclude = [
];
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers = [
'Chrome'
];
// test results reporter to use
// possible values: dots || progress
reporter = 'progress';
// web server port
port = 9018;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
|
// base path, that will be used to resolve files and exclude
basePath = '.';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'misc/test-lib/jquery-1.8.2.min.js',
'misc/test-lib/angular.js',
'misc/test-lib/angular-mocks.js',
'misc/test-lib/helpers.js',
'src/**/*.js',
'template/**/*.js'
];
// list of files to exclude
exclude = [
];
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers = [];
// test results reporter to use
// possible values: dots || progress
reporter = 'progress';
// web server port
port = 9018;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
|
Use String.valueOf() instead. It's more robust against Object values in the MDC. | package io.tracee.backend.jbosslogging;
import io.tracee.MDCLike;
import org.jboss.logging.MDC;
import java.util.HashMap;
import java.util.Map;
final class JbossLoggingMdcLikeAdapter implements MDCLike {
@Override
public boolean containsKey(String key) {
return MDC.get(key) != null;
}
@Override
public void put(String key, String value) {
MDC.put(key, value);
}
@Override
public String get(String key) {
return String.valueOf(MDC.get(key));
}
@Override
public void remove(String key) {
MDC.remove(key);
}
@Override
public Map<String, String> getCopyOfContext() {
final Map<String, Object> map = MDC.getMap();
final Map<String, String> copy = new HashMap<String, String>(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
copy.put(entry.getKey(), String.valueOf(entry.getValue()));
}
return copy;
}
}
| package io.tracee.backend.jbosslogging;
import io.tracee.MDCLike;
import org.jboss.logging.MDC;
import java.util.HashMap;
import java.util.Map;
final class JbossLoggingMdcLikeAdapter implements MDCLike {
@Override
public boolean containsKey(String key) {
return MDC.get(key) != null;
}
@Override
public void put(String key, String value) {
MDC.put(key, value);
}
@Override
public String get(String key) {
return (String) MDC.get(key);
}
@Override
public void remove(String key) {
MDC.remove(key);
}
@Override
public Map<String, String> getCopyOfContext() {
final Map<String, Object> map = MDC.getMap();
final Map<String, String> copy = new HashMap<String, String>(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (!(entry.getValue() instanceof String)) continue;
copy.put(entry.getKey(), (String) entry.getValue());
}
return copy;
}
}
|
Fix benjamin facade safetypay method call | <?php
class Ebanx_Gateway_Model_Peru_Safetypay extends Ebanx_Gateway_Payment
{
protected $_code = 'ebanx_safetypay';
protected $_formBlockType = 'ebanx/form_safetypay';
protected $_infoBlockType = 'ebanx/info_safetypay';
public function __construct()
{
parent::__construct();
$this->gateway = $this->ebanx->safetyPayCash();
}
public function initialize($paymentAction, $stateObject)
{
$safetyPayType = Mage::app()->getRequest()->getPost()['ebanx_safetypay_type'];
$this->gateway = $this->ebanx->{'safetyPay' . $safetyPayType}();
parent::initialize($paymentAction, $stateObject);
}
public function isAvailable($quote = null)
{
return parent::isAvailable() && in_array($this->getCode(), explode(',', $this->configs['payment_methods_peru']));
}
}
| <?php
class Ebanx_Gateway_Model_Peru_Safetypay extends Ebanx_Gateway_Payment
{
protected $_code = 'ebanx_safetypay';
protected $_formBlockType = 'ebanx/form_safetypay';
protected $_infoBlockType = 'ebanx/info_safetypay';
public function __construct()
{
parent::__construct();
$this->gateway = $this->ebanx->safetyPayCash();
}
public function initialize($paymentAction, $stateObject)
{
$safetyPayType = Mage::app()->getRequest()->getPost()['ebanx_safetypay_type'];
$this->gateway = $this->ebanx->safetyPay($safetyPayType);
parent::initialize($paymentAction, $stateObject);
}
public function isAvailable($quote = null)
{
return parent::isAvailable() && in_array($this->getCode(), explode(',', $this->configs['payment_methods_peru']));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.